How To Set A Maximum Width or Maximum Height For An Image With CSS

I was trying to figure out how to set the maximum width and maximum height for my images, and I wanted a way that didn’t require PHP programming. I finally found a way and stumbled upon how CSS could make use of expressions as well. It’s a method where you can have a conditional statement in CSS, as follows:

#container img {
  width: expression(this.width > 500 ? 500: true);
  width: expression(this.height > 300 ? 300: true);

What this does is to evaluate whether the height or width of your image is more than the stated (500px for width, 300px for height), and if so, resize them to 500px and 300px respectively. Note that you actually have to apply this CSS to your image directly, either by modifying the img tag as above, or by assigning a CSS class to your images. This doesn’t work if you apply the CSS to the containing DIV.

this.width > 500 ? 500: true is actually an inline programing statement, which takes on this form: (condition-to-evaluate) ? value-if-true:value-if-false

If you’ve done programming before, it’s exactly the same as the typical If-conditional, which looks like:

if (myName=="Alvin") {
  return "Hi Alvin!";
} else {
  return "Who're you?";

Done in the inline form, it’ll appear like the following. It’s exactly the same, but comes in one line to save space and make it more streamlined. It’s useful for short conditionals, but I wouldn’t recommend it for more complex code blocks.

(myName=="Alvin)?"Hi Alvin!":"Who're you?";

I haven’t done extensive cross-browser testing yet, but as far as I know, this works for FireFox 3.x and Internet Explorer 7 at least.

Similar Posts:

Alvin Poh lives in Singapore, and is interested in marketing, techy stuff, and likes to just figure out how the two can work with each other. He can also be found on Google+.

1 comments On How To Set A Maximum Width or Maximum Height For An Image With CSS

Leave a reply:

Your email address will not be published.


Sliding Sidebar