Background Attachment
Exercise
- Download the image from this GitHub repository: https://github.com/learn2buildapps/CSS_Background_Attachment/blob/main/images/another-game.jpg
- Place the image you downloaded into the "images" folder.
- 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 Attachment</h1> <div id="big-game-image"> <p>Big Game Image</p> </div> <div id="another-game-image"> <p>Another Game Image</p> </div> <div id="big-game-image"> <p>Big Game Image</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: 100vh; color: white; border: 2px solid yellow; } #big-game-image { background-image: url('../images/big-game.jpg'); background-repeat: no-repeat; background-size: cover; } #another-game-image { background-image: url('../images/another-game.jpg'); background-repeat: no-repeat; background-size: cover; background-attachment: fixed; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
background-attachment
In CSS, the background-attachment
property specifies whether the background image is fixed or
scrolls
along with the content. It can take one of the following values:
scroll
: The background image scrolls along with the content.fixed
: The background image is fixed relative to the viewport. It does not move even when the content is scrolled.local
: The background image scrolls along with the element it is applied to.
By default, background-attachment
is set to scroll
.
Parallax Effect
A parallax effect is a visual technique used in web design where the background of a webpage moves at a slower pace than the foreground, creating an illusion of depth and dimensionality. This effect is achieved by applying different scrolling speeds to different layers of content on the webpage. As the user scrolls down the page, the foreground elements move faster than the background elements, creating a dynamic and engaging visual experience.
Experiment with the Code
- Try adding your own background image and experimenting with each of the
background-attachment
values.
Video and Code References
Questions? Subscribe and ask in the video comments: