background-attachment
The background-attachment
is used for setting the behavior of the background image position when users are scrolling the screen. There are several property values you can set. In this section, we'll explain basic ones – scroll
and fixed
.
iOS browser support
This property may not properly work on iOS (iPhone and iPad).
scroll
The scroll
keyword is the default setting of this property. With this setting, the background image moves along with the element.
fixed
When you use the fixed
keyword, the background image stays in the same position relative to the browser window even when users scroll the screen.
Practice
Objective:
Test scroll and fixed in the background-attachment property
1. Prepare image files
We are using a palm tree icon. You can prepare any image but use a small image with weak color. Save the image file under the img
directory of the project.
2. Update the HTML file with the scroll keyword
Add the code below at the end of the body section in the chapter12.html file. To test the background-attachment
property, we are adding CSS code. For practice purposes, we are adding the <style>
tag in the middle of HTML. Usually, it should be written in the <head>
section or in a separate CSS file.
With this code, we test the scroll
keyword first.
<h2>Background Attachment</h2>
<p>Check the right top icon</p>
<style>
body{
background-image: url(img/palm-tree-round.png);
background-size: 100px;
background-repeat: no-repeat;
background-attachment: scroll;
background-position: 98% 10%;
}
</style>
3. Check the result with a browser
- Open chapter12.html with a browser.
- You can see that an icon is created at the top right of the window and the icon is moving along with the body element when you are scrolling.
4. Update the HTML file with the fixed keyword
Now, change the keyword to fixed.
:
background-attachment: fixed;
:
5. Check the result with a browser
- Open chapter12.html with a browser.
- You can see that the icon position is fixed (doesn't move) when you are scrolling.
You can also check the sample result here (Demo Site). The demo may not work on iOS.