Background Position
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <h1>Background Position</h1> <div id="big-game-image"> <p>Big Game Image</p> </div> <div id="big-game-image-center"> <p>Big Game Image - centered so a slightly different part of the image is visible</p> </div> <div id="small-game-image"> <p>Small Game Image</p> </div> <div id="small-game-image-center"> <p>Small Game Image - centered in the middle of the div area</p> </div> <div id="small-game-image-percentage-position"> <p>Small Game Image - 30% from the left and 70% from the top</p> </div> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
div { height: 300px; color: white; border: 2px solid yellow; } #big-game-image { background-image: url('../images/big-game.jpg'); background-repeat: no-repeat; background-size: cover; } #big-game-image-center { background-image: url('../images/big-game.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center; } #small-game-image { background-image: url('../images/small-game.jpg'); background-repeat: no-repeat; } #small-game-image-center { background-image: url('../images/small-game.jpg'); background-repeat: no-repeat; background-position: center; } #small-game-image-percentage-position { background-image: url('../images/small-game.jpg'); background-repeat: no-repeat; background-position: 30% 70%; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
background-position
In CSS, background-position
is a property that determines the starting position of a background
image
within its containing element. It accepts two values: a horizontal value (left, center, right, or a pixel or
percentage value) and a vertical value (top, center, bottom, or a pixel or percentage value). These values
define the
starting point of the background image relative to the top-left corner of the element.
For example, background-position: center top;
will center the background image horizontally and
position
it at the top of the element, while background-position: 20px 50%;
will position the background
image 20
pixels from the left of the element and halfway down the element vertically. The default value of
background-position
is 0% 0%, which places the background image at the top-left corner of the element.
Experiment with the Code
- Try adding your own background image and experimenting with each of the
background-position
values.
Video and Code References
Questions? Subscribe and ask in the video comments: