float属性定义元素在哪个方向浮动,任何元素都可以浮动。
浮动的原理
1、浮动以后使元素脱离了文档流
2、浮动只有左右浮动,没有上下浮动
脱离文档流之后,元素相当于在页面上增加一个浮层来放置内容。此时可以理解为有两层页面,一层是底层的原页面,一层是脱离文档流的上层页面,所以会出现折叠现象。
文档流作用下:
<!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">
<title>Document</title>
<style>
.box{
background-color: red;
width: 200px;
height: 200px;
}
.container{
background-color: blue;
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="container"></div>
</body>
</html>
脱离文档流:
.box{
background-color: red;
width: 200px;
height: 200px;
float: left;
}
空隙:
<img style="width: 300px;" src="p2831307612.jpg" alt="">
<img style="width: 300px;" src="p2831307612.jpg" alt="">
脱离文档流后:
img{
float: left;
}
<img style="width: 300px;" src="p2831307612.jpg" alt="">
<img style="width: 300px;" src="p2831307612.jpg" alt="">
空隙消失
向左浮动
<!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">
<title>Document</title>
<style>
div{
width: 200px;
height: 200px;
}
.box1{
background-color: red;
}
.box2{
background-color: green;
}
.box3{
background-color: blue;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>
</html>
想将它变成从左到右排列:
div{
width: 200px;
height: 200px;
float: left;
}
常应用场景:无序列表横向排放
<!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">
<title>Document</title>
<style>
ul li{
float: left;
margin: 30px;
}
</style>
</head>
<body>
<ul>
<li>导航1</li>
<li>导航2</li>
<li>导航3</li>
<li>导航4</li>
</ul>
</body>
</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">
<title>Document</title>
<style>
.container{
width: 500px;
height: 500px;
background-color: aquamarine;
}
div{
width: 200px;
height: 200px;
float: left;
}
.box1{
background-color: red;
}
.box2{
background-color: green;
}
.box3{
background-color: blue;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>