2

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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
the12
  • 2,395
  • 5
  • 19
  • 37

2 Answers2

4

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>
Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
1

They are gives you different output because of your parent div. You did not assign to it any sizes: width of height. Therefore, browser using original sizes to calculate new sizes.

If you will add something like this to your style:

div {
  width: 50%;
  height: 300px;
}

The output should be the same.

spirit
  • 3,265
  • 2
  • 14
  • 29