Computer >> Computer tutorials >  >> Programming >> CSS

How to shrink a header on scroll with CSS and JavaScript?


To shrink a header on scroll with CSS and JavaScript, the code is as follows −

Example

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      margin: 0px;
      padding: 0px;
      height: 150vh;
   }
   .header {
      position: fixed;
      top: 0;
      width: 100%;
      background-color: rgb(52, 21, 110);
      color: white;
      padding: 50px;
      font-size: 40px;
      transition: 0.8s;
   }
</style>
</head>
<body>
<div class="header">Header Text</div>
<p style="font-size: 35px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit vel dolore delectus 
esse consequatur at nulla, consequuntur sint quas ea. Incidunt, ex. Consequatur ipsa 
earum veritatis fugiat iusto, doloremque sunt beatae quaerat laboriosam nemo soluta 
quidem porro quia. Dolore reprehenderit cum
voluptatibus eius assumenda ipsam tenetur asperiores magni aliquid eligendi doloribus 
quidem ipsa et praesentium provident molestias quaerat laboriosam, veniam aspernatur 
repellendus. Debitis sapiente, odit iste voluptatibus nesciunt veritatis incidunt
 mollitia nostrum, vitae suscipit iusto molestias consequuntur rem facere perspiciatis 
ad! Ratione reiciendis asperiores aperiam vitae facilis accusantium non aliquid, facere 
cupiditate reprehenderit tempore veritatis eum accusamus omnis
tempora quos!</p>
<script>
   window.onscroll = function() {resizeHeader()};
   function resizeHeader() {
      if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
         document.querySelector(".header").style.fontSize = "20px";
      } else {
         document.querySelector(".header").style.fontSize = "40px";
      }
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

How to shrink a header on scroll with CSS and JavaScript?

On scrolling down a little the header font size will shrink as follows −

How to shrink a header on scroll with CSS and JavaScript?