Scale image with css to both width and height to scale
I think this A List Apart article may help you greatly, it discusses responsive images that adapt to their container, maintaining aspect ratio.
Essentially you just need to contain the <img>
and specify dimensions for that container than apply max-width:100%
to the <img>
and it will adapt. Read the rest of the article for obligitary IE considerations (thankfully IE7+ supports it).
You can set only width or only height to 100%. E.g.
img {
width: 100%;
}
or
img {
height: 100%;
}
That will preserve the image scale, but the image might overflow the container.
This might not work in all browsers, but it does in the latest versions of Firefox, Chrome and Opera. I've had weird experiences with this in the past and my solution was to calculate the new image size on the server.
I was having difficulty with this until I read this thread (resize view width, preserve image aspect ratio with CSS), and the List Apart article (http://alistapart.com/article/fluid-images) and put it all together.
If your markup is like this...
<img src="myImg.jpg" />
...then simply stating
img {
width:100%
}
should be enough because most modern browsers realise that most people, given a choice, don't want to change the aspect of their images. However, if your markup contains dimension attributes like...
<img src="myImg.jpg" width="400" height="400" />
...which, is meant to be better technique, then the markup will shine through the CSS keeping the image at fixed height but flexible width (urgh!) unless you tell it otherwise with something like...
img {
width:100%;
height:inherit;
}
...or...
img {
width:100%;
height:auto;
}
Both seem to work and force the image back into correct aspect.
I've just stumbled upon this problem myself (my WYSIWIG editor adds dims to images by default - I needed a simple solution or I needed to spend hours hacking JCE to stop this behaviour) and haven't yet tested it exhaustively but it should give you a good starting point if you're having the same issue as me.
I don't know if there is a way to do this with just CSS. If you want to achieve something like this then you can use supersized
Alternatively, if you don't care about older browsers, you can look into the CSS3 background-size
property. Specifically, I think that setting background-size: cover
will do the trick.
Edit - I misunderstood. What you might actually want is background-size: contain
, but the downside is that you probably will have to change your html markup, not just your css.