Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving column to next line using Flex Box

Tags:

html

css

flexbox

I have three columns, ordering 1,2,3.

HTML

<div class="flex-container">
    <div class="item first">1</div>
    <div class="item second">2</div>
    <div class="item third">3</div>
</div>

CSS

.flex-container {
    display: flex;
}
.item {
    background: orange;
    padding: 10px auto;
    color: #fff;
    font-family: arial;
    flex-grow: 100;
    flex-shrink: 50;
    text-align: center;
}
.first {
    order: 1;
}
.second {
    order: 2;
}
.third {
    order: 3;
}

What I want when I switch to mobile screen columns should display like this;

1 3
2 

Media Query

/* Too narrow to support three columns */
 @media all and (max-width: 640px) {
    .second {
        order: 3;
        /* And go to second line */
    }
    .third {
        order: 2;
    }
}

Column two should move to next line.

Fiddle

How can I do this?

like image 998
Aamir Shahzad Avatar asked May 26 '14 06:05

Aamir Shahzad


People also ask

How do you move the item to the next line in Flex?

Inserting a line-breaking flex itemUsing an element to break to a new flex row comes with an interesting effect: we can skip specifying the width of any item in our flex layout and rely completely on the line breaks to define the flow of our grid.

How do you break a flex column in CSS?

We can set break-before: column; on each 'head' element, where the column value means: Always force a column break before the generated box.

How do you align a column in Flex?

The flex columns can be aligned left or right by using the align-content property in the flex container class. The align-content property changes the behavior of the flex-wrap property. It aligns flex lines. It is used to specify the alignment between the lines inside a flexible container.


1 Answers

By default the flex-direction is row, you should change it to column and use flex-wrap:wrap (we can write it shortly using flex-flow:column wrap). Note that to make the third column jump to the next column, the .flex-container's height should be large enough to contain all the .first and .second but not enough to contain all 3 items. With just that, you can recognize that the .third expand/strecth the whole space (on the second column). So you can try setting its flex-grow:0 and use flex-basis:50%. Here is the code:

@media all and (max-width: 640px) {
  .flex-container {
    flex-flow:column wrap;  
    height:40px;   
  }    
  .third {
    flex-grow:0;
    flex-basis:50%;
  }
}

Demo.

Here is another solution using column box layout instead of flex-box, it works very well indeed.

Demo 2

like image 124
King King Avatar answered Sep 19 '22 14:09

King King