HTML CSS sticky navigation bar

How to make CSS Sticky Navbar?

In this tutorial, you will learn how to create a sticky navigation bar using only CSS.

Here is the demo of the Sticky Navbar

Demo of the CSS Sticky Navigation Bar

Creating the CSS Sticky Navbar

Here is a very simple markup (HTML) code

<div class="logo">
    <a href="https://devbabu.com"><img src="./devbabu200.png" alt="Devbabu.com"></a>
</div>
<nav class="navbar">
    <ul>
        <li><a href="">Home</a></li>
        <li><a href="">About</a></li>
        <li><a href="">Privacy</a></li>
        <li><a href="">Contact Us</a></li>
    </ul>
</nav>
<div class="container">
    <!-- content -->
</div>

The following CSS (style.css) code is for the above HTML code. In this CSS code, there are two properties that make our navbar sticky.

/* properties that make our navbar sticky */
position: sticky;
top: 0;
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap");
*,
*::before,
*::after {
    box-sizing: border-box;
    line-height: 1.5em;
}

html {
    font-size: 16px;
    scroll-behavior: smooth;
    -webkit-text-size-adjust: 100%;
}

body {
    margin: 0;
    font-family: "Open Sans", sans-serif;
    background-color: #f7f7f7;
}

.logo {
    display: flex;
    justify-content: center;
    padding: 30px 20px;
    background-color: white;
}

.container {
    max-width: 700px;
    margin: 0 auto;
}

.navbar {
    background-color: #232323;
    position: sticky;
    top: 0;
}
.navbar ul {
    list-style: none;
    display: flex;
    margin: 0;
    justify-content: center;
    gap: 20px;
}
.navbar li a {
    padding: 15px 10px;
    display: block;
    color: #e6e6e6;
    text-decoration: none;
    text-transform: uppercase;
}
.navbar li a:hover {
    color: #fcfcfc;
}