Float属性可以让元素摆脱文档流的束缚,在前端开发中是一种常用的属性。但是在开发过程中,总不能按照自己意愿将元素放在理想的位置。为避免重复冗余的修改工作,将float浮动属性的堆放规则做了测试总结,如有错漏,希望共同探讨。
堆放规则总结:
引入“当前行”的概念,指的是当前最右边元素的下边界
规则:当前行填充满或者填充不下之后,进入下一行,且不再返回。可能有点抽象,请看下面的测试图示和分析。
测试效果图:
浏览器:Chrome
分析:
步骤1 : 生成“float:left”的Left_1元素,此时的当前行为line_1;
步骤2: 生成“float:left”的Left_2元素,由于当前行未被填满,故Left_2与Left_1处于同一行上,此时的当前行为line_1;
步骤3: 生成“float:left”的Left_3元素,由于当前行未被填满,故Left_3与Left_2处于同一行上,此时的当前行为line_1;
步骤4: 生成“float:left”的Left_4元素,由于当前行剩余的位置放不下Left_4元素,故寻找下一行,根据规则,此时最右元素为Left_3,故将Left_3的下边界作为新的当前行,即line_2;但是此时line_2仍然放不下Left_4元素,进而寻找下一行,同理将line_3当成新的当前行,由于位置足够,故将Left_4放在line_3位置,此时的当前行为line_3;
步骤5: 生成“float:right”的Right_1元素,当前行放得下Left_5元素,故在图中位置放置Left_5元素,此时的当前行为line_3;
步骤6: 生成“float:right”的Right_2元素,由于Left_4和Right_1之间的空隙放不下Right_2元素,故查找下一行line_4,同理无法放下Right_2元素,最后找到line_5放置Right_2元素。
完整测试代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>浮动属性测试</title>
<style>
.commonType{
color:black;
font-size:20px;
}
.dashLine{
width:600px;
height:0;
border-top:2px dashed;
text-align:right;
color:red;
position:absolute;
}
</style>
</head>
<body>
<h1>浮动属性测试</h1>
<div style="width:500px;height:421px;border:1px solid;position:relative">
<div class="commonType" style="float:left;background-color:gold;width:200px;height:300px;">Left_1</div>
<div class="commonType" style="float:left;background-color:blue;width:150px;height:200px;">Left_2</div>
<div class="commonType" style="float:left;background-color:purple;width:100px;height:100px;">Left_3</div>
<div class="commonType" style="float:left;background-color:green;width:200px;height:120px;">Left_4</div>
<div class="commonType" style="float:right;background-color:yellow;width:50px;height:50px;">Right_1</div>
<div class="commonType" style="float:right;background-color:orange;width:200px;height:100px;">Right_2</div>
<div class="dashLine" style="top:0px">line_1</div>
<div class="dashLine" style="top:100px">line_2</div>
<div class="dashLine" style="top:200px">line_3</div>
<div class="dashLine" style="top:250px">line_4</div>
<div class="dashLine" style="top:320px">line_5</div>
</div>
</body>
</html>
联系方式: lzf199503@163.com