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

center text vertically in HTML list

Here at this festival, you'll find a unique menu on the sidebar. The menu is created using an HTML list with the following structure: <ul class="nav nav-pills nav-stacked"> <li class="active"> <a href="index.html"><i ...

Is the item positioned above another item instead of being positioned to the left of it?

Looking for help with my mobile navigation setup. I want to add text that says ' ...

Avoiding Backbone Routing Conflicts when Implementing CSS3 Targeting

I have implemented a CSS target to create some basic animation in my Backbone project. However, I am facing an issue where the method I am currently using adds a #banner to the URL, which Backbone tries to interpret as a route if users refresh the page aft ...

What is the best way to display data from an Excel spreadsheet on my website?

I'm faced with a challenge in my Excel spreadsheet- I have a mix of numbers and text that I want to turn into graphical representations on a webpage. I'm considering using Python or PHP to achieve this as HTML alone doesn't seem up to the ta ...

Determining the aspect ratio of an image is essential in using flexbox to achieve consistent heights

Recently, I came across a fascinating code pen titled: this demonstration of equal responsive height images I am determined to make sure that all images have the same height, regardless of their width/height variances. The CSS displayed below utilizes fle ...

Transform black and white image to vibrant colors and add various hover effects

There are three images displayed on this webpage: This website is built on WordPress and utilizes the WP Bakery plugin for designing layouts. The images here are set to change from color to grayscale, and back to color upon mouseover. The following CSS c ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

"PHP MySQL news error" - An unexpected error occurred

Just incorporated a news system using MySQL/PHP, it functions flawlessly; however, encounters errors when inserting HTML. For instance, inserting a YouTube video results in the addition of / or \ Can someone advise on what changes need to be made in ...

The measurement of a HTML window's entire content height (not just the visible viewport height)

Currently, I am attempting to determine the total height of a webpage's content, not just what is visible. In my efforts, I have managed to achieve some success in FireFox using: document.getElementsByTagName('html')[0].offsetHeight. Howeve ...

Boundaries on Maps: A guide to verifying addresses within a boundary

User provides address on the website. If the address falls within the defined boundary, it is marked as "Eligible". If outside the boundary, labeled as "Ineligible". Are there any existing widgets or code snippets available to achieve this functio ...

Tips for presenting a label and its value on separate lines while also displaying additional nested label-value pairs:

I have a specific request in mind, But the result I am seeing is different, Here's the code snippet, I'm utilizing bulma framework but encountering some challenges... <section class="section"> <p>Please verify the details below a ...

Why does my jQuery IMG center script not work in Chrome and Safari, but it works perfectly in IE?

I am experiencing an issue with centering the thumbnails of products on my e-commerce website. Despite successful centering in IE, FF, and Opera, Chrome and Safari are not aligning the thumbnails properly – they remain at the top of the div instead of be ...

What is the best way to design a content page with linked boxes to various arrays in PHP?

How can I create a PHP menu template that navigates to different pages? I am new to PHP and still learning. I want to achieve something similar to this image: https://i.stack.imgur.com/ylfe8.jpg I have the code for the navigation bar, but I need help crea ...

Centering a Font Awesome icon within its parent element

Below is the code I am using: <div style="width:60px; height:60px; background-color: lightgrey;"> <a class="" href="javascript:void(0)" style="color: black; width: inherit; height: inherit;"> <i class="fa fa-lg fa-play" aria-hidden="t ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Using Javascript and jQuery, populate a dropdown menu with options that are extracted from a different dropdown menu

These are my two <select> elements: <select class="js-select-1"> <option disabled>Starting point</option> <option>A</option> <option>B</option> <option>C</option> <option>D</op ...

Attempting to retrieve currentScript is causing a typeError to be thrown

I'm attempting to access a custom attribute that I added to my script tag: <script type="text/javascript" src="https://.../mysource.js" customdata="some_value"></script> To make this work on Internet Explorer ...

The HTML webpage is optimized for desktop and tablet viewing, but has difficulty displaying correctly on mobile phones

Just starting out with HTML and created a website using HTML and CSS that is now live. It looks good on desktop and tablet (iPad) but not so great on mobile devices. Tried different solutions, including viewport settings, to fix the issue with no success. ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

Creating stylistic layouts for text using CSS

After spending the last hour designing a web page, I am stuck on a particular issue that I just can't seem to solve. I need to write several paragraphs while adhering to two specific constraints: 1) The div in which the text resides must be centered ...