居中弹性盒内使用绝对定位会默认居中!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.outer {
display: flex;
position: relative;
align-items: center;
justify-content: center;
width: 200px;
height: 200px;
background: #e0e0e0;
}
.inner {
width: 50px;
height: 50px;
margin: 5px;
background: #e0ffe0;
}
.inner-abs {
position: absolute;
width: 30px;
height: 30px;
background: #ffe0e0;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
<div class="inner-abs"></div>
<div class="inner"></div>
</div>
</body>
</html>
代码效果展示如下:
可以简单明了的看出,绝对定位一如既往地让inner-abs元素脱离了文档流,但是并不出现在预期中的左上角,因为父容器中的双向居中同时使得绝对定位元素在未指定位置的情况下,可以居中定位。 当给inner-abs元素指定top或者left等样式属性后,则会覆盖居中的样式。
.inner-abs {
position: absolute;
top: 20px;
width: 30px;
height: 30px;
background: #ffe0e0;
}
则得到如下展示结果: