I've the following HTML and CSS.
.container-box { width: 200px; display: flex; flex-direction: row; justify-content: space-between; background-color: red; margin:50px; } .box { background-color: #9009A0; height: 50px; width: 50px; }
Which gives this layout:
The first layout for multiple items does what I expect, but how can I change the second to position the element in center as it only has one element?
See this codepen: https://codepen.io/dennismadsen/pen/oNvqjjV
For cases where you have one item in the container, you can use the :only-child
pseudo-class.
Add this to your code:
.box:only-child { margin: 0 auto; }
.box:only-child { margin: 0 auto; }
.container-box {
width: 200px;
display: flex;
flex-direction: row;
justify-content: space-between;
background-color: red;
margin: 50px;
}
.box {
background-color: #9009A0;
height: 50px;
width: 50px;
}
.box:only-child {
margin: 0 auto;
}