Positioning Background Images - HTML

The background-position property allows you to position an element’s background image. This property’s use isn’t as straightforward as some of the other properties. The basic forms of the values for this property fall into three categories:

  • Two percentages that specify where the upper-left corner of the image should be placed in relation to the element’s padding area
  • Two lengths (in inches, centimeters, pixels, em, and so on) that specify where the upper-left corner of the image should be placed in relation to the element’s padding area
  • Keywords that specify absolute measures of the element’s padding area No matter what format you use for the background-position values, the format is as follows:
background-position: horizontal—value vertical—value;

Backgrounds scroll by default, as shown by the second paragraph.

Backgrounds scroll by default, as shown by the second paragraph.

You can specify that a background image remain fixed under the element with the background-attachment property.

You can specify that a background image remain fixed under the element with the background-attachment property.

If only one value is given, it is used for the horizontal placement—the image is centered vertically. You can mix the first two formats (for example, 10px 25%), but keywords cannot be mixed with other values (for example, center 50% is invalid). The first two forms are much like the value formats used in other properties. For example, the following definition positions the upper-left corner of the background in the middle of the element’s padding area:

background-position: 50% 50%;

The next definition places the upper-left corner of the background 25 pixels from the top and left sides of the element’s padding area:

background-position: 25px 25px;

Several keywords can be used for the third format of the background-position property. They include top, left, right, bottom, and center. For example, you can position the background image in the top, center of the element’s padding using the following:

background-position: top center;

Or, you can position the background image directly in the center of the element’s padding with the following:

background-position: center center;

Tip:Combining the background attributes can achieve more diverse effects. For example, you can use background-position to set an image in the center of the element’s padding, and specify background-attachment: fixed to keep it there. Furthermore, you could use background-repeat to repeat the same image horizontally or vertically, creating dynamic striping behind the element.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

HTML Topics