background-position-x
Definition
The background-position-x
property in CSS specifies the horizontal position of a background image. It can be used to position the background image horizontally within the element's content, padding, or border.
Examples
Positioning the background image at the left edge of the element:
.left {
width: 200px;
height: 200px;
background-image: url('image.jpg');
background-position-x: left;
}
Centering the background image horizontally within the element:
.center {
width: 200px;
height: 200px;
background-image: url('image.jpg');
background-position-x: center;
}
Positioning the background image at the right edge of the element:
.right {
width: 200px;
height: 200px;
background-image: url('image.jpg');
background-position-x: right;
}
Positioning the background image 50 pixels from the left edge of the element:
.distance {
width: 200px;
height: 200px;
background-image: url('image.jpg');
background-position-x: 50px;
}
Positioning the background image 50% of the element's width from the left edge:
.percentage {
width: 200px;
height: 200px;
}
Values
Value | Description |
---|---|
left | The background image is positioned at the left edge of the element. This is the default value. |
center | The background image is centered horizontally within the element. |
right | The background image is positioned at the right edge of the element. |
<length> | The background image is positioned at the specified distance from the left edge of the element. The distance can be specified in any valid CSS length unit, such as pixels (px ), ems (em ), or percentages (% ). |
<percentage> | The background image is positioned at the specified distance from the left edge of the element, as a percentage of the element's width. |
Best Practices
- Use
background-position-x
to specify the horizontal position of a background image. - The default value for
background-position-x
isleft
, which means that the background image is positioned at the left edge of the element. - Use
background-position-x
in combination with other background properties, such asbackground-image
,background-color
, andbackground-position-y
, to create more complex and customized backgrounds. - You can specify the position of the background image in pixels, ems, or percentages using the
<length>
and<percentage>
values forbackground-position-x
. - Use the
background-position-x
property in conjunction with thebackground-position-y
property to specify the position of the background image in two dimensions. - Keep in mind that the
background-position-x
property only affects the positioning of the background image, not the size of the background. To specify the size of the background, use thebackground-size
property.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |