Imagine the following layout, where the dots represent the space between the boxes:
[Left box]......[Center box]......[Right box]
If the left and right boxes would be exactly the same size, I get the desired effect. However when one of the two is a different size the centered box is not truly centered anymore. Is there anyone that can help me?
Here's a method using flexbox to center the middle item, regardless of the width of siblings.
Key features:
Use nested flex containers and auto margins:
.container {
display: flex;
}
.box {
flex: 1;
display: flex;
justify-content: center;
}
.box:first-child > span { margin-right: auto; }
.box:last-child > span { margin-left: auto; }
/* non-essential */
.box {
align-items: center;
border: 1px solid #ccc;
background-color: lightgreen;
height: 40px;
}
p {
text-align: center;
margin: 5px 0 0 0;
}
short text
centered text
loooooooooooooooong text
↑
true center
Here's how it works:
.container) is a flex container..box) is now a flex item..box item is given flex: 1 in order to distribute container space equally (more details).justify-content: center.span element is a centered flex item.auto margins to shift the outer spans left and right.You could also forgo justify-content and use auto margins exclusively.
But justify-content can work here because auto margins always have priority.
8.1. Aligning with auto margins
Prior to alignment via
justify-contentandalign-self, any positive free space is distributed to auto margins in that dimension.