<< Back to Blog

17 DECEMBER 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. Calculate this value using the formula: [(height * 100) / width]. Worked example: Image dimensions of 2000px width by 1250px height will give padding-top: 62.5%; [worked out as (1250 * 100) / 2000 = 62.5]. This works because in CSS padding top/bottom percentages are relative to the width. This means regardless of the display size of the image (large/small device) the ratio will remain correct.
  3. Finally, position the image in the space created by the parent <div>. 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 fill the exact space left for it, and not change the positioning of 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:
╭──────────────────╮
│         //\\     │
│        //  \\    │
│   //\\//    \\   │
│  //  //      \\  │
│ //. _. _. _. _\\ │
╰──────────────────╯