问题
[ 1 ] [ 2 ] [ 3 ] [ 4 ]
I have four DIVs floating left (above), using simple CSS: float:left; width:128px;height:128px
As I narrow the screen, the last DIV jumps correctly onto the next line:
[ 1 ] [ 2 ] [ 3 ]
[ 4 ]
But what I'd really like is for the last two blocks to jump onto the next line in order to keep the look symmetrical:
[ 1 ] [ 2 ]
[ 3 ] [ 4 ]
And when the screen narrow further, the blocks stack one above the other:
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]
回答1:
Group [3] and [4] together in a div (and [1] and [2] if you desire). Give it a max width, but auto height. That way, when the screen narrows, the two divs should move together side by side, but jump down when the screen gets narrower.
ex:
.contain {
max-width:256px;
height:auto;
}
<div class="contain">
<div class="div3">contents</div>
<div class="div4">contents</div>
</contain>
回答2:
Here is one way of doing it using media queries.
The trick is to pick a suitable break point for max-width
, for example, 610px, and then use the nth-child
selected to clear the float at every 3rd child element beginning with the 3rd one.
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries
.box {
float: left;
width: 128px;
height: 128px;
background-color: grey;
margin: 10px;
box-sizing: border-box;
border: 2px solid black;
}
.container-box {
border: 1px dotted blue;
overflow: auto;
box-sizing: borderbox;
}
@media (max-width: 610px) {
.box {
background-color: yellow;
}
.box:nth-child(2n+3) {
background-color: red;
clear: left;
}
}
<div class="container-box">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
回答3:
Try wrapping 2 divs into a container div then set the width of that container div to be twice the size of each regular div.
<div class="container-box">
<div class="box">1</div>
<div class="box">2</div>
</div>
<div class="container-box">
<div class="box">3</div>
<div class="box">4</div>
</div>
.box {
float:left;
width:128px;
height:128px;
background: grey;
}
.container-box {
float: left;
width: 256px;
height: 128px;
}
Here's a link to a fiddle: https://jsfiddle.net/wfhk1fak/1/
Hope this helps.
来源:https://stackoverflow.com/questions/40119510/4-floating-divs-that-respond-symmetrically-on-narrowing-screens-with-css