Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reserving space for auto sized img

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.

like image 741
Xyand Avatar asked Oct 21 '22 09:10

Xyand


1 Answers

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

like image 159
Brian FitzGerald Avatar answered Oct 24 '22 03:10

Brian FitzGerald