问题
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