目录
CSS中浮动用于布局和格式化内容
浮动的特性
1.脱离标准流;
2.实现横向布局
3.具有行内块特性
浮动最常见的应用
浮动主要应用于多个块级元素一行内排列
效果图1:
代码1如下:
<style>
* {
margin: 0;
padding: 0;
}
.box {
height: 285px;
width: 1226px;
margin: 0 auto;
background-color: tomato;
list-style: none;
}
.box li {
float: left;
height: 285px;
width: 296px;
background-color: skyblue;
margin-right: 14px;
}
.box .box-4 {
margin-right: 0;
}
</style>
<ul class="box">
<li>1</li>
<li>2</li>
<li>3</li>
<li class="box-4">4</li>
</ul>
</body>
效果图2如下:
代码如下:
<style>
* {
margin: 0;
padding: 0;
}
.box {
height: 615px;
width: 1226px;
margin: 0 auto;
background-color: pink;
}
.left {
height: 615px;
width: 234px;
float: left;
background-color: aqua;
}
.right {
width: 992px;
height: 615px;
float: right;
background-color: aquamarine;
}
.right>div {
height: 300px;
width: 234px;
float: left;
background-color: blanchedalmond;
margin-left: 14px;
margin-bottom: 14px;
}
</style>
<div class="box">
<div class="left"></div>
<div class="right">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
外边距塌陷(外边距合并问题解决办法)
对于嵌套两个盒子,如下图:
踩坑:使小盒子顶部大盒子30px
代码:
<style>
.father {
height: 400px;
width: 400px;
background-color: skyblue;
}
.son {
margin-top: 30px;
height: 200px;
width: 200px;
background-color: aquamarine;
}
</style>
效果:
效果说明:两个盒子同时向下移动30px
产生原因:外边距塌陷(外边距合并)
解决办法(外边距塌陷):
1.父盒子加透明边框:
<style>
.father {
height: 400px;
width: 400px;
background-color: skyblue;
//方法一:给父盒子加透明边框
border: 1px solid rgba(0,0,0,0);
//方法二:给父盒子加1px的padding值
//方法三:给父元素添加overflow: hidden;
}
.son {
margin-top: 30px;
height: 200px;
width: 200px;
background-color: aquamarine;
}
</style>
外边距合并现象二:两个并列关系的盒子
给盒子1加30px下外边距,给盒子2加50px上外边距:
以数值较大的为准。
清除浮动
应用场景:父盒子不方便给高度,即内容可变。
实质:内容撑开盒子高度;
使用对象:父元素
方法:
1.给父元素样式中添加overflow:hidden;
2.单伪元素清除浮动,代码如下:
.clearfix:after{
content:"",
display:block;
height:0;
cleasr:both;
visibility:hidd
}
.clearfix{
*zoom:1;
}
3.双伪元素清除浮动,代码:
//双伪元素清除浮动
.learfix:before,.clearfix:after{
content:"";
display:table;
}
.clearfix:after{
clear:both;
}
.clearfix{
*zoom:1;
}