5

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>
j08691
  • 204,283
  • 31
  • 260
  • 272
Mdd
  • 4,140
  • 12
  • 45
  • 70

3 Answers3

11

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.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68
2

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

Community
  • 1
  • 1
Tisch
  • 2,598
  • 4
  • 27
  • 34
0

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.

JimG
  • 9
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 19 '23 at 15:03