What’s the math behind CSS’s background-size:cover

Here’s a logic behind cover calculations.

You have four base values :

imgWidth // your original img width
imgHeight

containerWidth // your container  width (here 698px)
containerHeight

Two ratios derived from these values :

imgRatio = (imgHeight / imgWidth)       // original img ratio
containerRatio = (containerHeight / containerWidth)     // container ratio

You want to find two new values :

finalWidth // the scaled img width
finalHeight

So :

if (containerRatio > imgRatio) 
{
    finalHeight = containerHeight
    finalWidth = (containerHeight / imgRatio)
} 
else 
{
    finalWidth = containerWidth 
    finalHeight = (containerWidth / imgRatio)
}

… and you have the equivalent of a background-size : cover.

Leave a Comment

tech