浮动
一、浮动产生原因
1.布局需要在一行显示
2.标准流无法满足需求
二、浮动的特性
1、脱离文档流
2、浮动后的元素不保留原先位置
三、浮动带来的影响
父布局坍塌,影响后面元素排列规则
四、 清除浮动策略(闭合浮动)
额外标签法,也成为隔墙法,W3C推荐的做法:需要在最后一个浮动的子元素增加一个空标签(必须为块级元素),使用clear:both
<style>
.father{
background-color:khaki;
}
.one,.two{
width: 300px;
height: 300px;
}
.one{
background-color: red;
float: left;
}
.two{
background-color: green;
float: left;
}
.clear{
clear: both;
}
</style>
<body>
<div class="father">
<div class="one">
</div>
<div class="two">
</div>
<div class="clear">
</div>
</div>
</body>
- 优点:通俗易懂,书写简单
- 缺点:增加不必要的标签,结构化较差
父级添加overflow属性,父级元素overflow设置为hidden,auto,scroll
<style>
.father{
background-color:khaki;
overflow: hidden | auto | scroll;
}
.one,.two{
width: 300px;
height: 300px;
}
.one{
background-color: red;
float: left;
}
.two{
background-color: green;
float: left;
}
</style>
<body>
<div class="father">
<div class="one">
</div>
<div class="two">
</div>
</div>
</body>
父级添加after元素(升级版的额外标签法)
<style>
.clearbox:after{
content: ""; // 伪元素必须写这个属性
display: block; // 必须为块级元素
height: 0; // 隐藏元素
clear: both;
visibility: hidden; // 隐藏元素
}
.clearbox{
*zoom: 1; //兼容ie7
}
.father{
background-color:khaki;
}
.one,.two{
width: 300px;
height: 300px;
}
.one{
background-color: red;
float: left;
}
.two{
background-color: green;
float: left;
}
</style>
<body>
<div class="father clearbox">
<div class="one">
</div>
<div class="two">
</div>
</div>
</body>
- 优点:代码简洁,使用css
- 缺点:需要写兼容低版本浏览器代码
父级添加双伪元素
<style>
.clearbox:after,.clearbox:before{
content: "";
display: table;
}
.clearbox:after{
clear: both;
}
.clearbox{
*zoom: 1;
}
.father{
background-color:khaki;
}
.one,.two{
width: 300px;
height: 300px;
}
.one{
background-color: red;
float: left;
}
.two{
background-color: green;
float: left;
}
</style>
<body>
<div class="father clearbox">
<div class="one">
</div>
<div class="two">
</div>
</div>
</body>
- 优点:代码简洁,使用css
- 缺点:需要写兼容低版本浏览器代码