I have a site with many pages and different background pictures, and I display them from CSS like:
body.page-8 {
background: url("../img/pic.jpg") no-repeat scroll center top #000;
background-size: cover;
}
However, I want to show different (fullscreen) pictures on one page using <img>
elements, and I want them to have the same properties as the above background-image: cover;
property (the images cant be displayed from CSS, they must be displayed from the HTML document).
Normally I use:
div.mydiv img {
width: 100%;
}
Or:
div.mydiv img {
width: auto;
}
to make the picture full and responsive. However the picture shrinks too much (width: 100%
) when the screen gets too narrow, and shows the body's background-color in the bottom screen. The other method, width: auto;
, only makes the image full size and does not respond to the screen size.
Is there a way to display the image the same way that background-size: cover
does?
With CSS you can simulate
object-fit: [cover|contain];
. It's usetransform
and[max|min]-[width|height]
. It's not perfect. That not work in one case: if the image is wider and shorter than the container.Try setting both
min-height
andmin-width
, withdisplay:block
:(fiddle)
Provided your image's containing element is
position:relative
orposition:absolute
, the image will cover the container. However, it will not be centred.You can easily centre the image if you know whether it will overflow horizontally (set
margin-left:-50%
) or vertically (setmargin-top:-50%
). It may be possible to use CSS media queries (and some mathematics) to figure that out.There is actually quite a simple css solution which even works on IE8:
No, you can't get it quite like
background-size:cover
but..This approach is pretty damn close: it uses JavaScript to determine if the image is landscape or portrait, and applies styles accordingly.
JS
CSS
http://jsfiddle.net/b3PbT/
For IE you also need to include the second line - width: 100%;
Assuming you can arrange to have a container element you wish to fill, this appears to work, but feels a bit hackish. In essence, I just use
min/max-width/height
on a larger area and then scale that area back into the original dimensions.