I want my image to have its width automatically sized (using image aspect ratio). I use something like:
img {
height: 100%;
width: auto;
}
The problem is that until the image is loaded, the browser doesn't reserve horizontal space for it. Is there a way to make the browser reserve space for my image without using javascript?
I know the image aspect ratio as well as the height and width of the full size image.
Actually there is a way to do this as long as you at least know the aspect ratio of the image(s).
The technique I have used successfully involves adding padding to a wrapper around the image based on the image's proportions. This technique was introduced (for video) by Thierry Koblentz and expanded upon (for images) by Anders M. Andersen.
<div class="grumpy-image-wrapper">
<img class="grumpy-image" src="images/grumpy-cat.jpg" />
</div>
<div class="grumpy-image-wrapper">
<img class="grumpy-image" src="images/grumpy-cat.jpg" />
</div>
<div class="grumpy-image-wrapper">
<img class="grumpy-image" src="images/grumpy-cat.jpg" />
</div>
.grumpy-image-wrapper {
width: 90%;
height: 0;
padding-bottom: 66.67%; /* determined by image aspect ratio */
border: 2px solid white;
position: relative;
}
.grumpy-image {
width: 100%;
position: absolute;
}
Read more here: https://www.andyshora.com/css-image-container-padding-hack.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With