Grotle
Grotle

Reputation: 53

Background fixed with regard to viewport, but also scrolling

In a <section>, I have a background-image with a fixed position, like this:

  section {
    background: url("/images/bergen_background.png"), rgba(0,0,0,0.5);
    background-blend-mode: color-dodge;
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-size: cover;
  }

What I want is to have it scroll when it has reached the end of the <section>, and I've been able to add the JS logic to add a CSS class, section.bottom, which will remove the fixed property for the background.

However, when I remove the fixed property and scroll down, the background-size: cover seem to break and the background-image seem to not fit the entire image in the viewport.

  section.bottom {
    /* what do I add here? */
  }

What do I do to have a background-image not-scroll and then scroll while having the background-image be fixed with regard to the viewport?

First image is before scroll reached end of the element, second is after scroll has reached the end of the element

first image is fixed and the second image removed the fixed

Reproduced here: https://svelte.dev/repl/04b96435904e4625a3ddbcc28bd7054f?version=3.38.2

Upvotes: 0

Views: 1069

Answers (1)

Ghost
Ghost

Reputation: 5019

I think that I have fixed your problem but not sure.

I just thinking about idea which might solve the problem my idea like below :

First : remove background-size: cover; and add

background: url(<image>) center top no-repeat fixed;
background-size: auto <width size in %>; /*Beacause background-size: cover; 
creates the scrolling issue.*/

Second : with the logic JS you can change background-attachment: fixed; into background-attachment: scroll;.

I think now everything is good.

Upvotes: 1

Related Questions