Sizing Background Images with CSS

The size of background images is controlled with the background-size property. It is non-inherited and the standard values it supports are listed in Table 15.7. Figure 15.31 shows a two-value example and Figure 15.32 the rendered result.

In the body{} rule in the example, background-image specifies the image to use for background, background-repeat says to repeat the image across the x-axis, and background-size says to resize it to 80 x 80. The hi, h2, p{} rule horizontally centers the content of the <h1>, <h2>, and <p> elements. Note that the auto and percentage values can be specified the same way as px. The example also displays the image in its actual size using the <img> element.

1. background-size with Keywords

When using keywords to size an image, only one value (i.e., cover or contain) can be specified. Figures 15.33 and 15.34 show the usage and the different results they produce. In the div{} rule in the example, the width and height properties specify the size of the <div> element, border makes the element’s border lpx-thick solid line and black, background-image specifies the image to use as background (i.e., yacht.jpg), and background- repeat says not to repeat it. The #cover{} rule says to scale the image so that it covers the entire background position area (i.e., containing <div> element), which means that some part of the bottom has to be cut off.

Figure 15.35 shows the result of Figure 15.33 with the value of the background- size property changed to contain in the ,cover{} rule. The resulting rule therefore says to scale the background image so that it is contained in the element, which means part of the container is left unfilled.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *