首页 > 解决方案 > 为什么绝对定位的img不能自动拉伸?

问题描述

如果绝对定位元素的height&没有显式声明,并且所有 4 个方向都是,那么该元素将获得与其包含块相同的& :width0heightwidth

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>

但是,当涉及到时,事情似乎很奇怪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>

除了我divimg. 我什至给出了img一个明确的display: block,这显然是多余的,因为绝对定位的元素被计算为block。但是img并没有像以前那样被拉伸div。检查它,发现它img恰好得到了height它的包含块的 400px section,但width是 0

所以这是我的问题:为什么绝对定位img不能自动拉伸?

注意:img没有内容。

有一个类似的问题,但我想要最本质和理论上的解释,而不是解决方法。

标签: csscss-positionabsolute

解决方案


推荐阅读