I am trying to find a way to distribute an uneven number of elements across the horizontal axis that satisfies the following:
- the left border of the first child overlaps the left border of the container
- the right border of the last child overlaps the right border of the container
- uneven number of children (that is, there exists a middle item)
- the middle item must be properly centered
- the remaining items (i.e. items between the first and middle items and between the middle and last items) are evenly distributed
- the items can vary in width (no fixed width)
Here is an example of the problem I encounter (4th condition not satisfied) with my current implementation:
#container {
display: flex;
justify-content: space-between;
}
#container > div {
background-color: black;
}
#container > div:nth-child(1) {
width: 100px;
height: 20px;
}
#container > div:nth-child(2) {
width: 80px;
height: 30px;
}
#container > div:nth-child(3) {
width: 50px;
height: 50px;
}
#container > div:nth-child(4) {
width: 40px;
height: 30px;
}
#container > div:nth-child(5) {
width: 90px;
height: 10px;
}
p {
width: 100%;
text-align: center;
}
<div id="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<p>
↑<br>
actual center
</p>
Another possible approach is given here:
#container {
display: flex;
}
#container > div {
flex: 1;
display: flex;
justify-content: center;
}
#container > div > div {
background-color: black;
}
#container > div:nth-child(1) > div {
width: 100px;
height: 20px;
margin-right: auto;
}
#container > div:nth-child(2) > div {
width: 80px;
height: 30px;
}
#container > div:nth-child(3) > div {
width: 50px;
height: 50px;
}
#container > div:nth-child(4) > div {
width: 40px;
height: 30px;
}
#container > div:nth-child(5) > div {
width: 90px;
height: 10px;
margin-left: auto;
}
p {
width: 100%;
text-align: center;
}
<div id="container">
<div><div></div></div>
<div><div></div></div>
<div><div></div></div>
<div><div></div></div>
<div><div></div></div>
</div>
<p>
↑<br>
center
</p>
While aesthetically more pleasing, this is not ideal because the second and fourth divs are centered relative to their given flow space instead of their surrounding space:
By contrast, here is what I am trying to achieve: