Positioning Background Images with CSS `background-position`: Keywords, Length Units, and Precise Placement
Learn how to precisely control the position of background images within elements using CSS's `background-position` property. This tutorial explains various methods for specifying background image position (keywords, length units), demonstrates their effects, and provides practical examples for creating visually appealing and well-designed web pages.
Positioning Background Images with CSS `background-position`
Understanding `background-position`
The CSS `background-position` property controls the starting position of a background image within its container element. It allows you to place the image precisely where you want it within the element. By default, if you don't set a `background-position`, the image is positioned at the top left corner of the element and repeated both horizontally and vertically.
`background-position` Syntax and Values
The basic syntax is:
background-position:
The `value` can be specified in several ways:
- Keywords:
left
,center
,right
(for horizontal);top
,center
,bottom
(for vertical). You can combine these (e.g., `left top`, `center bottom`). - Percentages: Specifies position as a percentage of the container's width and height (e.g., `25% 75%` positions the image 25% from the left and 75% from the top).
- Lengths: Specifies position using length units (e.g., `30px 80px` positions the image 30px from the left and 80px from the top).
Examples of `background-position`
These examples illustrate different ways to position background images. You'll need to include the corresponding HTML and CSS to see the effects. Each example shows a simple div element with a background image. The CSS then applies `background-position` to control the image's placement. The examples demonstrate positioning using keywords and length units.
Example 1: `background-position: left top;`
Positions the image at the top-left corner.
Example 2: `background-position: top center;`
Positions the image in the center horizontally at the top.
Example 3: `background-position: left center;`
Positions the image in the center vertically at the left.
Example 4: `background-position: left bottom;`
Positions the image at the bottom-left corner.
Example 5: `background-position: center center;`
Centers the image both horizontally and vertically.
Example 6: `background-position: center bottom;`
Centers the image horizontally at the bottom.
Example 7: `background-position: right top;`
Positions the image at the top-right corner.
Example 8: `background-position: top right center;`
Positions the image horizontally centered at the top right.
Example 9: `background-position: right bottom;`
Positions the image at the bottom-right corner.
Example 10: `background-position: 25% 75%;`
Positions the image 25% from the left and 75% from the top.
Example 11: `background-position: 30px 80px;`
Positions the image 30px from the left and 80px from the top.