1.概念
浮动:脱离原来的位置,可左右浮动,直到触碰到边缘或者另一个浮动框。如图
2.实现浮动:float
float:left;
float:right;
- 浮动后,原空间被后面的组件占用
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="test1.css">
<title>Document</title>
</head>
<body>
<div class="containter">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
</body>
</html>
css代码
.one{
width: 100px;
height: 80px;
background-color:aquamarine;
float: right;
}
.two{
width: 150px;
height: 80px;
background-color:blue;
}
.three{
width: 180px;
height: 80px;
background-color:chocolate;
}
-
不排队,要排自己的队
此时one,two向右浮动
-
全部浮动,实现横向排列
此时one,two,three向右浮动
-
父元素没有高度
原因:元素全部浮动,无法识别到高度。为了不影响下一个组件正常显示,需要清除浮动
3.清除浮动:clear
clear:both;(清除全部浮动)
clear:left;
clear:right;
如果下一个组件为非浮动元素,这样设计会出现一个问题,margin超界和父元素没有高度
如果下一个组件为浮动元素这不会出现。
css代码
.four{
width: 180px;
height: 200px;
background-color:rgb(179, 74, 156);
margin-top: 50px;
clear: both;
}
html代码
<div class="containter">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<div class="four"></div>
</body>
解决父元素无高度和margin超界问题
.containter::after{
content:'';
display:block;
clear:both;
}