Position absolute box causes container to collapse

8.6k Views Asked by At

I have 2 divs with position:absolute inside a container with position:relative. I am trying to display the first div .box1 while hiding the second div, .box2, using absolute positioning.

I can see with the border around the container that it is collapsed but I am not sure what I'm missing so that it wraps around the inner div that is 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>

3

There are 3 best solutions below

0
On BEST ANSWER

If the parent container that holds the absolute elements doesn't have an explicit height or width, it will collapse. The solution, then, is to give the parent container an explicit height/width. It's normal behavior.

0
On

You will need to specify dimensions (width and height) if you are using absolute positioning. "Wrapping" as you are mentioning will not occur with an absolutely positioned item.

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

1
On

I couldn't get either of these "answers" to work. The best thing today is to use the flexbox-container class and don't use absolute positioning at all.