I\'d like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this:
Try this:
<img src="whatever.jpeg" width="100%" height="auto" />
The easiest way to do so (if you don't need to support IE) is setting the object-fit
CSS property to contain
:
img { object-fit: contain; }
See also:
To piggyback on Franci Penov, yes you just want to set one of them. If you have a wide picture, you want to set width to 100% and leave height. If you have a long picture, you want to set height to 100% and leave width.
It is also possible to do this with pure CSS using a background image and the background-size:contain
property:
<head>
<style>
#bigPicture
{
width:100%;
height:100%;
background:url(http://upload.wikimedia.org/wikipedia/commons/4/44/CatLolCatExample.jpg);
background-size:contain;
background-repeat:no-repeat;
background-position:center;
}
</style>
</head>
<body style="margin:0px">
<div id="bigPicture">
</div>
</body>
This has the benefit of automatically updating if the container changes aspect ratios, without having to respond to resize events (the Javascript methods, as coded here, can result in cutting off the image when the user resizes the browser). The <embed>
method has the same benefit, but CSS is much smoother and has no issues with security warnings.
Caveats:
<img>
element means no context menu and no alt text.background-size:contain
is 9+ only, and I couldn't even get this to work in IE9 (for unknown reasons).background-*
properties have to be specified in the same CSS block as the background image, so multiple images on the same page will each need their own contain
, no-repeat
, and center
.You don't necessarily want to stretch in a certain direction based on which is bigger. For example, I have a widescreen monitor, so even if it's a wider image than it is tall, stretching it left-to-right may still clip the top and bottom edges off.
You need to calculate the ratio between the window width and height and the image width and height. The smaller one is your controlling axis - the other is dependent. This is true even if both axes are larger than the respective window length.
<script type="text/javascript">
// <![CDATA[
function resizeToMax (id) {
var img = document.getElementById(id);
myImage = new Image();
myImage.src = img.src;
if (window.innerWidth / myImage.width < window.innerHeight / myImage.height) {
img.style.width = "100%";
} else {
img.style.height = "100%";
}
}
// ]]>
</script>
Tested on IE and Firefox, plus the first line will center image:
<div align="center">
<embed src="image.gif" height="100%">
... also great to preserve aspect ratio with any other size value, so no more annoying calculations =)