0

I have the following HTML markup:

    <div class="img-container"
      <img src="images/" alt="" /> <!-- width: 100%; -->
    </div>

    <div class="img-container">
      <img src="images/" alt="" /> <!-- width: 100%; -->
    </div>

^^^ I have 2 images that are each nested inside of a div. I have given the images a width of 100%, so they can take the full width of their parent. I have also given the img-container divs a width of 50%. Everything works fine and both the images take a width of 50% on the screen.

enter image description here

^^^ I never gave it a height value and this is how it shows up.

BUT when I actually give the height a value of 50% then it shows up like this:

enter image description here

The width of 50% is working but the height of 50% is not working?

BUT WHY? Giving it a height in pixels work properly, but when I assign it a height in percentage, then it doesn't apply that height... Why is that?

Oxin
  • 63
  • 6
  • 1
    What do you expect it to be 50% of? – Richard Hunter Oct 16 '20 at 21:31
  • ^^^ Great question! For example, I want the width of each image to be 50% of the screen. and i works properly. I want those images to be a perfect square, so I try to also give it a width of 50% and it doesnt work... Not specifying the height makes the height automatically match up to the width. So I gave it a height of 50% so the image can be a perfect square, because if I gave it a width of 50%, would it not be right to also give it a height of 50%? – Oxin Oct 16 '20 at 21:36
  • Ah. See my comment below. – Ben in CA Oct 16 '20 at 21:42
  • So you expect `height:50%` to mean 50% of the width of the container. Unfortunately, that's not what it is. It's 50% of the height of your container, and your container isn't the same height as it width. – Richard Hunter Oct 16 '20 at 22:46

1 Answers1

0

Does your parent element (of the images - img-container for instance) have a height defined?

Height in HTML / CSS takes some getting used to - it doesn't always work the way you'd expect.

If you look at something like this, it also has to do with the window size: https://www.w3schools.com/css/tryit.asp?filename=trycss_dim_height_percent

Ben in CA
  • 688
  • 8
  • 22
  • Yes, and that is the element on which the height isn't working. I have nested my img tags inside of a DIV tag. The images will take 100% width and height of their parent and this case I gave the parent element a width of 50% – Oxin Oct 16 '20 at 21:33
  • May be a copy/paste error - do you have a > after the first
    – Ben in CA Oct 16 '20 at 21:35
  • Do you have a parent element to the div or have the body defined with a set height? – Ben in CA Oct 16 '20 at 21:36
  • You might want to look at the aspect ratio then. Setting height to 50% is not going to be what you want in that case. See: https://www.w3schools.com/howto/howto_css_aspect_ratio.asp – Ben in CA Oct 16 '20 at 21:42