且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用flexbox防止下一行占用上一行中最高项目的高度?

更新时间:2022-10-17 23:15:19

Flexbox无法以灵活的方式自行完成。

正如你自己提到的那样,CSS Grid可以做到这一点,不过既然你不想这样做,这个建议是基于这样的假设:你在较窄的屏幕上需要 b 在底部。

通过最初使用 float ,然后在某个断点处,swap在 float 显示:flex 之间,很容易利用两者。



此外,使用Flexbox的顺序属性,可以很容易地按照任意顺序定位元素,并避免使用脚本并获得合理的浏览器支持。



更新的codepen

Stack snippet

* {box-sizing:border-box; } .cont {background:gold; overflow:hidden;} .a,.b,.c {width:45%;填充:10px; float:left;}。a {background:red;}。b {background:blue;白颜色; float:right;}。c {background:orange;} @ media(max-width:500px){.a,.b,.c {width:auto; float:none; } .b {order:1; } .cont {display:flex; flex-direction:列; }}

 < div class =cont> < div class =a> A< / div> < div class =b> B< br>更多B< / div> < div class =c> C< / div>< / div>  

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

<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

<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.

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>