I'm currently working on a single page application where I need to display an image that fills up as much available space as possible:
- Priority: maintain the aspect ratio
- Avoid cropping the image
- Stretch the image horizontally and/or vertically (without altering the aspect ratio) to cover the maximum space
- The size of the image and viewport are unknown
- Center the image
- Avoid using JavaScript
- The element must be an
img
element without utilizing a background because there is already a background in the container
For example, if the image is 100px x 100px and the container is 500px x 300px, the image should stretch to 300px x 300px, horizontally centered with 100px padding on each side.
Is this achievable?
Here is the current state of my code for reference.
.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="https://dummyimage.com/100x100/000/fff">
</div>
<h1>Container 1, filled vertically (should be horizontally centered)</h1>
<div class="container1">
<img class="fill-vertical" src="https://dummyimage.com/100x100/000/fff">
</div>
<h1>Container 300px x 500px, not filled</h1>
<div class="container2">
<img class="fillIt" src="https://dummyimage.com/100x100/000/fff">
</div>
<h1>Container 300px x 500px, filled horizontally, should be vertically centered</h1>
<div class="container2">
<img class="fill-horizontal" src="https://dummyimage.com/100x100/000/fff">
</div>
In the current code, I have to assign different classes to the image depending on whether I want vertical or horizontal stretching, but ideally I want CSS to handle this automatically: only one stretch class should be needed.
In summary, what I need CSS to do is: stretch width and/or height to fit available space while maintaining aspect ratio