CSS3 清除浮动
CSS3 清除浮动
基础代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1, body {
margin: 0;
}
h1 {
background-color: aquamarine;
}
div > div:nth-of-type(1) {
width: 200px;
height: 200px;
background-color: antiquewhite;
}
div > div:nth-of-type(2) {
width: 200px;
height: 200px;
background-color: aqua;
}
div:nth-of-type(1) {
background-color: pink;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<div>
<div></div>
<div></div>
</div>
</body>
</html>
- 先去掉h1,和body的margin
- 一个没有宽高限制的盒子包裹两个固定宽高的子盒子。
- 让第一个去最左边,第二个去最右边
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1, body {
margin: 0;
}
h1 {
background-color: aquamarine;
}
div > div:nth-of-type(1) {
/* position: absolute; */
/* top: 0; */
/* right: 0; */
width: 200px;
float: left;
height: 200px;
background-color: antiquewhite;
}
div > div:nth-of-type(2) {
/* position: absolute; */
/* top: 0; */
/* left: 0; */
float: right;
width: 200px;
height: 200px;
background-color: aqua;
}
div:nth-of-type(1) {
/* position: relative; */
background-color: pink;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<div>
<div></div>
<div></div>
</div>
</body>
</html>
可以看到因为子容器脱离了标准流,导致父容器无法感知子容器的高度,而高度为0.
清除浮动代码
/* 清除浮动代码 */
.clearfix:before,
.clearfix:after {
content: "";
display: table;
}
.clearfix::after {
clear: both;
}
/* 用来兼容IE */
.clearfix {
zoom: 1;
}
或者更简洁的做法
.clearfix::after {
content: "";
display: table;
clear: both;
}
或者更加现代的做法,但是不支持IE
.clearfix {
display: flow-root;
}
使用相对布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1, body {
margin: 0;
}
h1 {
background-color: aquamarine;
}
div > div:nth-of-type(1) {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 200px;
background-color: antiquewhite;
}
div > div:nth-of-type(2) {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: aqua;
}
div:nth-of-type(1) {
position: relative;
background-color: pink;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<div>
<div></div>
<div></div>
</div>
</body>
</html>
子元素同意脱离标准流,但是暂时不知道如何使父元素包裹子元素。

CSS3 清除浮动
浙公网安备 33010602011771号