Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Create a sticky navbar with CSS
A sticky navbar is a navigation bar that sticks to a specific position on the page when scrolling. To create a sticky navbar, use the position: sticky property along with the top property to define where it should stick.
Syntax
selector {
position: sticky;
top: value;
}
Example
The following example creates a sticky navbar that remains at the top of the viewport when scrolling −
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.navbar {
position: sticky;
top: 0;
background-color: #333;
overflow: hidden;
z-index: 1000;
}
.navbar ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
}
.navbar li {
border-right: 1px solid #555;
}
.navbar li:last-child {
border-right: none;
}
.navbar a {
display: block;
color: white;
text-decoration: none;
padding: 15px 20px;
transition: background-color 0.3s;
}
.navbar a:hover {
background-color: #555;
}
.content {
padding: 20px;
height: 2000px;
background: linear-gradient(to bottom, #f0f0f0, #e0e0e0);
}
</style>
</head>
<body>
<div class="content">
<h1>Scroll down to see the sticky navbar effect</h1>
<p>This is some content above the navbar...</p>
</div>
<nav class="navbar">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<div class="content">
<h2>Main Content</h2>
<p>Keep scrolling to see how the navbar sticks to the top of the viewport.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
</body>
</html>
A navigation bar with dark background and white text links appears. When you scroll down, the navbar sticks to the top of the viewport. The navbar has hover effects and smooth transitions.
Key Properties
| Property | Description |
|---|---|
position: sticky |
Makes the element stick to a specified position during scrolling |
top: 0 |
Defines the distance from the top where the element should stick |
z-index |
Ensures the navbar appears above other content when sticky |
Conclusion
The position: sticky property creates an effective sticky navbar that enhances user navigation. Remember to set a top value and consider using z-index to ensure proper layering.
Advertisements
