Flex masonry effect not wrapping properly

南笙酒味 提交于 2019-12-25 01:29:38

问题


I have the following layout that I'm trying to achieve with flex, but just can't seem to get it:

* {
  box-sizing: border-box;
}

.box {
  border: 1px solid black;
  width: 50%;
  padding-top: 25%;
  float: left;
}

.box:first-child {
  padding-top: 50%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

If I try to use flex-direction row, it wraps the last two boxes under the first left box

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.box {
  border: 1px solid black;
  width: 50%;
  padding-top: 25%;
}

.box:first-child {
  padding-top: 50%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

If I use flex direction column, I get closer but have to set a height which means I lose responsiveness

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:400px;
  width:100%;
}

.box {
  border: 1px solid black;
  width: 50%;
  padding-top: 25%;
}

.box:first-child {
  padding-top: 50%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Is there a way to achieve this layout using flex without having a fixed height or changing the html structure?


回答1:


Using flexbox you can consider some hack to approximate this. One trick is to have two rows (keep the row direction) and use negative margin on the first element to make it overlap the second row:

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.box {
  outline: 1px solid black;
  width: 50%;
  padding-top: 25%;
}

.box:first-child {
  padding-top: 25%;
  margin-bottom:-25%;
}

.box:nth-last-child(-n+2) {
  width: 25%;
}
.box:nth-child(3) {
  margin-left:auto;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


来源:https://stackoverflow.com/questions/54632489/flex-masonry-effect-not-wrapping-properly

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