I have come to point out the answer nobody seems to see here. You can fullfill all requests you have made with pure CSS and it's very simple. Just use Media Queries. Media queries can check the orientation of the user's screen, or viewport. Then you can style your images depending on the orientation.
Just set your default CSS on your images like so:
img {
width:auto;
height:auto;
max-width:100%;
max-height:100%;
}
Then use some media queries to check your orientation and that's it!
@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }
You will always get an image that scales to fit the screen, never loses aspect ratio, never scales larger than the screen, never clips or overflows.
To learn more about these media queries, you can read MDN's specs.
To center your image horizontally and vertically, just use the flex box model. Use a parent div
set to 100% width and height, like so:
div.parent {
display:flex;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
justify-content:center;
align-items:center;
}
With the parent div's display
set to flex
, the element is now ready to use the flex box model. The justify-content
property sets the horizontal alignment of the flex items. The align-items
property sets the vertical alignment of the flex items.
I too had wanted these exact requirements and had scoured the web for a pure CSS solution. Since none of the answers here fulfilled all of your requirements, either with workarounds or settling upon sacrificing a requirement or two, this solution really is the most straightforward for your goals; as it fulfills all of your requirements with pure CSS.
EDIT: The accepted answer will only appear to work if your images are large. Try using small images and you will see that they can never be larger than their original size.