I am creating a single page application. In one of the views, I want to show an image that should occupy the maximum possible space:
- Most importantly: it must maintain aspect ratio
- it cannot be cut
- it must be stretched horizontally and / or vertically (without changing the aspect ratio) to cover the maximum possible space
- image size and viewing area unknown
- it should be centered.
- no js must be used
- the element should be an
img element and the background should not be used - I already have the background (in the container)
For example, let's say that the image is 100px x 100px, and that we have a container sized 500px x 300px. The image will then stretch to 300px x 300px and be horizontally centered, so that 100px will remain as a complement on both sides.
Is it possible?
Here is my incomplete code of what I'm trying to execute.
.container1 { width: 500px; height: 300px; border: 2px; border-color: red; border-style: solid; } .container2 { width: 300px; height: 500px; border: 2px; border-color: blue; border-style: solid } .fill-vertical { border: 2px; border-style: solid; border-color: green; display: block; max-width: 100%; } .fill-horizontal { width: 100%; border: 2px; border-style: solid; border-color: green; }
<h1>Container 1, 500px x 300px, not filled</h1> <div class="container1"> <img src="http://files.giercownia.pl/upload/avatars/r/ravax.png?v=0"> </div> <h1>Container 1, filled vertically (should be horizontally centered)</h1> <div class="container1"> <img class="fill-vertical" src="http://files.giercownia.pl/upload/avatars/r/ravax.png?v=0"> </div> <h1>Container 300px x 500px, not filled</h1> <div class="container2"> <img class="fillIt" src="http://files.giercownia.pl/upload/avatars/r/ravax.png?v=0"> </div> <h1>Container 300px x 500px, filled horizontally, should be vertically centered</h1> <div class="container2"> <img class="fill-horizontal" src="http://files.giercownia.pl/upload/avatars/r/ravax.png?v=0"> </div>
In this code, I am forced to use a different class for the image depending on whether I want to stretch vertically or horizontally, but in fact I want CSS to do this automatically: only one stretch class needs to be defined .
In short, what I want to do CSS: stretch width and / or height to fit the available space while maintaining aspect ratio
source share