前提:三个元素占据一整行
当多个元素都浮动时,每行的三个元素的高度不一致,第四个元素就会紧跟着高度最高的元素后边,导致界面变乱。
如下元素4跟在元素2的后边
第一感觉是给前三个元素包裹一个div,使用bootstrap的clearfix类,隔离掉第四个元素。这是最简单的办法,但是原来写的css选择器就会失效。
<div class="box clearfix container">
<div class="clearfix"> <!--添加一个父元素div-->
<div class="pull-left child">第一段文字1</div>
<div class="pull-left child">这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字</div>
<div class="pull-left child">第三段文字3</div>
</div>
<div class="pull-left child" style="background-color: hotpink;">第四段文字4</div>
</div>
当无法使用包裹元素时,可以使第四个元素的左边不要有浮动。因为所有子元素都是用了浮动,这时第四个元素就会另起一行。
如果多个元素,也会依次排列,不会跟随在高的元素后边。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/*仿bootstrap的代码*/
.container {
width: 800px;
margin: 0 auto;
}
.container::after,
.container::before {
content: " ";
display: table;
}
.container::after {
clear: both;
}
.pull-left {
float: left;
}
/*仿bootstrap的代码 结束*/
.box .child:nth-child(3n-1) {
width: 60%;
background-color: thistle;
}
.box .child:nth-child(3n) {
width: 20%;
background-color: wheat;
}
.box .child:nth-child(3n + 1) {
width: 20%;
background-color: tomato;
/*关键点,去掉注释,就可以看到想要看到的结果*/
/*clear: left;*/
}
</style>
</head>
<body>
<div class="box clearfix container">
<div class="pull-left child">第一段文字1</div>
<div class="pull-left child">这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字,这是第二大段文字</div>
<div class="pull-left child">第三段文字3</div>
<div class="pull-left child" style="background-color: hotpink;">第四段文字4</div>
</div>
</body>
</html>