# 浮动
网页布局的本质一用CSS来摆放盒子。把盒子摆放到相应位置
CSS提供了三种传统布局方式(简单说就是盒子如何进行排列顺序)
flot 属性用于创建浮动框,将其移动到一边,直到佐边缘或右边缘触及包含块或另一个浮动框的边缘。
属性值 | 描述 |
---|---|
none | 元素不浮动(默认值) |
left | 元素向左浮动 |
right | 元素向右浮动 |
<body>
<div class="flot-left"></div>
<div class="flot-right"></div>
</body>
<style>
.flot-left {
width: 100px;
height: 100px;
background-color: skyblue;
float: left;
}
.flot-right {
width: 100px;
height: 100px;
background-color: paleturquoise;
float: right;
}
</style>
# 特性
- 浮动元素会脱离标准流(脱标)
- 浮动的元素会一行内显示并且元素顶赔部对齐
- 浮动的元素会具有行内块元素的特性
# 清除浮动
语法:
选择器:{
clear: both;
}
属性值 | 描述 |
---|---|
left | 不允许左侧有浮动元素(清除左侧浮动的影响) |
right | 不允许右侧有浮动元素(清除右侧浮动的影响) |
both | 同时清除左右两侧浮动的影响 |
清除浮动方法
- 额外标签法也称为隔墙法,是W3C推荐的做法。
- 父级添加overflow属性
- 父级添加after伪元素
- 父级添加双伪元素
# 额外标签法
必须是块元素
<body>
<div class="parent">
<div class="flot-left"></div>
<div class="flot-right"></div>
<div class="clear-fix"></div>
<div class="footer"></div>
</div>
</body>
<style>
.footer {
height: 200px;
background-color: black;
}
.flot-left {
width: 100px;
height: 100px;
background-color: skyblue;
float: left;
}
.flot-right {
width: 100px;
height: 100px;
background-color: paleturquoise;
float: left;
}
.clear-fix {
/*如果不加上这个clear,会高度坍塌*/
clear: both;
}
</style>
# 父级添加 overflow
可以给父级添加overflow属性,将其属性值设置为hidden、.auto或scroll。
注意是给父元素添加代码
<body>
<div class="parent">
<div class="flot-left"></div>
<div class="flot-right"></div>
</div>
<div class="footer"></div>
</body>
<style>
.parent {
overflow: hidden;
width: 800px;
}
.flot-left {
width: 100px;
height: 100px;
background-color: skyblue;
float: left;
}
.flot-right {
width: 100px;
height: 100px;
background-color: paleturquoise;
float: left;
}
.footer {
width: 800px;
height: 200px;
background-color: black;
}
</style>
# :after伪元素法
:after方式是额外标签法的升级版。也是给父元素添动加
<body>
<div class="parent clear-fix">
<div class="flot-left"></div>
<div class="flot-right"></div>
</div>
<div class="footer"></div>
</body>
<style>
.clear-fix::after {
content: '';
display: block;
height: 0;
clear: both;
overflow: hidden;
}
.clear-fix {
/* IE6 IE7 专有 兼容 */
*zoom: 1;
}
.parent {
overflow: hidden;
width: 800px;
}
.flot-left {
width: 100px;
height: 100px;
background-color: skyblue;
float: left;
}
.flot-right {
width: 100px;
height: 100px;
background-color: paleturquoise;
float: left;
}
.footer {
width: 800px;
height: 200px;
background-color: black;
}
</style>
# 双伪元素
也是给给父元素添加
<body>
<div class="parent clear-fix">
<div class="flot-left"></div>
<div class="flot-right"></div>
</div>
<div class="footer"></div>
</body>
<style>
.clear-fix::before,.clear-fix::after {
content: '';
display: table;
}
.clear-fix::after {
clear: both;
}
.clear-fix {
*zoom: 1;
}
.parent {
overflow: hidden;
width: 800px;
}
.flot-left {
width: 100px;
height: 100px;
background-color: skyblue;
float: left;
}
.flot-right {
width: 100px;
height: 100px;
background-color: paleturquoise;
float: left;
}
.footer {
width: 800px;
height: 200px;
background-color: black;
}
</style>