htmlcssflexboxcentering

Keep the middle item centered when side items have different widths


enter image description here

Imagine the following layout, where the dots represent the space between the boxes:

[Left box]......[Center box]......[Right box]

When I remove the right box, I like the center box to still be in the center, like so:

[Left box]......[Center box].................

The same goes for if I would remove the left box.

................[Center box].................

Now when the content within the center box gets longer, it will take up as much available space as needed while remaining centered. The left and right box will never shrink and thus when where is no space left the overflow:hidden and text-overflow: ellipsis will come in effect to break the content;

[Left box][Center boxxxxxxxxxxxxx][Right box]

All the above is my ideal situation, but I have no idea how to accomplish this effect. Because when I create a flex structure like so:

.parent {
    display : flex; // flex box
    justify-content : space-between; // horizontal alignment
    align-content   : center; // vertical alignment
}

If the left and right box would be exactly the same size, I get the desired effect. However when one of the two is from a different size the centered box is not truly centered anymore.

Is there anyone that can help me?

Update

A justify-self would be nice, this would be ideal:

.leftBox {
     justify-self : flex-start;
}

.rightBox {
    justify-self : flex-end;
}

Solution

  • The key is to use flex-basis. Then the solution is simple as:

    .parent {
        display: flex;
        justify-content: space-between;
    }
    
    .left, .right {
       flex-grow: 1;
       flex-basis: 0;
    }
    

    CodePen is available here.