Change Div Width on Scroll

In this tutorial, you will learn how to change div width on scroll with CSS & JavaScript. The div's width will shrink when scrolled down and then expand on scroll up. The tutorial also includes doing it vice versa. Watch the video below for a detailed tutorial.


  <div class="container">
    <div id="expand"></div>

    function changeWidth() {
      var scroll = (window.pageYOffset / 5);
      var width = scroll;
      // var width = Math.min(100 - scroll);

      document.getElementById('expand').style.width = width + '%';

    window.addEventListener('scroll', function(){


body {
  background: #2e3537;
  margin: 0;
  height: 100vh;

.container {
  margin-top: 450px;
  position: relative;

#expand {
  background: #0380A7;
  /* width: 100%; */
  min-width: 20%;
  min-height: 400px;
  position: absolute;
  will-change: width;