Save up to 93% on some of the best SaaS →Check Black Friday Deals

How to Resize Images using CSS without losing the Aspect Ratio?

by: - Last updated on: March 23rd, 2019

Yesterday, if you have noticed, my blog was down for a few hours. This was because I had problems with my WordPress theme with sidebars getting messed up and found it hard to fix it up. I finally managed to debug this issue and found out it was all due to image over-sizing in my latest post. I googled a lot to find a fix for auto-resizing images in WordPress, but most of them were either blog theme specific or were controlling the image size before image upload.

resize images

Then I found out a quick and easy way to resize images with CSS by keeping your image’s aspect ratio. This is very quick you can use it in less than 5 minutes, let’s proceed!


Lets say you want to show large images on your web page with maximum 200 pixels width, blog or forums just create the following css class into your styling css file:

.resize {
width: 200px;
height : auto;
}

.resize {
width: auto;
height : 300px;
}

Second class will resize the images by keeping height as 300 pixels. You can use the following classes in <IMG> tags like:

<img src=”http://mywebsite.com/myphoto.jpg”  class=”resize” alt=”my photo”>

The above solution is always better than putting width and height attributes into the <IMG> tag. Hope it works out for you too

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. This is very nice. I wonder, is there a way to EXCLUDE this from my lightbox images that show full size? I only want it to apply to the images in the post, not when they lightbox.

  2. try this

    what it does is:
    1.) check if height is bigger than width
    2 True) if so make height 100 px and set width to auto
    2 False) if not make width 100 px and set height to auto

    .imgwidthNhigthLess100{
    max-width: 100px;
    max-height: 100px;
    height: expression(this.width > this.height ? auto: expression(this.height > 100 ? 100: true));
    width: expression(this.width > this.height ? expression(this.width > 100 ? 100: true) : auto);
    }

  3. To all of you suggesting the use of expression(); try using your CSS in a browser other than IE before suggesting to use non-standard CSS.