2

If the height & width of an absolutely positioned element is not explicitly declared, and all of the 4 directions are 0, then the element will get the same height & width as its containing block:

CSS

section {
  width: 400px;
  height: 400px;
  background-color: teal;
  position: relative;
}

div {
  background-color: pink;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

HTML

<body>
  <section>
    <div></div>
  </section>
</body>

BUT things seem strange when it comes to the img:

CSS

section {
  width: 400px;
  height: 400px;
  background-color: teal;
  position: relative;
}

img {
  background-color: pink;
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

HTML

<body>
  <section>
    <img src="" alt="">
  </section>
</body>

Nothing changed except I replaced the div with the img. I even gave the img an explicit display: block, which is obviously redundant since absolutely positioned elements are computed as block. BUT the img didn't be stretched as the div did. Inspected it and found that the img exactly got the height 400px of its containing block, section, but the width is 0.

So here is my questions: Why absolutely positioned img cannot be auto stretched?

NOTICE: The img has no content.

There is a similar question, but I want the most essential and theoretical explanation rather than a workaround.

Kento
  • 58
  • 5

0 Answers0