5

I am looking for a way to animate (with @keyframes, transform...) some elements when the user scrolls the page. For example:

  • When offset is 0: div has height: 100px.
  • When offset is between 0 and 100: div is height: 50px and color: blue.
  • And so on...

Is is possible using pure CSS? If it is not, what are the most efficient ways to do it with HTML or Javascript?

5 Answers5

6

The most efficient way to animate an element's style properties depending on scroll position will probably be to add a class with a scroll function:

Working Example

myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y > 500) {
    // myID.style.backgroundColor = "blue"; // you can add individual styles 
    myID.className = "blue" // or add classes
  } else {
    // myID.style.backgroundColor = "red";
    myID.className = "red"
  }
};

window.addEventListener("scroll", myScrollFunc);
body {
  height: 1100px;
}
#myID {
  position: fixed;
  height: 100px;
  line-height: 20px;
  transition: all 1s;
}
.blue {
  background: blue;
  animation: myAnimation 1s both;
}
.red {
  background: red;
}
@keyframes myAnimation {
  0% {
    border-radius: 0px;
    line-height: 10px;
  }
  100% {
    border-radius: 100%;
    line-height: 100px;
  }
}
<div id="myID" class="red">Hello world</div>

Docs:

.scrollY
.className
.addEventListener

apaul
  • 16,092
  • 8
  • 47
  • 82
1

Methinnks it's not possible to 'spy' scroll with pure css. If you want, you can do this with jQuery:

$(document).scroll(function() {
    var pos = parseInt($(document).scrollTop())

    if(pos == 0) {
        $('.yourDivClass').css({
            height : '100px' , 
            color : '#fff'
        })
    }

    if (pos > 0 && pos <= 100) {
        $('.yourDivClass').css({
            height : '50px' , 
            color : 'blue'
        })
    }   

    console.log(pos)
})  

and of course if you wanna get a smooth transition, you supposed to declare transitions in your css file

.yourDivClass {
    transition: height 0.5s ease
}
Dariusz Majchrzak
  • 1,227
  • 2
  • 12
  • 22
0

Scrolling is an event. Once you scroll the page, the event gets triggered and something happens. You cannot control events using Pure CSS. Period.

Some people would argue that even :hover is an event. Yes, and it is for some strange reason, implemented in CSS, but not others.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

With pure CSS: no.

But you can have a class with keyframed animation associated with it, and then say when the element is scrolled into view, to add the class to the element. This will make it start doing the animation.

Community
  • 1
  • 1
Djave
  • 8,595
  • 8
  • 70
  • 124
0

You can use Waypoints.js to set what happens when you reach a specific element of a page.