position absolute box导致容器塌陷

Position absolute box causes container to collapse

我在 position:relative 的容器中有 2 个 div 和 position:absolute。我正在尝试使用绝对定位显示第一个 div .box1,同时隐藏第二个 div、.box2

我可以看到容器周围的边框已折叠,但我不确定我遗漏了什么,所以它环绕着显示的内部 div。

.container {
    border: 1px solid black;
    position: relative;
    height: 100%;
}

.box {
    text-align: center;
    padding: 1em;
    position: absolute;
    width: 100%;
}

.box1 {
    background-color: #CECECE;
    top: 100%;    
}
.box2 {
    background-color: #87CEEB;
    top: 0%;
}
<div class="container">
    <div class="box box1">
        Content 1
    </div>
    <div class="box box2">
        Content 2
    </div>
</div>

如果您使用绝对定位,则需要指定尺寸(宽度和高度)。 "Wrapping" 正如您提到的那样,绝对定位的项目不会出现。

查看此答案了解更多信息:absolute vs relative position width & height

如果包含绝对元素的父容器没有明确的高度或宽度,它将折叠。那么解决方案就是给父容器一个显式的height/width。这是正常行为。