What is the best way to ensure the second navbar stays at the top when scrolling, after the first one?

Looking for a solution to create a navbar with two distinct sections for contact info and the menu. The goal is to have the contact info disappear when scrolling down, while the menu remains fixed at the top of the page. When scrolling back up, the menu should be pushed down by the contact info. Any assistance would be greatly appreciated.

body {
  margin: 0;
  padding: 0;
}

#navbar {
  width: 100%;
  /* position: fixed; */
}


/*NAVBAR-CONTACT*/

.navbar-contact {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: rgba(242, 122, 61, 1);
  width: 100%;
  list-style-type: none;
}

.navbar-contact li {
  padding: 10px 16px;
  float: right;
}

.navbar-contact li:first-child {
  padding-right: 25%;
}

.navbar-contact li a {
  display: block;
  color: rgba(255, 255, 255, 1);
  text-align: center;
  text-decoration: none;
  font-family: Verdana, Tahoma, sans-serif;
  font-size: 12px;
}

.navbar-contact li a:hover {
  text-decoration: underline;
}


/*NAVBAR-MENU*/

.navbar-menu {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: rgba(33, 33, 33, 0.8);
  list-style-type: none;
  text-align: center;
  position: fixed;
  width: 100%;
}

.navbar-menu li {
  display: inline-block;
}

.navbar-menu li a {
  display: block;
  color: rgb(190, 190, 190);
  text-align: center;
  text-decoration: none;
  font-family: Verdana, Tahoma, sans-serif;
  font-weight: 900;
  font-size: 16px;
  padding: 20px 16px;
}

.navbar-menu li a:hover {
  color: rgba(255, 255, 255, 1);
  text-shadow: 0 0 10px rgba(255, 255, 255, 1);
}

#content {
  margin: 0;
  padding: 80px 60px 0 60px;
  height: 300vh;
}
<!DOCTYPE html>
<html>

<head>
  <title>Website</title>
  <link rel="stylesheet" type="text/css" href="style/style.css">
</head>

<body>
  <!-- Navbar -->
  <nav id="navbar">
    <ul class="navbar-contact">
      <li><a href="#"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="620b0c040d22060d0d0f030b0c4c010d4c1709">[email protected]</a></a></li>
      <li><a href="#">(XXX) XXXX XXXX</a></li>
    </ul>
    <ul class="navbar-menu">
      <li><a href="#">About</a></li>
      <li><a href="#">Courses</a></li>
      <li><a href="#">Clients</a></li>
    </ul>
  </nav>
  <div id="content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
  </div>
</body>

</html>

Answer №1

If you want to make an element sticky using CSS, the simplest way is to use position: sticky;

Check out this example from w3schools (here):

div.sticky {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
}

Note that sticky elements are sticky relative to their parent element. Make sure your styling remains consistent by keeping your navbar-menu outside of your nav element like this:

<!-- Navbar -->
<nav id="navbar">
    <ul class="navbar-contact">
        <li><a href="#"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a53545c557a5e55575b5355144f51">[email protected]</a></a></li>
        <li><a href="#">(XXX) XXXX XXXX</a></li>
    </ul>
</nav>
<ul class="navbar-menu" style="position: sticky;">
    <li><a href="#">About</a></li>
    <li><a href="#">Courses</a></li>
    <li><a href="#">Clients</a></li>
</ul>

Then apply the following CSS to your navbar-menu:

/*NAVBAR-MENU*/

.navbar-menu {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: rgba(33, 33, 33, 0.8);
  list-style-type: none;
  text-align: center;
  width: 100%;
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
}

(Please note that I removed position: fixed;)

Answer №2

One suggestion to consider is implementing JavaScript into your code. I replicated your code and tested it using a helpful resource from W3Schools...give this a shot:

<script>
    var prevScrollpos = window.pageYOffset;
    window.onscroll = function() {
        var currentScrollPos = window.pageYOffset;
        if (prevScrollpos > currentScrollPos) {
            document.getElementById("navbar").style.top = "0";
        } else {
            document.getElementById("navbar").style.top = "-50px";
        }
        prevScrollpos = currentScrollPos;
    }

</script>

After that, incorporate some CSS styling for your #navbar:

#navbar{
    width: 100%;
    top: 0;
    transition: top 0.3s;
    position: fixed;
}

To delve deeper into this technique, check out this link: https://www.w3schools.com/howto/howto_js_navbar_hide_scroll.asp

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alternate. (individually)

Issue with Running Program I've been struggling to get my program to run correctly. The task at hand is to have the program display only one question at a time. But no matter what I try, clicking on all questions displays all the answers simultaneous ...

the iframe is not properly displaying the embedded responsive page

The primary webpage incorporates the responsive mobile page created with the JQUERY SUPERSLIDES plugin. The mobile page appears correctly when viewed directly on an iPhone using Safari. However, when it is embedded in an iframe, it does not display as expe ...

Using a global variable to change the class of the <body> element in AngularJS

I've recently developed an angularJS application. Below is the index.html <html ng-app="MyApp"> <head> <!-- Import CSS files --> </head> <body class="{{bodylayout}}"> <div ng-view></div> < ...

Is there a way to locate the content enclosed within a span tag without any specific class or ID attribute using Selenium with Python?

I have been attempting to utilize Selenium in order to locate the text within a span element that lacks any specific attributes such as class or id for identification. Here is the HTML structure: HTML snippet obtained from inspecting the element in Chrome ...

How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over: <div id="locationmap"> <a class="linkhide" id="link1" href="#">Occupier 1</a> <a class="linkhide" id ...

Deselect a CheckBox along with its corresponding label using VueJS

I am currently working on unchecking a checkbox that is already checked using its label in VueJs. DEMO: new Vue({ el: '#app', data: { checkedNames: [], checkedName: true }, methods: { uncheck: function() { this.check ...

The styling in CSS does not accurately reflect its relationship to the parent

My code includes a div with the ID of "outer" nested inside a parent div with the ID of "Container". I'm attempting to adjust the properties of the outer div relative to its parent, meaning its width, height, and other attributes should be based on th ...

Is there a way to enhance the height of Bootstrap combobox items? Can this be achieved?

Is it possible to improve the height of Bootstrap combobox item? How can I achieve that? 1 2 3 4 ...

Troubleshooting overlap problem between Skrollr and SlickNav

I successfully implemented Skrollr to fix images, similar to this example: Additionally, I am utilizing Slicknav for the menu functionality. However, I encountered an issue where the menu opens behind the fixed "parallax" image. Despite trying various ap ...

Bootstrap progress bar loading does not function properly

I have a progress bar on my page with three parts: progress-bar-success, progress-bar-warning, and progress-bar-danger. I would like each part of the progress bar to complete sequentially, starting with progress-bar-success, then progress-bar-warning, and ...

Getting rid of the <br> tag as well as the linked <span> element

I've been experimenting with creating dynamic forms. My latest project involves a text box, an 'Add' button, and a div. The idea is that whenever a user types something into the text box and clicks the Add button, that value should appear in ...

Adjust the Weight of a Single Word in H1 CSS

I've been trying to figure out how to achieve the following for a while now. I know I can solve this issue by using different h1 tags and positioning them separately, but I'm curious to find out if there's a way to do it without dividing the ...

Using JQuery to swap out background images in CSS

I have been working on a slider that is supposed to fade one picture over another. The issue is that the background change seems to only work in the Dreamweaver preview and not in the actual browser. loop = setInterval(function(){ $("#slider").css("ba ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

firefox compatibility issues with jquery ajax

Trying to establish a connection with a URL and expecting a large object in response has proven to be challenging. The process appears to function smoothly until an error occurs during the return reply, triggering the .ajax.error() function. Unfortunately, ...

Utilizing AJAX to Fetch Data from Python

I am attempting to utilize AJAX to dynamically update a table with data retrieved from a Python script. However, when I make an AJAX request to the Python script, instead of receiving just the content within the print commands, I get the entire Python scri ...

Implementing dynamic classes for each level of ul li using JavaScript

Can anyone help me achieve the goal of assigning different classes to each ul li element in vanilla Javascript? I have attempted a solution using jQuery, but I need it done without using any libraries. Any assistance would be greatly appreciated! con ...

``In Internet Explorer, the function to swap the image source when hovering over the parent element

I'm trying to make it so that when I hover over the parent (Li) tag with my mouse, the src attribute of the child img tag changes. This code works correctly in Chrome but not in Firefox and Internet Explorer. <li class="player"> . . //some c ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

Problem with Pathjs routing

Can anyone help with this routing issue I'm having? Path.map("/(:page_1)(/:page_2)/").to(funct); The route is not matching for: /projects/index2/ It matches /anything, but not /anything/anything If you have any ideas, please share! ...