Background-position controls the placement of a background image within its container element. It allows you to position the image in various ways, such as centered, top-left, bottom-right, or even with custom offsets.
Syntax
background-position: <position1> <position2>;
<position1> and <position2>: Specify the horizontal and vertical positions of the background image, respectively.
Values
- Keyword values:
top: Aligns the top edge of the image with the top edge of the container.right: Aligns the right edge of the image with the right edge of the container.bottom: Aligns the bottom edge of the image with the bottom edge of the container.left: Aligns the left edge of the image with the left edge of the container.center: Centers the image both horizontally and vertically.
- Percentage values:
- Specify the position relative to the container’s dimensions. For example,
50% 25%places the center of the image at the horizontal midpoint and 25% down from the top.
- Specify the position relative to the container’s dimensions. For example,
- Length values:
- Specify the position in pixels, ems, rems, or other length units. For example,
10px 20pxplaces the top-left corner of the image 10 pixels from the left edge and 20 pixels from the top edge.
- Specify the position in pixels, ems, rems, or other length units. For example,
Common Use Cases
- Centering an image:
background-position: center;
- Positioning an image in the top-left corner:
background-position: top left;
- Creating a parallax effect:
- Use percentage values and adjust the position based on scrolling or other interactions to create a depth effect.
- Customizing image placement:
- Experiment with different keyword, percentage, and length values to achieve your desired positioning.
Best Practices
- Use meaningful and descriptive values: Avoid using arbitrary numbers or percentages that are difficult to understand later.
- Consider responsiveness: If your layout is responsive, ensure that the background position adapts appropriately to different screen sizes.
- Test across different browsers and devices: Verify that the positioning works as expected in various environments.
- Combine with other background properties: Use
background-size,background-repeat, andbackground-attachmentto create complex background effects.
Example
.container {
background-image: url("image.jpg");
background-size: cover;
background-position: right bottom;
}
This example places the image in the bottom-right corner of the container and scales it to cover the entire container.