The background-position property in CSS is used to control the position of a background image within an element. By default, the background image is placed at the top-left corner, but you can move it to the center, bottom, or to any specific offset using keywords, percentages, or pixel values.
background-position controls where the background image is drawn inside the box.top, center, bottom, left, right.top left, center center, top center.background-position: 50px 100px; or 50% 50%.background-repeat and background-size for better control.Basic pattern: background-position: x-position y-position;
/* Basic background-position syntax */
selector {
background-position: x-position y-position;
}
Below are a few common ways to position background images using keywords and pixel values.
/* Top-left position */
.container-box {
background-image: url('https://via.placeholder.com/300x150');
background-position: top left;
background-repeat: no-repeat;
background-size: cover;
}
/* Centered position */
.centered-background {
background-image: url('https://via.placeholder.com/300x150');
background-position: center;
background-repeat: no-repeat;
background-size: contain;
}
/* Custom pixel values */
.custom-position {
background-image: url('https://via.placeholder.com/300x150');
background-position: 50px 100px;
background-repeat: no-repeat;
background-size: contain;
}
Here we used:
background-position: center center; to place the focal point in the middle.background-size: cover; (via inline style) so the image covers the entire box.background-repeat: no-repeat; (implicit when using cover) to avoid tiling.Some useful background-related properties that are commonly used together:
| Property | Description | Example Value |
|---|---|---|
background-position |
Position of the background image inside the element. | top left, center, 50px 100px |
background-repeat |
Controls whether the background image repeats. | repeat, no-repeat |
background-size |
Controls how the background image is scaled. | cover, contain |
background-position: 50% 50%) for more flexible, responsive positioning.background-position: 10px 20px to move the image from the top-left corner.background-position: 50 100; ❌ vs background-position: 50px 100px; ✅.background-size: cover or contain to keep the image looking good on different screen sizes.background-repeat: no-repeat;.center or center center when you want the main subject always visible in the middle.<div> with a background image and experiment with: background-position: top left, center, and bottom right. Observe how the visible area changes.background-position: 50px 50px; to “nudge” the image into the exact spot you want.background-position with background-size: cover and background-size: contain and compare the results on different screen sizes..top-left, .centered, and .custom-position classes to solidify the concept.