the12 the12 - 1 month ago 9
CSS Question

Images having the same percentage height and width are rendering with different heights

I've been reading in multiple places that if you measure images in percentage, that the percentage is based on its parent container. Given the following code, I cannot understand why two different images, given the same height and width percentage would yield two slightly different size outputs.



div {
border: solid black;
}
img {
width: 40%;
height: 40%;
margin-right: 5%;
}
body {
background-color: white;
}

<div>
<img src="../images/458.jpg">
<img src="../images/650S.jpg">
</div>




Answer

The images are being sized based on the width: 40% only.

Your height: 40% is being ignored, because the parent element doesn't have a height specified.

In a block formatting context, a height must be declared on the parent for a percentage height to work on the child, unless the child is absolutely positioned.

See here for details: Working with the CSS height property and percentage values

Try this:

html,
body {
  height: 100%;
  background-color: white;
}
div {
  height: 100%;
  border: solid black;
}
img {
  width: 40%;
  height: 40%;
  margin-right: 5%;
}
<div>
  <img src="../images/458.jpg">
  <img src="../images/650S.jpg">
</div>

Comments