目录
一、浮动(float)
1.属性
float:left; | 元素靠左边浮动 |
float:right; | 元素靠右边浮动 |
float:none; | 元素不浮动 |
2.作用
定义网页中其他文本如何环绕该元素显示。
让竖着的东西横着来。
float 属性定义元素在哪个方向浮动,任何元素都可以浮动
浮动以后使元素脱离了文档流
浮动只有左右浮动,没有上下浮动
脱离文档流之后,元素相当于在页面上面增加一个浮层来放置内 容。此时可以理解为有两层页面,一层是底层的原页面,一层是脱 离文档流的上层页面,所以会出现折叠现象。
折叠
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style>
.container{
width: 300px;
height: 300px;
background-color: aqua;
}
.box{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
</style>
<body>
<div class="box"></div>
<div class="container"></div>
</body>
</html>
元素向右浮动
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style>
.container{
width: 300px;
height: 300px;
background-color: aqua;
}
.box{
width: 200px;
height: 200px;
background-color: blue;
float: right;
}
</style>
<body>
<div class="box"></div>
<div class="container"></div>
</body>
</html>
所有元素向左浮动
当所有元素同时浮动,会变成水平摆放,向左或者向右
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style>
.box{
width: 200px;
height: 200px;
background-color: blue;
float: left;
margin:0 10px;
}
</style>
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</body>
</html>
当容器不足以横向摆放内容时候,会在下一行摆放。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style>
.container{
width: 300px;
height: 300px;
border: 1px solid red;
}
.box{
width: 100px;
height: 100px;
background-color: blue;
float: left;
margin:10px;
}
</style>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</body>
</html>
3.浮动副作用
当元素设置float浮动后,该元素就会脱离文档流并向左/向右浮动
浮动元素会造成父元素高度塌陷
后续元素会受到影响
4.清除浮动
清除浮动-方法1
Clear
Clear:none; | 允许有浮动对象 |
Clear:right; | 不允许右边有浮动对象 |
Clear:left; | 不允许左边有浮动对象 |
Clear:both; | 不允许有浮动对象 |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style>
.box1,.box2{
width: 100px;
height: 100px;
float: left;
}
.box1{
background-color: aqua;
}
.box2{
background-color: aquamarine;
}
.box{
width: 300px;
height: 300px;
background-color: blue;
clear: both
}
</style>
<body>
<div>
<div class="box1">11</div>
<div class="box2">22</div>
</div>
<div class="box">33</div>
</body>
</html>
清除浮动只是改变元素的排列方式,该元素还是漂浮着,不占据文档位置。
清除浮动-方法2
父元素设置高度
如果父元素高度塌陷,可以给父元素设置高度,撑开元素本身大小
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style>
.container{
height: 300px;
width: 400px;
border: 1px solid red;
}
.box{
width: 100px;
height: 100px;
background-color: blue;
float:left;
margin: 5px;
}
</style>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</body>
</html>
清除浮动-方法3
在设置了浮动的div里再增加一个div,该div不设置其他属性,仅仅加一个行内标签,设置clear属性。
清除浮动-方法4
overflow清除
如果有父级塌陷,并且同级元素也收到了影响,可以使用 overflow 清 除浮动 这种情况下,父布局不能设置高度, 父级标签的样式里面加:
overflow:hidden;clear: both;