1

I have noticed that I always need height & width attributes for absolute positioned images, even if I set left, right, bottom and top attributes.

See example code below or here: https://codepen.io/Rechi/pen/mdKQGym

The div.descendant follows the expected behavior, image does not.

Is the reason behind that the element replacement mentioned here:

.ancestor {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.ancestor .descendant {
  background: green;
  position: absolute;
  left: 5px;
  right: 5px;
  top: 5px;
  bottom: 5px;
  box-sizing: border-box;
  border: 2px solid blue;
}
.ancestor img.descendant {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="ancestor">
  <div class="descendant"></div>
  <img src="https://cdn.pixabay.com/photo/2013/07/12/17/47/test-pattern-152459_960_720.png" alt="" class="descendant">
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415

1 Answers1

0

Declare your css classes without embedded.

Add space between composed classes as img .descendant.

.ancestor {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}

.descendant {
  background: green;
  position: absolute;
  left: 5px;
  right: 5px;
  top: 5px;
  bottom: 5px;
  box-sizing: border-box;
  border: 2px solid blue;
}

img .descendant {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="ancestor">
  <div class="descendant"></div>
  <img src="https://cdn.pixabay.com/photo/2013/07/12/17/47/test-pattern-152459_960_720.png" alt="" class="descendant">
</div>
ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
  • Thanks for your answere, unfortunatly I've copied my SASS-Code instead of the css result into my question. I tried to change my question but that did no longer work. But the problem is not the mentioned embedding. – Wolfgang Rechberger Dec 04 '22 at 10:43