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) :

css code
<style>
#img_box
{
width:90%;
height:90%;
}
.resize_horizontal
{
width:100%;
}
.resize_vertical
{
height:100%;
}
</style>
<div id="img_box">
<img class="resize_horizontal" src="path/to/horizontal_image.jpg" />
</div>
<div id="img_box">
<img class="resize_vertical" src="path/to/vertical_image.jpg" />
</div>
[ad type=”banner”]

Categorized in: