Three ways to resize images to fit a DIV :

  • Two different CSS classes (one for width, one for height).
  • Using the STYLE attribute within the IMG tag to manually set the width or height for each image (essentially the same as #1).
  • Warning, exiting browser-side territory!
  • To resize an image proportionally, you have to set either the height or width to “100%”, but not both.
  • If you set both to “100%”, your image will be stretched.
  • Choosing whether to do height or width depends on your image and container dimensions:
  • If your image and container are both “portrait shaped” or both “landscape shaped” (taller than they are wide, or wider than they are tall, respectively), then it doesn’t matter which of height or width are “%100“
  • If your image is portrait, and your container is landscape, you must set height=”100%” on the image.
  • If your image is landscape, and your container is portrait, you must set width=”100%” on the image.
  • If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.
  • You just have to ensure that the SVG file has none of these properties set in the <svg> tag:
    1. height
    2. width
    3. viewbox
  • Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.

Example Image:

Two different CSS classes (one for width, one for height) :

[pastacode lang=”css” manual=”%3Cstyle%3E%0A%23img_box%0A%7B%0A%20width%3A90%25%3B%0A%20height%3A90%25%3B%0A%7D%0A.resize_horizontal%0A%7B%0A%20width%3A100%25%3B%0A%7D%0A.resize_vertical%0A%7B%0A%20height%3A100%25%3B%0A%7D%0A%3C%2Fstyle%3E%0A%3Cdiv%20id%3D%22img_box%22%3E%0A%20%3Cimg%20class%3D%22resize_horizontal%22%20src%3D%22path%2Fto%2Fhorizontal_image.jpg%22%20%2F%3E%0A%3C%2Fdiv%3E%0A%3Cdiv%20id%3D%22img_box%22%3E%0A%20%3Cimg%20class%3D%22resize_vertical%22%20src%3D%22path%2Fto%2Fvertical_image.jpg%22%20%2F%3E%0A%3C%2Fdiv%3E%0A” message=”css code” highlight=”” provider=”manual”/] [ad type=”banner”]

Categorized in: