VatsalSura VatsalSura - 4 months ago 10
Javascript Question

Background Image not remaining fixed on scrolling

I am new to HTML/CSS and I am designing a basic web-page. I added a Background Image and showing information on it. But, when I scroll the webpage, the image remains fixed on the starting and when I scroll down, it doesn't show any background. I have attached the image below describing my problem.

This is my page on opening HTML file
This is my page on opening HTML file

And this is my page on scrolling down
And this is my page on scrolling down

This is my code:

<!DOCTYPE html>
<html>
<head>
<title>
CSS | HOME
</title>
</head>
<style>
h2
{
color: yellow;
font-family: courier;
}
body
{
position: absolute;
top = 0;
bottom = 0;
left = 0;
right = 0;
background-image:url("tomb_raider_definitive_edition.jpg");
background-repeat: no-repeat;
background-size: cover;
}
.noselect /* Disable Copy Text */
{
-moz-user-select:none; /* Mozila FireFox */
-ms-user-select: none; /* Internet Explorer */
-webkit-user-select: none; /* Chrome, Safari, and Opera */
}

</style>
<body>
<span style="color:red"></span>
<h2 class="noselect; h2">TOMB_RIDER (2013)</h3>
<pre class="noselect">
<!-- Some Info here -->
</pre>
<p class="noselect" style="font-family: verdana;"><strong>TOMB_RIDER</strong></p>
<a href="https://upload.wikimedia.org/wikipedia/en/f/f1/TombRaider2013.jpg">
<img src="TombRaider2013.jpg">
</a>
<table border="1px"; style="border-style:solid;" class="noselect">
<!-- Table code-->
</table>
<h2 class="noselect">Requerment !</h2>
</body>
</html>


What I want is that the background image should remain fixed and only the content should be scrolled.

I also tried
position: relative;
and
position: fixed;
, but none of them is working. I also searched on SO and W3Schools before asking it, but I couldn't find solution to my problem.

Any kind of help would be appreciated. Thank you.

Answer

According to W3schools

background-attachment: scroll|fixed|local|initial|inherit;

Check this property this will solve your problem..

Here the value "fixed" is used to fixed the background with regard to the viewport.

You can edit your code like this-

body
{
    background-attachment: fixed;
    position: absolute;
    top = 0;
    bottom = 0;
    left = 0;
    right = 0;
    background-image:url("tomb_raider_definitive_edition.jpg");
    background-repeat: no-repeat;
    background-size: cover;
}

Hope this helps.