How to Set Background Attachment in CSS
The background-attachment property in CSS sets and controls the background image position on the web page.
Syntax:
background-attachment: scroll|fixed|local|initial|inherit;
The CSS background-attachment property receives multiple values like a fixed, scroll, local, initial, and inherit. The scroll property is the default value, It means the background image will scroll with the page.
Property Values:
Scroll: The scroll is the default value and sets the background image fixed in the web page and scrolls with the page.
background-attachment: scroll;
fixed: The fixed property is used to set background image position fixed in web page and It does not scroll with web page in container.
background-attachment: fixed;
local: This local property is used to set the background image to scroll with the element's contents.
background-attachment: local;
initial: In css initial property is used to set the background-attachment property to its default value.
background-attachment: initial;
inherit: It is used to set the property from its parent element.
background-attachment: inherit;
Examples:
In this example, we are using background-attachment: scroll property. The background image will scroll with web page.
<!DOCTYPE html>
<html>
<head>
<title>How to Set Background Attachment in CSS</title>
<style>
.scrollExample {
background-image: url("https://www.webrecto.com/css/images/webrecto.jpg");
background-position: center;
background-repeat: no-repeat;
background-attachment: scroll; // Background image will scroll
}
</style>
</head>
<body style="text-align:center">
<h1>WebRecto.com</h1>
<h2> background-attachment: scroll;</h2><br><br>
<div class="scrollExample">
<!--Use more content-->
<p>Background image will fixed with content and scroll with page</p>
</div>
</body>
</html>
In this example, we are using background-attachment: fixed property. The background image will not scroll with web page.
<!DOCTYPE html>
<html>
<head>
<title>How to Set Background Attachment in CSS</title>
<style>
.scrollExample {
background-image: url("https://www.webrecto.com/css/images/webrecto.jpg");
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed; // Background image will fixed
}
</style>
</head>
<body style="text-align:center">
<h1>WebRecto.com</h1>
<h2> background-attachment: scroll;</h2><br><br>
<div class="scrollExample">
<!--Use more content-->
<p>Background image will fixed with content and not scroll with page</p>
</div>
</body>
</html>
