myol
myol

Reputation: 9906

img max-width 100%, overscale img to fill div

I'm using max-width: 100% on an img within a div, to have the image scale automatically as the browser window is adjusted.

Is there any way I can make the image 'over-scale / enlarge' over its initial size, with the same scale, if the div's width is larger than the img width?

Thanks

Upvotes: 1

Views: 905

Answers (1)

KatieK
KatieK

Reputation: 13863

Actually, you don't need max-width: 100%;. Just use width: 100%; instead. Example:

img {
  width: 100%;
}

<img src="http://placekitten.com/500/500?image=9" />

The above kitten image will always scale up or down to be 100% as wide as its parent.


You can get a sort of conditional logic with media queries. In this example below, we have a headline and a 500px wide image. The image has max-width: 100%;. And there's a media query which says that when the viewport is more than 500px wide, the image's width should be 100% the width of its parent (and make the body background grey to identify when this media query applies).

HTML:

<h1>Pellentesque habitant morbi</h1>
<img src="http://placekitten.com/500/500?image=10" />

CSS:

img {
  max-width: 100%;
}

@media (min-width: 500px) {
  body  {
    background-color: #AAA;
  }  
  img {
      width: 100%;
    }
}

Thus, when inside a wide viewport, the image is as wide as that viewport.


Alternately, try making the image a background image, and then use CSS's background-size: cover;:

#image {
  background: #D84E51 url(http://placekitten.com/800/800?image=10) no-repeat center center;
  background-size: cover;
  min-height: 400px;
}

Upvotes: 2

Related Questions