Creating a Custom Sticky Navbar with CSS
Getting Started with HTML and SCSS
Navigation bars are an essential component of any website, allowing users to navigate effortlessly without getting lost. In this article, we’ll explore how to create a custom sticky navbar that is responsive to all screen sizes using only CSS.
To start, we’ll write some simple HTML code for our navbar. We’ll use the BEM (Block, Element, Modifier) convention for writing class names, which will help us maintain consistency and organization in our code.
<div class="header">
<nav class="header__nav">
<ul class="header__list">
<li class="header__item"><a href="#">Home</a></li>
<li class="header__item"><a href="#">About</a></li>
<li class="header__item"><a href="#">Contact</a></li>
</ul>
</nav>
</div>
Styling the Navbar with SCSS
Next, we’ll write some SCSS code to style our navbar. We’ll use variables for colors and media queries to make our navbar responsive.
.header {
background-color: #333;
color: #fff;
padding: 1rem;
text-align: center;
&__nav {
display: flex;
justify-content: space-between;
align-items: center;
}
&__list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
&__item {
margin-right: 20px;
&:last-child {
margin-right: 0;
}
}
}
Creating a Hamburger Navbar for Smaller Screens
For smaller screens, we’ll create a hamburger menu that will display the nav items by overlaying the background of the whole screen. We’ll add a checkbox to determine when to show and hide the nav items.
<div class="header">
<input type="checkbox" id="nav-toggle" class="header__toggle">
<label for="nav-toggle" class="header__icon"><span></span></label>
<nav class="header__nav">
<ul class="header__list">
<li class="header__item"><a href="#">Home</a></li>
<li class="header__item"><a href="#">About</a></li>
<li class="header__item"><a href="#">Contact</a></li>
</ul>
</nav>
</div>
We’ll then add SCSS code to style the hamburger menu.
.header__toggle {
display: none;
}
.header__icon {
display: inline-block;
width: 30px;
height: 30px;
position: relative;
cursor: pointer;
}
.header__icon span {
display: block;
width: 100%;
height: 2px;
background-color: #fff;
margin-bottom: 5px;
transition: transform 0.3s;
}
.header__icon span:last-child {
margin-bottom: 0;
}
.header__toggle:checked ~.header__nav {
display: block;
}
.header__nav {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background-color: #333;
padding-top: 60px;
text-align: center;
}
.header__list {
margin: 0;
padding: 0;
list-style: none;
}
.header__item {
margin-bottom: 20px;
}
.header__item a {
color: #fff;
text-decoration: none;
}
We’ve now created a custom sticky navbar that is responsive to all screen sizes using only CSS. You can customize the styles and layout to fit your website’s design.