What could be causing my sticky positioning to not function properly when I scroll outside of the designated

My website is organized into sections, with each section corresponding to a hyperlink in the navigation menu. I've applied the CSS property position: sticky to my navbar, which works as expected within the section bounds. However, I want my red navbar to remain visible not only in the yellow section, but across all sections of the website - yellow, green, or blue.

$('.links a[href^="#"]').click(function (event) {
  event.preventDefault();
  const section = document.querySelector(event.target.getAttribute("href"));
  section.scrollIntoView({
    behavior: "smooth"
  });
})

$(document).scroll(function () { 
  $("nav").toggleClass("sticky", window.scrollY > 0);
});
body{
    margin: 0;
    box-sizing: border-box;

}


nav.sticky{
    background-color: blue;
    border-bottom: 10px solid black;
}

nav img{
    width: 10vh;
}

nav.title-bar{
    background-color: red;
    display: block;
    position: sticky;
    top: 0;
    width: 100%;
    transition: 0.5s;
    height: 50vh;
    z-index: 10000;
    color: white;


    nav.title-bar > *{
        padding: 20vh;
    }

}

#first{
    background-color: yellow;
}

#second{
    background-color: green;
}

#third{
    background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <section id="first">

        <nav class="title-bar">
            <div class="logo">
                <img src="https://picsum.photos/200" alt="logo" id="logo">
                <h1 id="title"><a href=".">My Website</a></h1>
            </div>

                <div class="links">
                    <a href="#first" class="selected">First</a>
                    <a href="#second">Second</a></label>
                    <a href="#third">Third</a></label>
                </div>
        </nav>

        <div class="div-1">
            <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Vel mollitia tempora labore, ad laboriosam modi recusandae ipsam tempore quasi tenetur, veritatis, alias pariatur qui doloremque accusamus temporibus doloribus porro aperiam?</p>
            <img src="https://picsum.photos/200/300">
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. At maiores sunt voluptatum quas laboriosam, ducimus nesciunt ipsa quis, ullam rerum ipsam consectetur aperiam, mollitia totam aliquid sit exercitationem eius facilis?</p>
            <img src="https://picsum.photos/200/301">
        </div>

    </section>

    <section id="second">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>
    
    
        <section id="third">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>
</body>
</html>

Answer №1

According to MDN Web Docs:

Keep in mind that a sticky element will adhere to the closest ancestor with a scrolling mechanism (such as overflow hidden, scroll, auto, or overlay), even if that ancestor isn't actually the closest scrolling ancestor. [1]

Your <nav class="title-class> will stay fixed to the nearest scrolling ancestor, which is . Therefore, your navbar will always remain within its container.

Solution:

Position the navbar as the first child of the body element.

Answer №2

Here's a simple solution, just adjust the position of the links

$('.links a[href^="#"]').click(function (event) {
  event.preventDefault();
  const targetSection = document.querySelector(event.target.getAttribute("href"));
  targetSection.scrollIntoView({
    behavior: "smooth"
  });
})
body{
    margin: 0;
    box-sizing: border-box;

}


    nav.sticky{
        background-color: blue;
        border-bottom: 10px solid black;
    }
    
    nav img{
      width: 10vh;
    }
    
    nav.title-bar{
        background-color: red;
        display: block;
        position: sticky;
        top: 0;
        width: 100%;
        transition: 0.5s;
        height: 50vh;
        z-index: 10000;
        color: white;


    nav.title-bar > *{
            padding: 20vh;
    }

    }
    
    #first{
       background-color: yellow;
    }
    
    #second{
      background-color: green;
    }
    
    #third{
    background-color: blue;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <nav class="title-bar">
            <div class="logo">
                <img src="https://picsum.photos/200" alt="logo" id="logo">
                <h1 id="title"><a href=".">My Website</a></h1>
            </div>

                <div class="links">
                    <a href="#first" class="selected">First</a>
                    <a href="#second">Second</a></label>
                    <a href="#third">Third</a></label>
                </div>
        </nav>
    <section id="first">
        <div class="div-1">
            <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Vel mollitia tempora labore, ad laboriosam modi recusandae ipsam tempore quasi tenetur, veritatis, alias pariatur qui doloremque accusamus temporibus doloribus porro aperiam?</p>
            <img src="https://picsum.photos/200/300">
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. At maiores sunt voluptatum quas laboriosam, ducimus nesciunt ipsa quis, ullam rerum ipsam consectetur aperiam, mollitia totam aliquid sit exercitationem eius facilis?</p>
            <img src="https://picsum.photos/200/301">
        </div>

    </section>

    <section id="second">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>>
    
    
        <section id="third">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>
</body>
</html>

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

Overridden CSS rules

Having a slight CSS dilemma. Within my webpage's html, I have the following structure: <div class='box-div'> <div>Entry 1</div> <div class='hide'>Entry 2</div> </div> Here is my associated ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

How to toggle classes on specific items generated with Vue JS's v-for directive

I have a list rendering using the v-for directive in Vue.js. <li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." > Content </li> My goal is to apply a class to the li el ...

Parent div's overflow due to its flexbox properties

I am currently facing a dilemma with my nested flexbox setup. The primary objective is to create two responsive columns: .ColWrap, { width: 100%; box-sizing: border-box; background-color: #fff; padding: 50px 10px 50px 25px; display: fl ...

iOS devices are not displaying the background image as intended

I've searched through previous answers on the SO platform, but I'm still unable to find a solution that works for me. I have a static Gatsby site with an infinite scrolling background implemented on desktop, and a static image displayed on mobile ...

The barely noticeable difference of 1 pixel in the link between Chrome and Firefox

Hello there, I need some advice on how to adjust a one-pixel difference between Chrome and Firefox. The menu links appear correctly in Chrome, but in Firefox, they are 1px smaller than they should be. Below is the CSS code: ul#menu { padding: 0 0 2px ...

Bootstrap table issue: server side call fails to trigger

I'm in the process of familiarizing myself with the bootstrap table plugin, which can be found at this link: The specific example I'm attempting to replicate is located here: Here's my HTML code: http://jsfiddle.net/6h5sqs9d/ Within my cg ...

Invalid for the purpose of storage

Encountering the following error message: The dollar ($) prefixed field '$size' in 'analytics.visits.amounts..$size' is not valid for storage. return Manager.updateMany({}, { $push: { & ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

Issues encountered when trying to use default color classes in Tailwind CSS

I'm currently working on a React project that utilizes the Tailwind CSS Framework. To integrate Tailwind into my React app, I used NPM to install it in the following way: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p After i ...

Is there a method to have JavaScript display all the information during a SQL while loop?

I'm currently working on implementing a timer for my script. However, I am facing an issue where the timer only counts down from the last result instead of each individual result returned from the query. Any assistance with resolving this problem woul ...

Rendering HTML is not supported by AngularJS on Android 19 with version 4.4.4 and Safari 8.0.5

I have been working on an AngularJS app that is being displayed in a Webview on Android. Everything was functioning properly until yesterday when I started encountering issues with Angular not rendering the DOM correctly. I have tested the app on various v ...

Send multiple form submissions using JQuery Ajax without needing to refresh the page

I am facing an issue with my form submission using Ajax. After receiving a response in the form of another form, when I try to submit it again using the submit button, it doesn't go through Ajax and uses the normal method instead. Why is this happenin ...

CSS :hover problem, text appearing unexpectedly

I'm currently working on designing a logo that displays hidden text when hovered over, providing instructions to users. However, I've encountered an issue where the hidden text reveals itself even before the logo is hovered over. This is frustrat ...

Triggering a system context menu through a longpress gesture on the MobileFirst iOS app is a

After experimenting with our MobileFirst iOS app, I noticed that if you hold down on any anchor links for more than 2 or 3 seconds, iOS will bring up a built-in menu displaying the internal path of the current HTML page. I'm unsure whether this behav ...

Tips for utilizing SeleniumRC within JUnit framework for elements with dynamically changing IDs

I'm currently in the process of automating a workflow and I need to click on a link within a table row. The challenge is that all links within the rows share the same element ID, and the source code has a JavaScript code snippet like this: ("Element I ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

The VisJS Network lacks proper alignment

I am attempting to generate a vis js network. This is how I envision the graph should appear https://i.sstatic.net/xIv3s.png Here is the code snippet extracted from the page source <script type="text/javascript"> var options = { ...

Can we create a collection of Vue highcharts components in a library format?

I am in search of an answer, with hope that it lies here. I have used the following: "vite": "^2.7.13", "highcharts": "^9.3.3", "highcharts-vue": "^1.4.0" I aim to create a library of Vue compon ...

What is causing my HTML to not recognize my Angular JS code?

Trying to dive into Angular JS, I wrote a small piece of code but for some reason, the HTML is not recognizing Angular JS. This is my index.html file: <!DOCTYPE HTML> <html ng-app="store"> <head> <link rel="stylesheet" type=" ...