CSS background – Part 2
background-size
This article gets to grips with the CSS background-size
property. It can take one of five values; length
, percentage
, auto
, contain
or cover
. The last three are more specifically called keywords and our focus here is on the latter.
Although background images are often used in html
and body
tags to completely fill the background of a web page, the same effect can be achieved with any element which senses scaling of the browser window.
cover
cover
scales the image as large as possible to fill the container, stretching the image if necessary. If the proportions of the image differ from the element, it is cropped either vertically or horizontally so that no empty space remains. (MDN 2021)
Contrary to the contain
value, cover
does not squeeze the image. Said differently, a circle will not become an ellipsis, and portraits will not be deformed.
The background images used for this article were saved with intentionally low JPEG qualities both because they would be displayed with pattern overlays, a subtle black cover, blurring and opacity but also to reduce loading times (see note below). For the same reasons no retina-specific images were prepared.
Two test pages are linked to below. They differ in method and visual treatment.
Fig. Blurring an image in CSS is non-destructive and obviates the need for a trip to an external image editor just to create a special version of the image. The downside, however, is that the borders of the image get affected by the gaussian blur, more or less depending on the radius value in the filter: blur()
function. This is visually exaggerated in the image above, showing a lower left corner. Please refer to the Demo 2 page’s source code for a CSS-trick hiding the “debris”.
Images are courtesy of Pixabay.
Note: Backround image file sizes tend to be huge and when a background image is served via CSS, part of the page contents may be put on hold while the large image is downloaded from a server. If this is a concern, do check out Backstretch, a JavaScript alternative which fetches images after the page has loaded. That way a user can start interacting with the page at an earlier stage.
Note also that there is a Part 1 article in this “series” on the background
property.