It will need more HTML code, but you can use the same basic technique as http://alistapart.com/article/creating-intrinsic-ratios-for-video/. You will need to set a width somewhere (because background images don't have intrinsic dimensions), but that could come from a parent element. Essentially:
<div class="wrapper-with-intrinsic-ratio"><div class="element-to-stretch"></div></div>
.wrapper-with-intrinsic-ratio {
position: relative;
padding-bottom: 20%; /* Adjust this to suit the aspect ratio of the image */
height: 0;
width: 100%;
}
.element-to-stretch {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url("http://placehold.it/350x150/000/fff");
background-size: cover;
}
.element-to-stretch:hover {
background-image: url("http://placehold.it/350x150/ccc/fff");
}
Here's some documentation on background-size. Secondly, the aspect ratio can be tricky: If the ratio is 2:1 (so the image is twice as wide as it is tall) then the padding-bottom
on .wrapper-with-intrinsic-ratio
would be 50%
. Work it out with (height ÷ width) × 100. So for example your 350×150px image would be padding-bottom: 42.857%;
and for a 150x350px it'd be 233.333%
.
Alternatively, you could do it with two img elements. Clunky, but...
<div>
<img src="normal.jpg" alt="" class="normal"><img src="hover.jpg" alt="" class="hover">
</div>
div img { max-width: 100%; height: auto; }
div img.normal,
div:hover img.hover { display: block; }
div img.hover,
div:hover img.normal { display: none; }
Or you could use javascript.