关于子元素(如div)在父元素(如div)中的定位问题:
假设现有html代码如下
<div class="div1">
<div class="div2>
test
</div>
</div>
想让div2在div1中实现底部居中的效果,查找资料发现关键步骤(CSS)是
div
{
width: 100px;
height: 100px;
position: relative;
}
.div2
{
position: absolute;
left: 50%;
bottom: 20px; /*按需要从底部上移*/
}
在一篇文章看到以下内容,解释得很清楚
position:absolute 元素相对最近的 position 为 absolute / relative / fixed 的祖先元素(包含块)定位,如果没有这样的祖先元素,则以初始包含块进行定位,而初始包含块并不是以或进行定位的。
测试如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position:absolute</title>
</head>
<style type="text/css">
html{
border: 1px solid red;
background-color: #ee8;
}
body{
width:300px;
height: 200px;
margin: 10px auto;
background-color: #ccc;
border: 1px solid blue;
}
div{
width: 100px;
height: 100px;
background-color: #3ff;
position: absolute;
}
</style>
<body>body
<div>div</div>
</body>
</html>
此时的效果如下:
body添加position:relative;
div添加 bottom:0;
效果如下:
html添加position:relative;
div添加 bottom:0;
效果如下:
body和html都不进行定位,div设置bottom:0;
此时效果如下:
所以,当绝对定位元素的祖先元素都没有进行relative/absolute/fixed定位时,是相对于初始包含块来定位的,而初始包含块并不是以或进行定位的。