Preventing Layout Reflow for Fluid Sized Images

One problem I had with redoing my blog was noticing that the sidebar photo was causing a layout reflow. This is because the image has a fluid size and until the image loads, the browser does not give the image a width or height and just renders the border radius as a small black circle:

No css properties

This is how the CSS for this looks:

.container {
width: 45%;
}

.img {
border-radius: 50%;
}

However, historically if you know the aspect ratio of the image you could resolve this with a bit of a work around using positioning and padding like so:

.container {
position: relative;
width: 45%;
padding-top: 45%;
}

.img {
position: absolute;
top: 0;
border-radius: 50%;
}

This 'works', but feels like a bit of a hack. It also has the side effect of rendering the border radius as a black circle until the image actually loads. So although there is no reflow of the structure of the site, the image itself re-renderers because the image still has size zero until load.

Using a padding hack

With IE now being officially deprecated, we can use the aspect-ratio CSS property to achieve the same effect and also prevent the border radius being rerendered like so:

.container {
width: 45%;
aspect-ratio: 1/1; /** The image is a square so we use a 1/1 aspect ratio! **/
}

.img {
height: 100%;
width: 100%;
border-radius: 50%;
}

Here aspect-ratio represents the aspect ratio of the image in question, in my case it was a square so we used 1/1. This solves the issue:

Using the aspect-ratio property

This feels like a pretty nice improvement! We prevent the reflow caused by the image loading, and we also respect the circular border-radius the whole time.

Published