如何使用flexbox获得三列和两行(1 x 2 x 2)

时间:2017-08-01 16:21:26

标签: html css css3 flexbox

如果可能,我希望使用Flex获得以下结果。知道如何用CSS完成,但不熟悉Flex。我之所以想要在flex中这样做,是为了强迫自己编写简洁且更易于维护的代码。

enter image description here

.banner {
  width: 20%;
  height: 100%;
  position: relative;
  float: left;
  overflow: hidden;
}

.item {
  height: 50%;
  width: 33.33%;
  float: left;
  position: relative;
}

.inner-item-block {
  height: 100%;
  width: 80%;
  float: left;
  position: relative;
}

.inner-line {
  border-right: 1px solid #dedede;
  border-bottom: 1px solid #dedede;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center; /* center child elements */
}
<div class="item-block">
  <div class="banner banner3">
  </div>
  <div class="inner-item-block">
    <div class="item">
      <div class="inner-line">
      </div>
    </div>

    <div class="item">
      <div class="inner-line">
      </div>
    </div>

    <div class="item">
      <div class="inner-line">
      </div>
    </div>

    <div class="item">
      <div class="inner-line">
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

如果您可以在父元素上设置固定高度,则可以使用Flexbox执行此操作。您可以使用flex-direction: column设置flex-wrap: wrap,并使第一个子元素占据100%的高度。

* {
  box-sizing: border-box;
}
body {
  margin: 0;
}
.parent {
  display: flex;
  flex-direction: column;
  height: 100vh;
  flex-wrap: wrap;
}
.parent > div {
  flex: 0 0 50%;
  width: 33.33%;
  border: 1px solid black;
}
div.first {
  flex: 0 0 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="parent">
  <div class="first">First</div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

创建此布局的新选项是网格布局,您只需在第一个子元素上设置grid-row: span 2

* {
  box-sizing: border-box;
}
body {
  margin: 0;
}
.parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: minmax(100px, auto);
}
.parent > div {
  border: 1px solid black;
}
div.first {
  grid-row: span 2;
}
<div class="parent">
  <div class="first">First</div><div></div><div></div><div></div><div></div>
  <div class="first">First</div><div></div><div></div><div></div><div></div>
</div>