Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox - move middle element to the next line (without media query)

Tags:

css

flexbox

What I want to achieve (but without the media query):

JsFiddle

@media all and (max-width: 600px) {
  #wrapper {
    flex-wrap:wrap;
    height: 100px;
  }

  .center {
    width: 100%;
    order: 3;
  }

  .left{
    width: 50%;
  }

  .right {
    width:50%;
    order:2;
  }
}

I have 3 elements inside a wrapper, all shrinked. At desktop size, there is some space left over, however when I resize my window to a smaller dimension, at some point, elements run out of space. When that happens, I want to put the middle element to the next line. I have a solution, where the third element goes to the next line, and JSFiddle solution, where the second element goes to the next line, but always at the same static width.

So is it possible to put the middle element to the next line, when all three shrinked elements run out of space?

like image 668
Kres Avatar asked Jan 04 '18 21:01

Kres


People also ask

How do you push the flex item to the next row?

Since we've said that . break should take up 100% of the width of the container (because we set flex-basis: 100% ), the breaking flex item needs to sit on its own row to accomplish that. It can't share a row with the first item so it will break to a new row, which will leave the first item alone on one row.

How do you position flex items?

Justify Content Flex Start positions element at the start of the page. Flex End sets the element to the end of the page. Space Around arranges the items evenly but with spaces between them. The spaces will be equal among all the elements inside a flex-box container, but not outside them.

What is flex wrap?

The flex-wrap CSS property sets whether flex items are forced onto one line or can wrap onto multiple lines. If wrapping is allowed, it sets the direction that lines are stacked.


1 Answers

You can definitely wrap the line without media queries by using flex-wrap, flex-grow, flex-shrink and flex-basis to specify a minimum width that any given item should have:

#wrapper{
  display: flex;
  width: 100%;
  height: 50px;
  align-items: center;
  text-align: center;
  flex-wrap: wrap;
}

.right{
  width: 20%;
  background-color: blue;
  order: 3;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 200px;
}

But it's not possible to change the flex-order based solely on whether the elements "fit". For that you definitely need a media query.

like image 184
Wedge Avatar answered Oct 18 '22 09:10

Wedge