绝对定位脱离文档流
2019-07-20 本文已影响0人
青铜搬砖工
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style type="text/css">
.parent{
position: relative;
width: 100%;
background-color:black;
}
.child1{
position: absolute;
left: 50px;
}
.child2{
position: absolute;
right: 50px;
}
</style>
<body>
<div class = 'parent'>
<div class = 'child1'>
我是第一个子元素
</div>
<div class = 'child2'>
我是第二个子元素
</div>
</div>
</body>
</html>
当两个子元素都为绝对定位的时候,父元素的背景颜色就失效了.
![](https://img.haomeiwen.com/i11302390/3aa4613bf0079a70.png)
如果只有一个元素设置绝对定位,父元素背景颜色就会显示.
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style type="text/css">
.parent{
position: relative;
width: 100%;
background-color:black;
}
.child1{
position: absolute;
left: 50px;
color:white;
}
.child2{
right: 50px;
color: white;
}
</style>
<body>
<div class = 'parent'>
<div class = 'child1'>
我是第一个子元素
</div>
<div class = 'child2'>
我是第二个子元素
</div>
</div>
</body>
</html>
![](https://img.haomeiwen.com/i11302390/510bf17912486f07.png)
因为元素设置绝对定位后回脱离文档流,导致父元素的内容为空,所以父元素就不显示了.背景颜色也就失效了.给父元素加上高度就可以了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style type="text/css">
.parent{
position: relative;
width: 100%;
height: 50px;
background-color:black;
}
.child1{
position: absolute;
left: 50px;
color:white;
}
.child2{
position: absolute;
right: 50px;
color: white;
}
</style>
<body>
<div class = 'parent'>
<div class = 'child1'>
我是第一个子元素
</div>
<div class = 'child2'>
我是第二个子元素
</div>
</div>
</body>
</html>
![](https://img.haomeiwen.com/i11302390/c99b67286dc0eff9.png)