<< Back to Blog

21 NOVEMBER 2019

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

Prerequisite: The aspect ratio of the placeholder space is known. E.g. an image with ratio 16:9.

There are two key steps:

  1. Wrap the image in a parent element (e.g. a div). Give the parent padding-top of 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.
  2. Next, have the image sit in the space left by this padding. Set the image positioning to absolute so it fills the exact space left for it. This means when the image loads it will not move the positioning of other elements on the page as it appears.

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 below 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. Best to ensure you have the correct image crops to handle all screen sizes you intend to support.


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


.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%