Generate HTML code for a Transparent Header. The header will become sticky on reaching a scroll distance of 300px. On becoming sticky the background of the header will become white.

Home » Snippets » Generate HTML code for a Transparent Header. The header will become sticky on reaching a scroll distance of 300px. On becoming sticky the background of the header will become white.
0

Created with:

Visibility: 

public

Creator: Vikas Gautam

Customize With AI
					<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Transparent Sticky Header</title>
  <style>
    body {
      margin: 0;
      padding: 0;
    }
    .header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      padding: 20px;
      background-color: transparent;
      transition: background-color 0.5s ease;
    }
    .sticky {
      background-color: white;
    }
    .content {
      height: 2000px;
      padding-top: 60px; /* To push content down and avoid overlapping with header */
    }
  </style>
  <script>
    window.addEventListener('scroll', function() {
      var header = document.querySelector('.header');
      var scrollDistance = window.pageYOffset;
      if (scrollDistance >= 300) {
        header.classList.add('sticky');
      } else {
        header.classList.remove('sticky');
      }
    });
  </script>
</head>
<body>
  <header class="header">
    <!-- Header content goes here -->
  </header>
  <div class="content">
    <!-- Page content goes here -->
  </div>
</body>
</html>

				

Explanation:

In this code, we start with a basic HTML structure. We use the <header> tag for the transparent header and the <div> tag for the page content. The CSS styles are added in the <style> element within the <head> section. The header is initially transparent with a background-color: transparent;. We add a CSS transition effect to smoothly change the background color when the header becomes sticky.

To make the header sticky, we use JavaScript. We listen for the scroll event on the window object. When the scroll distance exceeds 300 pixels (you can adjust this value as per your requirement), we add the sticky class to the header, which applies the white background color. Otherwise, we remove the sticky class to restore the transparency.

Remember to replace the <!– Header content goes here –> and <!– Page content goes here –> comments with your actual header content and page content, respectively.

Feel free to customize the styles and adjust the scroll distance as per your needs.

Register an account to save your snippets or go Pro to get more features.