Navigation Bar that Sticks as you Scroll

I have been searching for a solution to make my Navbar stick to the top of the page when scrolling down, but I haven't been able to find one that fits my specific needs. The challenge lies in the fact that my Navbar is currently positioned using flex and is not fixed at the top of the page.

If you have any suggestions or solutions, please take a look at my CODEPEN example.

* {margin:0;padding:0;box-sizing:border-box}
html, body {text-align: center;}
#logo2 img {
margin: 0 auto;
    margin-top: 3%;
}
.menu2 {
display: flex; /* displays children inline */
margin: 0;
width: 100%;
margin-top: 2%;
list-style-type: none;
background: linear-gradient(#3E3E3E, #2B2B2B);
}

li {
flex: 1; /* each takes as much width as it can, i.e. 25% */
border-right: 1px solid #232323;
}

li:last-child {
border: none;
}

li a {
display: block;
text-align: center;
font: Verdana;
font-size: 16px;
color: #EAE0D2;
text-decoration: none;
padding: 20px 0;
}

li a:hover {
background: linear-gradient(#404040, #3E3E3E);
}

.active {
background: linear-gradient(#2B2B2B, #232323);
}
<header id="logo2">
<a href="index.html"><img src="logo.png" alt="Logo"/></a>
</header>

<nav>
<ul id="navigation" class="menu2">
  <li><a href="index.html">HOME</a></li>
  <li class="active"><a href="gallery.html">GALLERY</a></li>
  <li><a href="art.html">ART</a></li>
  <li><a href="contact.html">CONTACT</a></li>
</ul>
</nav>
</body>

Answer №1

After much searching, I was able to uncover the solution to my inquiry. Here it is for those who are curious.

JS

let position = 200; //pixels threshold for style modification

$(window).on('scroll', function() {
    if ($(window).scrollTop() > position) {
        $('.menu2').addClass('fixed');
        $('.main').addClass('main2');
    } else {
        $('.menu2').removeClass('fixed');
        $('.main').removeClass('main2');
    }
});

Answer №2

.main-nav {
  width: 100%; height: 100%;
  background-color: rgb(240, 240, 240);
  position: sticky;
  left: 0; top: 0;
}

.emptySpace{width: 100%; height: 1000000px;}
<span class="main-nav">
  <a href="">Menu Item 1</a>
  <a href="">Menu Item 2</a>
  <a href="">Menu Item 3</a>
  <a href="">Menu Item 4</a>
  <a href="">Menu Item 5</a>
</span>

<!-- the div below is to allow you to scroll so you can see how it works (it's absolutely useless) -->
<div class="emptySpace"></div>

If I understand your question correctly, one way to create a sticky navigation bar in HTML and CSS is by using:
HTML:

<span class="main-nav">
  <a href="">Menu Item 1</a>
  <a href="">Menu Item 2</a>
  <a href="">Menu Item 3</a>
</span>

CSS:

.main-nav {position: sticky;}

This code will make the navigation bar stick to the top of the screen as the user scrolls down. For more information on CSS positioning, visit W3Schools. Feel free to explore this concept further with my example on LiveWeave at LiveWeave.

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

Creating Input Fields on the Fly in VueJS

My goal is to dynamically manipulate input fields in real-time. I found a helpful solution at , which successfully adds and removes fields as needed. However, when attempting to save the input values to the database, the functionality breaks. Here is the ...

The execution of the return statement in the catch block is unsuccessful

Here is a simple example that results in an error because the variable tl was not specified: function allmatches() { SpreadsheetApp.getActive().getSheetByName('data').getRange('A1').setValue(tl) } To track any errors that occur durin ...

Expanding containers with flexbox to allow for flexibility in size

I need help with a page that contains 3 div elements, where 2 of them need to be resizable. These elements should be able to be moved left or right, and maximized or minimized. You can view the example on Stackblitz. The issue I'm facing is that som ...

Unusual Actions from the Text Field

Please take a look at this link <div id="textarea_wrapper"> <textarea>How and where is my width derived from?</textarea> </div> #textarea_wrapper{ height: 250px; border:thick solid green; } textarea{ background-color: #930; ...

Optimal method for translating date string data from JSON to the user interface

Let's take a look at this JSON response: { data: { nestedData: { someMoreNestedData: { someArray: [ { someWhereThereIsADate: '2018-10-26' } ] }, w ...

Best practices for defining module-wide constants in AngularJS

In my project, I have around 20 "modules" each with its own unique functionality but following the same structure. These modules are stored in separate files within their respective folders. For instance, the admin module is located in the modules/admin fo ...

React - Why does React fail to update the state when expected? (not retaining)

Hello there, I'm currently working on fetching JSON data from an API and populating it into a table. It seems pretty straightforward but here's where things get tricky – I can see that the "tableData" state is getting updated as new rows are ad ...

Tips for managing the dimensions of the <label> element within a React component

I'm facing an issue where the element size is not matching the box size as expected. Additionally, the width property doesn't seem to work in React. Does anyone know how to solve this problem? const DragDrop = () => { ... return ( &l ...

Is there a way to convert a jQuery object into a PHP array?

After creating a jQuery object using $("input").serializeArray();, I received the following output: 0: Object { name: "id", value: "9" } 1: Object { name: "name", value: "Fred" } 2: Object { name: "quantity", value: "1" } When I send this object via AJA ...

What could be the reason why readyState is not equal to 4?

I've been trying to figure out how to use Ajax to fetch data from a database, but I'm encountering some issues... The problem arises when I submit the query and nothing appears on the screen... I understand that this issue is related to the read ...

Issue with preserving data in form fields on an HTML form

I've been working on a form that should retain values in a specific field (title) even after submitting the form. However, despite my efforts, the values disappear and leave a blank space when an error message pops up. Can anyone help me identify what ...

The Vue method is failing to properly send data to an array of objects

Trying to troubleshoot this issue is proving to be quite challenging for me. Despite following all the guidelines, I seem to be stuck at a roadblock and cannot figure out what is causing the problem. Let's take a look at my vue.js application: new Vu ...

Verifying the size of the unordered list and deleting a list item

I'm attempting to remove the last <li> element from a <ul> element only if it goes beyond a certain length. To achieve this, I have implemented the following code: var selector = "#ulelement" if($(selector).children().length > threshol ...

Incorporating a radio button input into the parent component in a React application

The main component stores all the state data. Whenever there is a change in any input field, the function myChangeHandler is triggered and updates the state accordingly. myChangeHandler(event) { this.setState({ [event.target.name]: event.target.value }) ...

Getting the most out of setInterval() - a guide in jQuery

I am currently working on an auto slide feature and could use some guidance with setInterval(). From my understanding, setInterval() is used to repeat functions infinitely, which is exactly what I need for this project. Here is the current layout: HTML & ...

<ul><li>issue with indentation

Is there a way to eliminate the indent from my unordered list? While inspecting the element, I noticed what appears to be padding between the width of the box and the content. However, setting padding to 0px and margin to 0px doesn't seem to work as t ...

How come the navigation menu is still visible on the screen when its width is supposed to be set to zero?

I encountered an issue with the code where the navigation items, previously links inside a div, now wrapped in UL and LI tags do not disappear off-screen to the right as intended. Additionally, I am exploring the possibility of enclosing this UL within a ...

Mastering the art of integrating a multi-step form in React

While developing a multi-step form in my React 17.0.1 application using Typescript version 4.1.2, I came across this helpful guide: https://dev.to/sametweb/how-to-create-multi-step-forms-in-react-3km4 The guide was clear up to step 6, which I decided to s ...

Lazy Highcharts and Foundation clash when loading JavaScript

I'm currently utilizing lazy_high_charts along with foundation 4. Within my view, I have included <%= high_chart("my_id", @chart) %>, which produces the following: <section> <script type="text/javascript"> (function() { ...

Get the redirectUri using npm's Request package

When using npm Request to generate a response, I am able to retrieve information like "statusCode" by using "response.statusCode". However, I am unable to retrieve other information such as "redirectUri" as it shows undefined. Is there a way to access the ...