Sticky header implemented using HTML, CSS, and JavaScript

Daftar Isi

 Below is an example of a sticky header implemented using HTML, CSS, and JavaScript:

<!DOCTYPE html>

<html>

<head>

  <title>Sticky Header Example</title>

  <link rel="stylesheet" href="styles.css">

</head>

<body>

  <header class="sticky-header">

    <nav>

      <!-- Your navigation links go here -->

      <a href="#">Home</a>

      <a href="#">About</a>

      <a href="#">Services</a>

      <a href="#">Contact</a>

    </nav>

  </header>

  <main>

    <!-- The main content of your website goes here -->

    <h1>Welcome to Our Website!</h1>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>

  </main>

  <script src="script.js"></script>

</body>

</html>




css

body {

  margin: 0;

  padding: 0;

}


.sticky-header {

  background-color: #333;

  color: #fff;

  padding: 10px;

  position: fixed;

  top: 0;

  width: 100%;

  z-index: 100;

}


.sticky-header nav {

  display: flex;

  justify-content: center;

}


.sticky-header a {

  color: #fff;

  text-decoration: none;

  margin: 0 10px;

}


main {

  padding: 40px;

}


h1 {

  text-align: center;

}


JavaScript masukkan ke dalam file script.js atau masukkan di html menggunakan <script></script>

// JavaScript is not required for the sticky header effect, but you can add it for additional functionality if needed.

// For example, you can add smooth scrolling to the navigation links.

// Example of smooth scrolling when clicking on navigation links

document.addEventListener('DOMContentLoaded', () => {

  const links = document.querySelectorAll('.sticky-header a');  

  links.forEach(link => {

    link.addEventListener('click', (event) => {

      event.preventDefault();

      const target = document.querySelector(event.target.hash);

      const offset = 60; // Adjust this value as needed to offset the scroll position

      const top = target.getBoundingClientRect().top + window.pageYOffset - offset;

      window.scrollTo({ top, behavior: 'smooth' });

    });

  });

});