Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

html - Prevent next row taking up height of tallest item in previous row with flexbox?

I made a layout with flexbox consisting of 2 columns. When everything is the same height it works fine:

https://codepen.io/anon/pen/rJZeJm

enter image description here

<div class="cont">
  <div class="a">
    A
  </div>
  <div class="b">B</div>
  <div class="c">C</div>
</div>

* {
  box-sizing: border-box;  
}

.cont {
  width: 400px;
  background: gold;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
}

.a,
.b,
.c {
  width: 45%;
  padding: 10px;
}

.a {
  background: red;
}

.b {
  background: blue;
  color: white;
}

.c {
  background: orange;
}

However in reality div.b may be taller than div.a, but I don't want the height of div.a or the position of div.c to change:

https://codepen.io/anon/pen/KQxzoz

enter image description here

<div class="cont">
  <div class="a">
    A
  </div>
  <div class="b">
    B
    <br>
    More B
  </div>
  <div class="c">C</div>
</div>

Can I achieve my desired layout with flexbox? Im sure grid could do this but I'm reluctant to use it as its still not properly supported in IE.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Flexbox can't do that by itself in a flexible way.

As you mentioned yourself, CSS Grid can do this, though since you didn't want that, this suggestion is based on the assumption that you at narrower screens want the b to be at the bottom.

By simply initially use float, and then at a certain break point, swap between float and display: flex, it is very easy to take advantage of both.

Additionally, using Flexbox's order property, one can easily position the elements in any desired order, and with this avoid script and get a reasonable level of browser support.

Updated codepen

Stack snippet

* {
  box-sizing: border-box;  
}

.cont {
  background: gold;
  overflow: hidden;
}

.a,
.b,
.c {
  width: 45%;
  padding: 10px;
  float: left;
}

.a {
  background: red;
}

.b {
  background: blue;
  color: white;
  float: right;
}

.c {
  background: orange;
}

@media (max-width: 500px) {
  .a,
  .b,
  .c {
    width: auto;
    float: none;
  }
  .b {
    order: 1;
  }
  .cont {
    display: flex;
    flex-direction: column;
  }
}
<div class="cont">
  <div class="a">
    A
  </div>
  <div class="b">
    B
    <br>
    More B
  </div>
  <div class="c">C</div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...