Search code examples
htmlcssbackground-image

How can I create a background that tracks the viewport in HTML/CSS?


I am trying to setup a website, and my goal is to create a background that tracks the clients view port. So while the client scrolls through the text, the background stays the same.

I've seen this before on a website somewhere, but can't think of it.

How could I achieve this?


Solution

  • Here it is. I gave custom height to div only for example as it's height is = to inner content.

    For client viewport you have to set min-height to 100vh (vh: viewport height) & width: 100%;

    body {
      margin: 0;
      background: url('https://images.unsplash.com/photo-1574969970937-a90cdcbeea2e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80') no-repeat center;
      -webkit-background-size: cover;
      background-size: cover;
      background-attachment: fixed;
      padding: 60px;
      min-height: 100vh;
    }
    
    div {
      height: 800px;
      background: rgba(255, 255, 255, .6);
      padding: 20px;
      text-align: center;
    }
    <body>
      <div>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, porro ab repellat doloremque reprehenderit dolor minus dolores quia eveniet ducimus, amet, ipsum quidem nesciunt illo assumenda! Architecto distinctio delectus dolorum odio culpa est,
          labore repellendus numquam repellat consequuntur in officiis optio atque, illum ratione eos neque et accusantium iusto voluptas natus dolore sint impedit dignissimos ex. Earum quae impedit obcaecati molestiae minus numquam rerum quos debitis temporibus
          ullam enim rem, quia sit quo? Ad accusantium fugit corporis eligendi numquam nam inventore similique, cumque velit doloribus quis quidem illo dolorem delectus quo magni iusto ab quaerat odit porro. Praesentium, dolor, porro.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, porro ab repellat doloremque reprehenderit dolor minus dolores quia eveniet ducimus, amet, ipsum quidem nesciunt illo assumenda! Architecto distinctio delectus dolorum odio culpa est,
          labore repellendus numquam repellat consequuntur in officiis optio atque, illum ratione eos neque et accusantium iusto voluptas natus dolore sint impedit dignissimos ex. Earum quae impedit obcaecati molestiae minus numquam rerum quos debitis temporibus
          ullam enim rem, quia sit quo? Ad accusantium fugit corporis eligendi numquam nam inventore similique, cumque velit doloribus quis quidem illo dolorem delectus quo magni iusto ab quaerat odit porro. Praesentium, dolor, porro.</p>
      </div>
    </body>