CSS background-position Property

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:

keywordSpecifies 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, poxYDefines 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’.
initialSets the background-position property to its default value(0% 0%).
inheritInherits the background-position property from the parent element.

General Info

Default Value0% 0%
InheritedNo
JavaScript Usageelement.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

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

Leave a Comment