Positioning Background Images with CSS

A background image can be positioned in a number of places within an element’s box. The property used to do this is the background-position property and it allows you to specify where in the browser window to place a background image that is not repeated. It is non-inherited and typically takes a pair of values. The first value specifies the horizontal position and the second the vertical. Each pair can be a pair of keywords, length values (such as px and em), or percentage values. The allowed keyword pairs and the demonstration of how they position a background image are shown in Figure 15.40. One way to look at it is that you can only specify left, center, and right for the first value, and top, center, and bottom for the second. If only one value is specified, a default of center is used for the other.

Figure 15.41 shows how keyword values are used with the background- position property and Figure 15.42 the result. In the example, the background- image property specifies the URF of the image to use for the <body> element’s background, the background-repeat property says not to repeat the image, the background-attachment property specifies to make the position fixed, the background-position property says to position it at the horizontal and vertical center of the page (i.e., the <body> element), and padding specifies the space between all the contents of the <body> element and the edges of the element’s box. Note that if the height for the element containing the image is not specified, the vertical positioning may not work properly, unless the background-attachment: fixed declaration is also included to fix the image, as used in the example.

Figure 15.43 shows how the same example in Figure 15.41 and Figure 15.42 can be achieved with percentage values. The values represent, respectively, the horizontal and vertical distances from the top-left corner of the browser window, which is 0% 0%. So, 50% 50% specifies a position that is 50% of the browser’s width and 50% of the height from the top-left corner.

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 *