【发布时间】:2021-01-17 01:59:27
【问题描述】:
我只是在学习 CSS 中的定位。根据我发现有用的文章,我开始玩弄。
使用下面的代码,我无法理解为什么绝对的灰盒 div 在它的相对父级之外。我预计灰色框会在容器的左上角。
.container {
background: lightblue;
position: relative;
}
.box-orange {
background: orange;
height: 100px;
width: 100px;
position: relative;
top: 100px;
left: 100px;
z-index: 2;
}
.box-blue {
background: lightskyblue;
height: 100px;
width: 100px;
/*position: static;*/
}
.box-green {
background: lightgreen;
height: 100px;
width: 100px;
position: relative;
top: -105px;
left: 105px;
z-index: 2;
}
.box-grey {
background: grey;
height: 100px;
width: 100px;
position: absolute;
}
<div class="container">
<div class="box-orange"></div>
<div class="box-blue"></div>
<div class="box-green"></div>
<div class="box-grey"></div>
</div>
在以下情况下也无法理解为什么灰色框不在左上角,而是在橙色框留下的空白区域之后移动。我刚刚将灰色框移到容器 div 内的第二个位置。
.container {
background: lightblue;
position: relative;
}
.box-orange {
background: orange;
height: 100px;
width: 100px;
position: relative;
top: 100px;
left: 100px;
z-index: 2;
}
.box-blue {
background: lightskyblue;
height: 100px;
width: 100px;
/*position: static;*/
}
.box-green {
background: lightgreen;
height: 100px;
width: 100px;
position: relative;
top: -105px;
left: 105px;
z-index: 2;
}
.box-grey {
background: grey;
height: 100px;
width: 100px;
position: absolute;
}
<div class="container">
<div class="box-orange"></div>
<div class="box-grey"></div>
<div class="box-blue"></div>
<div class="box-green"></div>
</div>
我发现的所有详细文档(例如 MDN)和教程只是用 2-3 个框演示了非常简单的示例。
【问题讨论】:
-
您没有设置任何 top/left .. 设置 top/left 来控制位置,否则它将根据其 static 位置进行定位。由于您仍在学习,因此无需对默认位置感到困惑
标签: html css css-position