0

Link demo: http://codepen.io/leoaivy/pen/adxJaR As you can see in the link above, the first square's child didn't stretch its parent while the second square's child did. I think it's because the image has its ratio itself, so we can't change it by position absolute. Is it right?

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;
}
David H.
  • 953
  • 1
  • 8
  • 20
Vincent
  • 161
  • 2
  • 15

1 Answers1

0

You can force the image to stretch by adding 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>
Nick
  • 3,231
  • 2
  • 28
  • 50