How to specify an element after which to wrap in css flexbox?

theazureshadow picture theazureshadow · Oct 24, 2013 · Viewed 151.7k times · Source

I don't think this is part of the flexbox standard yet, but is there maybe a trick to suggest or force wrapping after a certain element? I'd like to respond to different page sizes and wrap a list differently without extra markup, so that rather than having (for example) orphaned menu items on the next line, I break in the middle of the menu.

Here's the starting html:

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

And css:

ul {
    display: flex;
    flex-wrap: wrap;
}

I'd love something like the following:

/* inside media query targeting width */
li:nth-child(2n) {
    flex-break: after;
}

See the jsfiddle for a more complete setup: http://jsfiddle.net/theazureshadow/ww8DR/

Answer

luksak picture luksak · May 5, 2015

You can accomplish this by setting this on the container:

ul {
    display: flex;
    flex-wrap: wrap;
}

And on the child you set this:

li:nth-child(2n) {
    flex-basis: 100%;
}

This causes the child to make up 100% of the container width before any other calculation. Since to container is set to break in case there is not enough space it does so before and after this child.