Computer >> Computer tutorials >  >> Programming >> CSS

How to Create an On Scroll Fixed Navigation Bar with CSS?


By specifying CSS position property, we can create a fixed navigation bar using CSS.

The syntax of position property in CSS is as follows −

Selector {
   position: /*value*/;
}

The following is an example of CSS position property.

Example

<!DOCTYPE html>
<html>
<head>
<style>
#navigation-bar {
   overflow: hidden;
   box-shadow: inset 0 0 20px green;
}
a {
   float: left;
   display: block;
   margin-left: 2%;
   padding: 2% 4%;
   text-align: center;
   color: black;
   text-decoration: none;
   font-size: 1.2em;
   border: 0.5px ridge red;
}
a:hover {
   box-shadow: inset 0 0 14px red;
   font-size: 1.6em;
}
.content {
   background-color: coral;
   padding: 16px;
}
.sticky {
   position: fixed;
   top: 0;
   width: 100%;
}
.sticky + .content {
   padding-top: 80px;
}
</style>
</head>
<body>
<div class="content"></div>
<div id="navigation-bar">
<a class="active" href="#">logo</a>
<a href="#">SignUp</a>
<a href="#">SignIn</a>
<a href="#">More</a>
</div>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum faucibus ante quis odio rhoncus, sit amet porta nunc venenatis. Vivamus eu ex et risus vehicula semper eu eu elit. Aliquam tempor rutrum neque sit amet aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras non eros ex. Suspendisse placerat tincidunt tortor a semper. Etiam molestie justo ac sapien auctor maximus. Etiam ut ante sollicitudin, tempor mauris nec, malesuada purus. Nunc malesuada sem sed fermentum eleifend. Cras ultrices velit eu blandit lobortis.
</p>
<img src="https://images.unsplash.com/photo-1612305876291-
c369fea489b3?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=800&ixlib=rb1.2.1&q=80&w=600" />
</div>
<script>
let nav = document.getElementById("navigation-bar");
let sticky = nav.offsetTop;
window.onscroll = function() {sticker()};
function sticker() {
   if (window.pageYOffset >= sticky) {
      nav.classList.add("sticky")
   } else {
      nav.classList.remove("sticky");
   }
}
</script>
</body>
</html>

Output

This will produce the following result −

How to Create an On Scroll Fixed Navigation Bar with CSS?

How to Create an On Scroll Fixed Navigation Bar with CSS?