简体   繁体   中英

How to set image height in px if the width is a percentage?

If I have set the width of my images to 100% how can I insert the height of the image (in my HTML as height="") as an exact pixel figure? I need the height of all my images so the rest of the page can structure the layout out correctly.

height:auto; is no good because it's as good as leaving height="" empty, it doesn't give any measurement information to the page.

I can grab the exact pixel height of the original image

style="height:<?=$image_height[1]?>px;"

But once it's been resized by the width it's no longer in proportion, so the original height value is useless as it is.

Is there any solution for this, I'm stumped.

Each image is in a container that is 20% width of the page, making 5 columns.

Just set the height (and leave width as auto) as percentage and set the container to a fixed height so your rest layout is fine. Then width of images will adjust accordingly (responsive)

Another solution is to use padding to maintain aspect-ratio of images/videos, if needed i can add this solution as well

You can use this css code for setting all images in their actual pixels.

img{
   width: 100%;
   height: auto;
  overflow: hidden;
}

it seems to me like you need to play around with css property min-height

or you may need to dynamically calculate the height of the images with javascript as a proportion of their width , after they have been inserted into the dom.

example:

function calculateImageHeight (imageId) {

  var image = document.getElementById(imageId);

  // assuming you want the height to be 50% the width
  return image.width * 0.5;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM