Home > Software engineering >  How to make background image stay while text scrolls? (Safari)
How to make background image stay while text scrolls? (Safari)

Time:11-06

Before you try to close: I know that there are similar questions and answers out there, however none of these solutions work for me, rather just locking scrolling all together. This could possibly be because I am using a website template from w3schools.

I am making a website for a school project where I would like the background to be a picture of tree leaves. Unfortunately, this image doesn't seem to cover the full page, causing it to repeat downwards. This is an issue.

I have used background-attachment: fixed; to solve this issue on chrome (for windows), but have discovered that safari does not support this.

The website's code can be accessed: here. (Control U for page source)

tldr; I need to find an equivalent to background-attachment: fixed; for safari that works for my website.

TIP: You will have to test the page in safari to see the issue.

CodePudding user response:

You can't keep the background on the actual body in this case because of the Safari attachment-fixed problem as you point out.

You can however put the background on a pseudo element and then use the 'ordinary' CSS fixed position so it stays in place even as you scroll down.

Here's a basic example:

body {
  width: 100vw;
  height: 200vh;
  margin: 0;
  padding: 0;
}

body::before {
  content: '';
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-image: url("https://hdwallsource.com/img/2014/5/green-background-21874-22427-hd-wallpapers.jpg");
  background-size: cover;
  z-index: -1; /* added */
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note: the background size is set to cover so the whole viewport is covered whatever its aspect ratio (some of the img may get cropped either top/bottom or at the sides so that it fits).

  • Related