我在处理新网站的显示时出现问题。基本上,所有内容都将显示在2列中,当从较小的屏幕查看时,这将减少到1。
当我向这些框添加内容时,第一个"列"在第二行上低于第一行"行"上的第二个元素,我希望它能使我的下一行向下保持其直接位于其上方的元素,而不是最后解析的元素。
以下是我的问题的一个例子:
body{
background-color:lightgray;
}
.box{
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width:48%;
margin:1%;
padding:10px;
background-color:white;
display:inline-block;
float:left;
}

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="box">
<h1>Box 1</h1>
Test content 1
</div>
<div class="box">
<h1>Box 2</h1>
its a bit longer<br/>
than the last one<br/>
<br/>
its a lot longer<br/>
than the last one actually<br/>
</div>
<div class="box">
<h1>Box 3</h1>
its cold and lonely down here :(<br/>
I want to be with my waifu Box 1<br/>
</div>
</body>
</html>
&#13;
如何更改样式以匹配此项?有可能吗?
答案 0 :(得分:2)
您可以使用:nth-child()
选择器选择所有2n
元素并向右浮动。
* {
box-sizing: border-box;
}
body {
background-color: lightgray;
}
.box {
width: 48%;
margin: 1%;
padding: 10px;
background-color: white;
float: left;
}
.box:nth-child(2n) {
float: right;
}
<div class="box">
<h1>Box 1</h1> Test content 1</div>
<div class="box">
<h1>Box 2</h1> its a bit longer
<br/>than the last one<br/>
<br/>its a lot longer
<br/>than the last one actually<br/>
</div>
<div class="box">
<h1>Box 3</h1> its cold and lonely down here :(
<br/>I want to be with my waifu Box 1<br/>
</div>
<div class="box">
<h1>Box 4</h1> its cold and lonely down here :(
<br/>I want to be with my waifu Box 1<br/>
</div>
答案 1 :(得分:1)
你可以用类似的东西来实现它。
你应该看看css flex和卡布局,如:https://codepen.io/cssgirl/pen/NGKgrM
body{
background-color:lightgray;
display:flex;
flex-flow: row wrap;
}
.box{
padding:10px;
margin:10px;
background-color:white;
width: 200px;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="box">
<h1>Box 1</h1>
Test content 1
</div>
<div class="box">
<h1>Box 2</h1>
its a bit longer<br/>
than the last one<br/>
<br/>
its a lot longer<br/>
than the last one actually<br/>
</div>
<div class="box">
<h1>Box 3</h1>
its cold and lonely down here :(<br/>
I want to be with my waifu Box 1<br/>
</div>
</body>
</html>
答案 2 :(得分:0)
您可以使用CSS3 :nth-child()
选择器
body{
background-color:lightgray;
}
.box{
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width:48%;
margin:1%;
padding:10px;
background-color:white;
display:inline-block;
float:left;
}
.box:nth-child(even){
float: right;
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="box">
<h1>Box 1</h1>
Test content 1
</div>
<div class="box">
<h1>Box 2</h1>
its a bit longer<br/>
than the last one<br/>
<br/>
its a lot longer<br/>
than the last one actually<br/>
</div>
<div class="box">
<h1>Box 3</h1>
its cold and lonely down here :(<br/>
I want to be with my waifu Box 1<br/>
</div>
</body>
</html>
&#13;