How To Keep Header At Top Of Page Css

Have you ever wanted to create a sticky header that stays at the top of the screen, regardless of how far the user scrolls down the page? This effect can be achieved easily using CSS, and in this tutorial, we’ll show you how to do it step by step.

Step 1: Create your header

First, let’s create a simple header using HTML. We’ll use a div with the class header and place some content inside:

    <div class="header">
        <h1>My Sticky Header</h1>
    </div>
    

Step 2: Add CSS to make the header sticky

To make the header stick to the top of the page, we’ll use the following CSS properties:

  • position: fixed; – This ensures the header remains in place, even when the user scrolls.
  • top: 0; – This positions the header at the top of the page.
  • width: 100%; – This makes sure the header spans the entire width of the page.
  • z-index: 1000; – This ensures the header stays on top of all other content on the page.

Now, let’s apply these properties to our header:

    .header {
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 1000;
    }
    

You can also add other styles to your header, such as a background color and padding, for a more polished look:

    .header {
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 1000;
        background-color: #f1f1f1;
        padding: 20px;
    }
    

Step 3: Adjust the content below the header

With the header now sticking to the top, you might notice that the content below it is being overlapped. To fix this, we’ll add some margin to the top of the content to push it down below the header:

    .content {
        margin-top: 100px; /* Adjust this value according to the height of your header */
    }
    

And that’s it! Your header should now remain at the top of the page, regardless of how far down the user scrolls. Here’s the complete HTML and CSS code:

    
    
    
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Sticky Header Example</title>
        <style>
            .header {
                position: fixed;
                top: 0;
                width: 100%;
                z-index: 1000;
                background-color: #f1f1f1;
                padding: 20px;
            }

            .content {
                margin-top: 100px;
            }
        </style>
    
    
        <div class="header">
            <h1>My Sticky Header</h1>
        </div>

        <div class="content">
            <!-- Add your content here -->
        </div>
    
    
    

Now you know how to create a sticky header using just a few lines of CSS. Go ahead and try it out on your own website!