Static background on a web page

When creating designs using HTML and CSS we can have a static background on a web page, regardless of the scroll that the user performs on said page.

Achieving this effect within a web page will be useful in many cases, for example when we want to have a shield, a logo, etc. in the background… We must keep in mind that if we put a background image, by default, the background will be repeated as many times as the web page is.

To have a static background on a web page we will rely on the CSS

background
. The first attribute that we must know is
background-image
. This attribute allows us to specify the image to be placed in the background of the web page.

In this way the code to use will be the following:

body {
  background-image: url('https://lineadecodigo.com/wp-content/uploads/2006/12/w3c.jpg');
}

We will use the url() function to reference the file to use.

Once we have the image in the background, let’s see how to fix it. To do this we use two other attributes:


  • background-repeat
    , which indicates how the image will be repeated in the background, whether vertically, horizontally, in both directions or not at all (no-repeat value). The latter will be our case.

  • background-attachment
    , through this attribute we will indicate if the image is going to remain fixed (fixed) or will scroll with the rest of the page (scroll).

Finally the code to have a static background on a web page will look like this:

body {
 background-image: url('https://lineadecodigo.com/wp-content/uploads/2006/12/w3c.jpg');
 background-repeat: no-repeat;
 background-attachment: fixed;
}

We will simply have to put this class CSS in the element
style
of our website and we will have the desired effect:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document Title</title>
  <style>
    body {
      background-image: url('https://lineadecodigo.com/wp-content/uploads/2006/12/w3c.jpg');
      background-repeat: no-repeat;
      background-attachment: fixed;
    }
  </style>
</head>
<body>

<!-- HTML5 document -->

</body>
</html>

As you can check, it is something simple and very useful.

Leave a Comment