【问题标题】:Absolutely positioned img didn't stretch the parent?绝对定位的 img 没有拉伸父级?
【发布时间】:2016-02-17 10:25:02
【问题描述】:

链接演示:http://codepen.io/leoaivy/pen/adxJaR 正如您在上面的链接中看到的那样,第一个正方形的孩子没有拉伸它的父母,而第二个正方形的孩子做了。我认为这是因为图像本身有它的比例,所以我们不能通过绝对位置来改变它。对吗?

html:

<div class="parent">
  <img src="http://placehold.it/350x150" alt="" />
</div>

<div class="parent">
  <span></span>
</div>

css:

.parent {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 150px;
  overflow: hidden;
}
.parent img, span {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.parent span {
  background: gold;
}

【问题讨论】:

  • 为图片添加max-width: 100%;

标签: html css


【解决方案1】:

您可以通过添加height:100%; width:100%;来强制图像拉伸

.parent {
  position: relative;
  display: inline-block;
  width: 400px;
  height: 400px;
  overflow: hidden;
}
.parent img {
  width: 100%;
  height: 100%;
}
.parent img,
span {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.parent span {
  background: gold;
}
<div class="parent">
  <img src="http://placehold.it/350x150" alt="" />
</div>

<div class="parent">
  <span></span>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多