Lieutenant Dan
Lieutenant Dan

Reputation: 8294

Responsive IMGs maintain dimensions

I have a responsive website, where I am resizing all my images in the corresponding CSS3 media query's viewports. I'm wondering if there's an easier way to state that I want all my images to resize maintaining their original stated dimensions as opposed to manually resizing each accordingly with max-height, width, etc. Any suggestions?

EG Below.

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {

#logoimg { max-height: 100px; max-width: 100px; }

}

Upvotes: 4

Views: 217

Answers (4)

zloctb
zloctb

Reputation: 11194

use picture element http://caniuse.com/picture

manual http://www.html5rocks.com/en/tutorials/responsive/picture-element/

<picture>
  <source 
    media="(min-width: 650px)"
    srcset="images/kitten-stretching.png">
  <source 
    media="(min-width: 465px)"
    srcset="images/kitten-sitting.png">
  <img 
    src="images/kitten-curled.png" 
    alt="a cute kitten">
</picture>

Upvotes: 0

Joe Johnson
Joe Johnson

Reputation: 1824

Use background-size: contain; or background-size: cover; as appropriate.

Upvotes: 1

kremalicious
kremalicious

Reputation: 1371

This is what's needed for what is commonly referred to as fluid images:

img {
  max-width: 100%;
  height: auto;
}

The first declaration makes sure all images won't exceed the width of their containing element. The auto declaration for height ensures all images retain their proportions when scaled down even when they have size attributes in the img element.

This way you could just declare width or max-width on the container element of the img without having to worry about dimensions/proportions.

Upvotes: 0

Dennis Fagan
Dennis Fagan

Reputation: 551

I believe declaring img {max-width:100%} should do the trick. The image will scale down and maintain its dimensions.

Upvotes: 3

Related Questions