<< Back to Blog

21 NOVEMBER 2019

CSS: How to leave placeholder space for an image (or block) using CSS

Prerequisite: You know the aspect ratio for the image e.g. 16:9.

Steps:

  1. Wrap the image in a parent element (e.g. a div) which will act as the placeholder space for the image.
  2. Set the parent padding-top to a percentage of the width that gives the aspect ratio you want. E.g. padding top of 62.5% gives a 8:5 ratio. This works because padding top/bottom on an element is based on the current width. This means regardless of the current size of the image (large/small device) the ratio will be correct.
  3. Finally, position the image in the space left by this padding. Set the image position: absolute so it fills the exact space left for it. The effect of this is that when the image loads it will sit in the exact space left for it, and not move the positioning of other elements around it.

HTML

<div class="block-placeholder block-ratio-5by8">
    <img src="~/images/abc.jpg" class="figure-img" alt="An image">
</div>

CSS

.block-placeholder {
    position: relative
    overflow: hidden
    display: block
}

.block-ratio-5by8 {
    padding-top: 62.5%
}

.figure-img {
    left: 0
    right: 0
    top: 0
    bottom: 0
    position: absolute
    height: 100%
    width: 100%
}

As a final step you can set {image} max-width: 100% to ensure it never overflows the space left for it. Alternatively you can use width: 100% as I have above to ensure it is always stretches to fill the space - with the caveat that this may lead to the image being blurry if it is stretched too much.

Ensure you have a comprehensive set of image crops (with the same ratio) to handle all screen sizes you intend to support.

Example

Before image loads, placeholder space:
╭──────────────────╮
│▲                 │
│|                 │
│62.5%             │
│|                 │
│▼◄------100%-----►│
╰──────────────────╯

When image loads it fills space:
╭──────────────────╮
│         //\\     │
│        //  \\    │
│   //\\//    \\   │
│  //  //      \\  │
│ //. _. _. _. _\\ │
╰──────────────────╯