CSS
π― What is background-position?
The background-position property determines the starting position of a background image.
It is commonly used to precisely align background images in:
- hero sections
- banners
- cards
- buttons
- fullscreen backgrounds
π§© Simple Definition
CSS
background-position = controls where the background image appears
π‘ Basic Syntax
CSS
background-position: value;
π§ Example
CSS
background-position: center;
π This centers the background image inside the element.
βοΈ Accepted Values
| Value Type | Description |
|---|---|
| length | Uses units like px, em, rem |
| % | Uses percentage positioning |
| position keywords | Uses keywords like top, center, left |
| initial | Resets to default value |
| inherit | Inherits from parent element |
πΉ Position Keywords
CSS provides predefined keywords for positioning.
| Keyword | Description |
|---|---|
| top | Aligns image to the top |
| right | Aligns image to the right |
| bottom | Aligns image to the bottom |
| left | Aligns image to the left |
| center | Centers the image |
π§© Common Examples
Centered Image
CSS
background-position: center;
Top Left Corner
CSS
background-position: left top;
Bottom Right Corner
CSS
background-position: right bottom;
Horizontal and Vertical Center
CSS
background-position: center center;
π This is equivalent to:
CSS
background-position: center;
πΉ Using Length Values
You can position the image using fixed units.
CSS
background-position: 50px 100px;
π This means:
- 50px from the left
- 100px from the top
πΉ Using Percentage Values
CSS
background-position: 50% 50%;
π Positions the image at the center.
π§© Practical Examples
1. Hero Section Background
CSS
.hero {
background-image: url("hero.jpg");
background-position: center;
}
2. Top Banner Image
CSS
.banner {
background-image: url("banner.jpg");
background-position: top center;
}
3. Bottom Right Logo
CSS
.card {
background-image: url("logo.png");
background-position: right bottom;
}
π¨ Common Usage with Other Background Properties
background-position is usually combined with:
| Property | Purpose |
|---|---|
| background-image | Defines the image |
| background-size | Controls image size |
| background-repeat | Controls repetition |
π§© Full Example
CSS
.hero {
background-image: url("background.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
π§ Explanation
cover
Makes the image fill the element.
center
Keeps the image centered.
no-repeat
Prevents image repetition.
β οΈ Important Note
If the image is larger than the container, parts of it may become hidden depending on the chosen position.
Using:
CSS
background-position: center;
usually creates the best visual balance for responsive designs.
