How to Specify a Fixed Background Image in CSS?
We will explore how to specify a fixed background image using the background-attachment property in CSS. This property is used to control the behavior of a background image as the user scrolls through a web page. By using the background-attachment property, you can make a background image fixed, scroll, or local to the element.
What is the background-attachment Property?
The background-attachment property in CSS defines how a background image moves when the page or an element is scrolled. This property is useful when you want to create a visually appealing design by keeping the background image static or scrolling it along with the content.
Values of background-attachment property:
- Scroll: It is the default value for the background-attachment property. It is used to scroll the image with the background page.
- Fixed: The background image will not scroll. It is fixed with the page.
- Local: The background image will scroll with the content.
To keep your background image fixed, you have to use the background-attachment property with the value Fixed.
Syntax:
background-attachment: fixed;
Example: Fixing a Background Image
In this example, we are using the background-attachment property.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
h1 {
text-align: center;
}
#ex {
text-align: center;
background-image:
url("https://media.geeksforgeeks.org/wp-content/uploads/geeks-25.png");
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}
</style>
</head>
<body>
<h1>Example for fixed Background Image</h1>
<div id="ex">
<p>
Paragraphs are the building blocks
of papers. Many students define
paragraphs in terms of length: a
paragraph is a group of at least
five sentences,
</p>
<br><br>
<p>
a paragraph is half a page long,
etc. In reality, though, the unity
and coherence of ideas among
sentences is what constitutes a
paragraph.
</p>
<br><br>
<p>
A paragraph is defined as “a group
of sentences or a single sentence
that forms a unit” (Lunsford and
Connors 116).
</p>
<br><br>
<p>
Length and appearance do not
determine whether a section in
a paper is a paragraph.
</p>
<br><br>
<p>
For instance, in some styles of
writing, particularly journalistic
styles, a paragraph can be just
one sentence long. Ultimately, a
paragraph is a sentence or group of
sentences that support one main idea.
</p>
<br><br>
<p>
In this handout, we will refer to this
as the “controlling idea,” because it
controls what happens in the rest
of the paragraph.
</p>
</div>
</body>
</html>
Output:
Supported Browsers:
- Google Chrome 1.0
- Internet Explorer 4.0
- Firefox 1.0
- Opera 3.5
- Safari 1.0