• Readhubs Substack
  • Posts
  • A sticky header and how we can achieve this using HTML, CSS and and JavaScript

A sticky header and how we can achieve this using HTML, CSS and and JavaScript

A sticky header is a common feature on websites where the header remains fixed at the top of the page as the user scrolls down. Here's a simple example of how you can achieve this using HTML, CSS, and

HTML:

html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

    <title>Sticky Header Example</title>

</head>

<body>

    <header id="myHeader">

        <h1>My Sticky Header</h1>

    </header>

    <div class="content">

        <!-- Your page content goes here -->

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

    </div>

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

</body>

</html>

```

CSS (styles.css):

css

body {

    margin: 0;

    font-family: Arial, sans-serif;

}

header {

    background-color: #333;

    padding: 15px;

    color: #fff;

    text-align: center;

    position: relative;

    z-index: 1000;

}

.content {

    padding: 20px;

}

.sticky {

    position: fixed;

    top: 0;

    width: 100%;

}

```

JavaScript (script.js):

```javascript

window.onscroll = function() { myFunction() };

var header = document.getElementById("myHeader");

var sticky = header.offsetTop;

function myFunction() {

    if (window.pageYOffset > sticky) {

        header.classList.add("sticky");

    } else {

        header.classList.remove("sticky");

    }

}

```

In this example:

- The `header` element initially has a `position: relative;` style, making it positioned relative to its normal position in the document flow.

- The JavaScript code checks the scroll position (`window.pageYOffset`) and adds the class `sticky` to the header when the scroll position surpasses the offsetTop of the header.

- The CSS class `.sticky` is defined to give the header a fixed position at the top of the page when it has that class.

Remember to adjust styles and content to fit your specific design and requirements.