How to get three columns and two rows (1 x 2 x 2) with flexbox

爱⌒轻易说出口 提交于 2019-12-25 08:47:18

问题


I want to achieve the following result with Flex if possible. Know how to get that done with CSS, but not quite familiar with Flex. The reason why I want to do that in flex it to force myself write concise and more maintainable codes.

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


If you can set fixed height on parent element then you can do this with Flexbox. You can set flex-direction: column with flex-wrap: wrap and make first child element take 100% of height.

* {
  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>

New option to create this layout is Grid-layout, you just have to set grid-row: span 2 on first child element.

* {
  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>


来源:https://stackoverflow.com/questions/45442974/how-to-get-three-columns-and-two-rows-1-x-2-x-2-with-flexbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!