the12
the12

Reputation: 2415

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>

Upvotes: 2

Views: 429

Answers (2)

Michael Benjamin
Michael Benjamin

Reputation: 371669

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>

Upvotes: 4

spirit
spirit

Reputation: 3415

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.

Upvotes: 1

Related Questions