Background Positions

The background-position property in CSS takes two values - the first identifies the horizontal position of the background image and the second identifies its vertical position (when specified as lengths or percentages).. The same vales in the same order can also be used in the shortcut background property where you define all the properties for the background at once.

The first thing to note about this property is that apart from lengths and percentages it can also take positioning names top, center, bottom for vertical position and left, center, right for horizontal position. Peculiarly when these are used the vertical position can precede the horizontal one although since the names are different for each direction the order doesn't matter since the browser can easily determine what is meant regardless of order. Where only one positioning name is used the second defaults to center (this also applies if only a horizontal length or percentage is specified). Also you can't combine the names with lengths or percentages but you can use one length and one percentage. Since there are percentage equivalents to each name this restriction doesn't cause any problem.

Where lengths are used for background-position the lengths specified indicate the distance from the top left corner of the element (inside the padding) to the top left corner of the background image. So if background-position:1cm 2cm; is specified then the top left corner of the background image will be one centimetre to the right and two centimetres down from the top left corner of the element.

Percentages work somewhat differently since it is not necessarily the top left corner that it is positioning - in fact that is only the case where 0 0 is specified. While 0% will position the image at the top or left (depending on which is set to zero) 100% will position it bottom right and 50% will centre it. The percentage indicates both the percentage of the way across or down the element and also the percentage of the way across or down the background that is to be aligned to that position.

A horizontal position of 20% therefore means that if you divide the width of the element into five parts and the background image also into five parts then the left most of the five parts in the background image will be right aligned within the leftmost part of the element. A vertical position of 20% would mean dividing both heights into five parts and bottom aligning the topmost part of the image in the topmost part of the element.

diagram showing placement of image at 20%

Of course the horizontal and vertical percentages do not have to be the same.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate