0

I'm looking for a relatively simple and standard way of changing CSS pseudoelement property value by JS Scrollspy. The parent element (section of a landpage) should change grayscale, while scrolled, and its child should have position:fixed.

As it turns out, it's impossible to make it in an easy way, because any filter is removing position:fixed by definition. More about this: CSS-Filter on parent breaks child positioning

Moving that background-image to a pseudoelement creates another problem: manipulation of the pseudoelement's properties by JS.

The expected result: I wanted to make a section of a landing page, having grayscale filter for background image. That's the easy part. But it should has less grayscale, while moving upward (the more picture user see, the more color it has), and centered content element shuffles up from previous section, and later hiding under next one. So basically I need two things:

  1. filter grayscaled background image, with dynamically changing value of a grayscale, relative to distance to the top of the window (JS scrollspy)
  2. position:fixed central content element visible only in that section

Illustration (with background-picture in pseudoelement) is here: https://codepen.io/tdudkowski/pen/MLyMyG

HTML

<section class="one">
</section>
<section class="two">
  <div><p>DIV with a position:fixed</p></div>
</section>
<section class="three"></section>

CSS

 section {
 position: relative;
 max-width: 1000px;
 height: 70vh;
 background-color: #eee;
 margin: 0 auto;
 overflow: hidden;
}

.two {
 background-color: transparent;
 /* Try to uncomment rule below */
/*  filter: grayscale(50%); */
}

.two div {
 position: fixed;
 left: 50%;
 top: 50%;
 transform: translate(-50%, -50%);
 width: 30rem;
 height: 10rem;
 background-color: #f00;
 z-index: 1;
}

.one,
.three {
 z-index: 100;
}

/* background of section */

section.two::after {
 content: "";
 position: absolute;
 left: 0;
 right: 0;
 top: 0;
 bottom: 0;
 background-image: url(https://picsum.photos/1000/200);
 background-size: cover;
 background-repeat: no-repeat;
 z-index: -1; 
/*   filter: grayscale(50%); */
}
kyle
  • 691
  • 1
  • 7
  • 17
  • You might use a regular element instead of pseudoelement, or since you're using JS scrollspy, you might set `position:absolute` and move your central element with JS scrollspy. – Kosh Jan 28 '19 at 22:54
  • Thank you, it seems that's good idea, with some corrections. First: I had to make new span element specially for background-image (filter given to parent is inherited by children, so to set my central block free f filter, filter must be given to its sibling). Second, if JS is used to position central element it must have position:fixed. This solved my problem, and it works on my target page as well, Here's the solution https://codepen.io/tdudkowski/pen/WPGNOj – tdudkowski Jan 29 '19 at 07:32

0 Answers0