Background Size
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 Size</h1> <div id="big-game-image"> <p>Big Game Image</p> </div> <div id="small-game-image"> <p>Small Game Image - when set to a background size of cover, it looks blurry b/c of the original image size</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; } #small-game-image { background-image: url('../images/small-game.jpg'); background-repeat: no-repeat; background-size: cover; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
background-size
In CSS, background-size
is a property that specifies the size of an element's background
image. The
property accepts various values, including auto, contain, and cover, as well as specific lengths and
percentages.
The contain
value scales the background image to fit within the element's content area while
maintaining the image's aspect ratio. On the other hand, the cover
value scales the background
image
to completely cover the element's content area, while also maintaining its aspect ratio.
The background-size
property can also take two values separated by a comma to set different values
for
the horizontal and vertical dimensions of the background image. Additionally, the property can use the
background-size
shorthand to set both the size and position of the background image at once.
Experiment with the Code
- Try adding your own background image and experimenting with each of the
background-size
values.
Video and Code References
Questions? Subscribe and ask in the video comments: