微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – 布局可能吗? Flexbox vs Float布局,包含多个列和行

我很好奇这个布局是否可以使用flexBox.我似乎无法解决div 3& 4属于#2.浮点数非常简单,只是好奇我是否遗漏了一些可能对flexBox有帮助的属性.

布局

+-------+-------+-------+
| div 1 |     div 2     |
+       +-------+-------+
|       | div 3 | div 4 |
+-------+-------+-------+

标记

<div class="features">
  <div class="feature feature-1">1</div>
  <div class="feature feature-2">2</div>
  <div class="feature feature-3">3</div>
  <div class="feature feature-4">4</div>
</div>

演示

http://codepen.io/mikevoermans/pen/xbWvJJ?editors=110

解决方法

FlexBox不喜欢通过多个列或行扩展的flex项,因为实际上flexBox没有网格概念.

但是,使用一些技巧,您可以实现此布局(以及more complicated ones):

>使用行布局

┌─┬─┬─┬─┐
│1│2│3│4│
└─┴─┴─┴─┘

>使用flex-wrap:换行允许换行.
>使用伪元素在2之后强制换行

┌─┬─┐
│1│2│
├─┼─┤
│3│4│
└─┴─┘

>对所有弹性项目使用flex:1.

┌─────────┬─────────┐
│1        │2        │
├─────────┼─────────┤
│3        │4        │
└─────────┴─────────┘

>设置margin-left:50%到3

┌─────────┬─────────┐
│1        │2        │
└─────────┼────┬────┤
          │3   │4   │
          └────┴────┘

>设置高度:200px,到2,3和4.设置高度:400px到1.

┌─────────┬─────────┐
│1        │2        │
│         ├─────────┘
│         │
└─────────┼────┬────┐
          │3   │4   │
          └────┴────┘

>设置margin-bottom:-200px为1:

┌─────────┬─────────┐
│1        │2        │
│         ├────┬────┤
│         │3   │4   │
└─────────┴────┴────┘

>由于您有边框,因此请在所有方框上使用Box-sizing:border-Box以使高度包含边框.否则1需要高度:416px; margin-bottom:-216px.
>注意flexBox引入auto作为min-width的新初始值.这可能会让内容迫使一些盒子增长.这会打破布局,所以禁用min-width:0或将溢出设置为除可见之外的任何内容.

这是代码

.features {
  display: flex;
  flex-flow: row wrap;
}
.feature {
  background: #ccc;
  border: 8px solid #fff;
  height: 200px;
  Box-sizing: border-Box;
  min-width: 0;
  flex: 1;
}
.feature-1 {
  /* Make it taller without increasing the height of the flex line */
  height: 400px;
  margin-bottom: -200px;
}
.features:after {
  /* Force line break */
  content: '';
  width: 100%;
}
.feature-2 ~ .feature {
  /* Place 3 and 4 after the line break */
  order: 1;
}
.feature-3 {
  margin-left: 50%;
}
<div class="features">
  <div class="feature feature-1">1</div>
  <div class="feature feature-2">2</div>
  <div class="feature feature-3">3</div>
  <div class="feature feature-4">4</div>
</div>

但是,修改HTML以便嵌套FlexBox会更容易.

#wrapper {
  height: 400px;
}
.flex {
  display: flex;
}
.column {
  flex-direction: column;
}
.flex > div {
  min-width: 0;
  flex: 1;
}
.item {
  background: #ccc;
  border: 8px solid #fff;
}
<div id="wrapper" class="flex row">
  <div class="item">1</div>
  <div class="flex column">
    <div class="item">2</div>
    <div class="flex row">
      <div class="item">3</div>
      <div class="item">4</div>
    </div>
  </div>
</div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。