CSS background-position
property is used to set the position of the background image relative to the background origin.
By default, the background image is positioned at the top left corner of the element. However, we can change this default position and the background image can be set to any desired position using the background-position
property.
The background image in the below example is set to the center of the body.
Example:
body{ background-image: url('images/smile.png'); background-repeat: no-repeat; background-position: center; }
The background image can be positioned at any corner using two keyword values. See the example below:
Example:
body{ background-image: url('images/smile.png'); background-repeat: no-repeat; background-position: top right; }
CSS Syntax
The background-position
property has the following syntax:
background-position: keyword|posX posY|x% y%|initial|inherit;
Property Values
The background-position
property accepts the following values:
keyword | Specifies background image position using inbuilt CSS keywords like. These keywords are ‘top’ ,’left’, ‘bottom’, ‘right’, ‘center’, ‘top left’, ‘top right’, ‘bottom left’, ‘bottom right’. If only one keyword is specified, the other keyword value is set to ‘center’. |
posX, poxY | Defines the horizontal and vertical position of the background image. The value of posX and poxY can be specified in any valid CSS formats like ‘px’, ’em’ , ‘rem’, etc. |
x%, y% | Defines the position of the background image in percentage. The 0%, 0% sets the background image to the top-left corner and this is the default value. The value 50% 50% is the same as specifying the background-image to the ‘center’. |
initial | Sets the background-position property to its default value(0% 0%). |
inherit | Inherits the background-position property from the parent element. |
General Info
Default Value | 0% 0% |
Inherited | No |
JavaScript Usage | element.style.backgroundPosition = “bottom right” |
More Examples
Set background-position using pixels value.
The background image in the below example is 100px away from the left and 50px away from the top.
Example:
body{ background-image: url('images/smile.png'); background-repeat: no-repeat; background-position: 100px 50px; }
Set the background image using percentage(%) value.
The background image in the below example is 50% away from left and 30% away from the top.
Example:
body{ background-image: url('images/smile.png'); background-repeat: no-repeat; background-position: 50% 30%; }
Related Pages
CSS Tutorial: CSS Background