Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always wrap at least two items with flexbox

Tags:

css

flexbox

Take a look at this example

It has a flexbox container with flex-flow: row wrap; to wrap all items. This is almost what I want.

When it starts to wrap, item number 6 wraps to the second line:

1 2 3 4 5
    6

But always I want to wrap at least two items when it starts to wrap so you'll never have a single items on a line:

1 2 3 4
  5 6
like image 674
Jayne Mast Avatar asked May 22 '15 07:05

Jayne Mast


People also ask

How do you force a flexbox wrap?

Making things wrap If you want to cause them to wrap once they become too wide you must add the flex-wrap property with a value of wrap , or use the shorthand flex-flow with values of row wrap or column wrap . Items will then wrap in the container.

How do you wrap text in flexbox?

As you only want the text itself to wrap you need to use flex-wrap: nowrap; to keep . right on the same line. The text will automatically wrap when there is not enough space.

Why is flexbox not wrapping?

If you are using flexbox and want the content to wrap, you must specify flex-wrap: wrap . By default flex items don't wrap. To have the images be three-across, you should specify flex-basis: 33.33333% .


1 Answers

While not the most elegant solution, you could wrap the last two elements in another flexbox:

<html>
    <head>
        <style>
            .flex {
                display: flex;
                flex-wrap: wrap;
            }
            .flex > div {
                flex: 1 0 auto;
                padding: 20px;
                text-align: center;
            }
            .flex .flex {
                padding: 0;
                flex-grow: 2;
            }
        </style>
    </head>
    <body>
        <div class="flex">
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div class="flex">
                <div>5</div>
                <div>6</div>
            </div>
        </div>
    </body>
</html>

See a pen here: https://codepen.io/anon/pen/prodVd

like image 99
Rolf Avatar answered Sep 21 '22 02:09

Rolf