Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position absolute box causes container to collapse

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>
like image 673
Mdd Avatar asked Dec 15 '22 13:12

Mdd


2 Answers

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.

like image 148
Josh Beam Avatar answered Jan 05 '23 10:01

Josh Beam


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

like image 37
Tisch Avatar answered Jan 05 '23 09:01

Tisch