rich22 rich22 - 4 months ago 8
HTML Question

Why do pictures that have the same percentage measurement output different heights?

I've been reading in multiple places that if you measure images in percentage, that the percentage is based on it's 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.

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

Answer

The images are being sized based on the width only.

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

For elements using percentage heights, that aren't absolutely positioned, a height must be declared on the parent, per the spec. (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