Absolute field position causes container to crash

I have 2 divs s position:absolute

inside a container s position:relative

. I am trying to display the first div .box1

while hiding the second div .box2

using absolute positioning.

I can see that the border around the container is collapsed, but I'm not sure what I'm missing for it to wrap around the inner div being displayed.

.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>
      

Run codeHide result


+3


source to share


2 answers


If the parent container that contains absolute elements does not have an explicit height or width, it will collapse. So the solution is to provide the parent container with an explicit height / width. This is normal behavior.



+6


source


If you are using absolute positioning, you need to specify the dimensions (width and height). The "wrapper", as you mention, will not take place with an absolutely positioned element.



see this answer for more info: absolute and relative width and position height

+2


source







All Articles