-1

please take a look to the snippet below. I honestly can't get why the absolute positioned element (red) is not overlapping the other one. Why?

I all comes from analyzing a more complex case with some animations on a slideshow which I wanted to replicate. And they are take advantage of this strange (at least to me) behaviour, along with some other absolute-pos-in-flex-container related things.

Anyway, I tried to simplify the thing down to the bone and that's it. Why isn't the description overlapping the caption?

.caption{
  background-color: rgba(0, 0, 0, .2);
}

.description{
  position: absolute;
  background-color: rgba(250, 0, 0, .7);
}
<div class="caption">caption</div>
<div class="description">description</div>
Luca Reghellin
  • 7,426
  • 12
  • 73
  • 118

2 Answers2

3

The description element does not overlap the caption element because you have not set the top, bottom, left or right properties. Just setting position: absolute; by itself won't change the position of the element. You also need one of those additional properties to be set in order to tell the element where it will be absolutely positioned.

Try something like:

.caption{
  background-color: rgba(0, 0, 0, .2);
}

.description{
  position: absolute;
  top: 8px;
  background-color: rgba(250, 0, 0, .7);
}
<div class="caption">caption</div>
<div class="description">description</div>
Sup3rkirby
  • 155
  • 1
  • 9
1

To explicitly move absolutely positioned elements, it is necessary to set the CSS values of the top|bottom|left|right properties. By default, these properties have auto values - this is the key point in this situation.

According to the documentation, when top: auto:

for absolutely positioned elements, the position of the element is based on the bottom property, while height: auto is treated as a height based on the content; or if bottom is also auto, the element is positioned where it should vertically be positioned if it were a static element.

Similar with the rest of the properties (bottom, left, right).

Accordingly, when you set the positioning explicitly, then the elements will already overlap:

.caption {
  background-color: rgba(0, 0, 0, .2);
}

.description {
  position: absolute;
  background-color: rgba(250, 0, 0, .7);
  top: 0;
  left: 0;
}
<div class="caption">caption</div>
<div class="description">description</div>
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17