CSS sticky element not preserving its parent's styles

Hello everyone, I need some assistance with a CSS sticky property issue I am encountering. When I apply the sticky property to a div and scroll down, it doesn't retain its parent's properties as expected. Here is the scenario:

I have a Bootstrap navigation bar wrapped in columns which are then wrapped in rows. I applied the sticky property to the row and used JavaScript to add fixed positioning on scroll. However, when the window scrolls to that row, it retains all the elements within the row but not the properties of the row itself, which affects the overall design. Any help would be appreciated. Thank you.

window.onscroll = function() {
  stickNav()
};

var nav = document.getElementById("navtwksamp");
var sticky = nav.offsetTop;

function stickNav() {
  if (window.pageYOffset > sticky) {
    nav.classList.add("sticky");
  } else {
    nav.classList.remove("sticky");
  }
}
.sticky {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 2;
}
<div class="row" id="navtwksamp">
  <div class="col-12">
    <nav class="">
      <div class="">

        <div style="">...</div>
        <div class="">...</div>

      </div>
      <nav class=""> ... </nav>

    </nav>
  </div>
</div>

Unfortunately, I am unable to provide an image to better illustrate my issue due to reputation constraints. Any accessible links for reference would also be helpful. Thank you once again for your support.

Answer №1

.container {
  height : 200vh;
}

.box {
  color: blue;
  background: green;
  position: fixed; /* key */
  top: 0;
}
<div class="container">
  <div class="box">Header</div>
</div>

Utilize position: fixed;

for more information, visit:

https://www.example.com/howto_css_fixed_element.asp

.fixed {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 3;
}

Answer №2

It seems like you are having trouble with the height of the content above and below the div class named "row", causing issues with scrolling. However, I have used your code and it is working perfectly fine.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <style>
  .sticky {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 2;
}
  </style>
</head>
<body>

<div class="container-fluid">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing 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.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullam</p>
  <div class="row" id="navtwksamp">
    <div class="col-12">
      <nav class="">
        <div class="">

          <div style="">Home</div>
          <div class="">About</div>

        </div>
        <nav class=""> Contact </nav>
      </nav>
    </div>
  </div>
  <p>
  Lorem ipsum dolor sit amet, consectetur adipisicing 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.Lorem ipsum dolor sit amet, consectetur adipisicing 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.Lorem ipsum dolor sit amet, consectetur adipisicing 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.Lorem ipsum dolor sit amet, consectetur adipisicing 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.</p>
</div>
<script>
window.onscroll = function() {
  stickNav()
};

var nav = document.getElementById("navtwksamp");
var sticky = nav.offsetTop;

function stickNav() {
  if (window.pageYOffset > sticky) {
    nav.classList.add("sticky");
  } else {
    nav.classList.remove("sticky");
  }
}
</script>
</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

"Error encountered when attempting to execute the delete() function in Django

Having some trouble with my delete function. It successfully deletes the object but does not redirect to window.location as expected. Instead, I'm getting an error message: DoesNotExist at /api/personnel/delete/ Resource matching query does not exist ...

Locating an Image and Adding it to a Different Image Source

Here is the HTML markup that I am working with: <div id="main"> <div id="slider"> <img src=""/> </div> <div class="clear slider"></div> <div class="slider ndslider"> <a href="# ...

Determine the type of a nested class within TypeScript

Utilizing nested classes in TypeScript is achieved through the following code snippet: class Parent { private secret = 'this is secret' static Child = class { public readSecret(parent: Parent) { return parent.secret } } } ...

Fashioning PHP using CSS

Excuse my lack of experience with PHP, but I am new to working with it. I am currently using a premium Wordpress theme called Kingsize. While the theme is visually appealing, it does not display the author on posts by default. I have managed to add it to ...

JavaScript program failing to execute

Seeking to incorporate a read more and read less feature that activates on click for my articles application using Django. However, encountering an issue where my JavaScript code does not work when the read more link is clicked. Below are the relevant fil ...

Span element hides the text in the background

Is there a more efficient way to accomplish this task? My current approach involves creating a slide-in background color effect when hovering over a link. However, I am encountering some difficulties with the CSS implementation. In my setup, each link cont ...

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

Fulfill a promise based on a particular event in Puppeteer

I am looking for a way to seamlessly continue my puppeteer code after a particular event occurs. Specifically, I need guidance on how to handle the 'request' event in a synchronous manner. Here is an example of the event code: await page.on(&apo ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...

Strange behavior exhibited by the HTML DataList component within an Angular application

I have created a simple component that displays a list of data and allows users to add new entries. <h6 *ngIf="withHeader"><label for="select"> {{title}} </label></h6> <label *ngIf="!withHeader" [ngClass]="{'required&apos ...

"Utilizing Express.js and PHP for Streamlined Functionality

I have been working on a project that involves using expressjs, Php, Html, and MongoDB. Here is the code snippet from my "Index.Html" File: <form action="/Login" method="POST"> <input type="text" placeholder="name" name="Username"> <in ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

Angular filter is causing an error message saying "Unable to interpolate," but the filter is functioning as expected

I have implemented the filter below (which I found on StackOverflow) that works perfectly fine on one page. However, when using the same object, it throws an error as shown below: app.filter('dateFormat', function dateFormat($filter){ return f ...

Not enough test coverage with Jest

Here is the code snippet I am working with: <ReturnToLastSearch href={'/listings'} onClick={(e): void => { e.preventDefault(); router.back(); }} /> The function ReturnToLastSearch( ...

Reverse all elements on the page except for ::selection

Is there a way to invert the page while keeping text selection unchanged? I attempted to use ::selection to exclude it, but was unsuccessful. Below is the CSS code I used for inverting the page: html { background-color: #131313 !important; filter: cont ...

Python, JavaScript, and Selenium RC all work together within loop statements on .aspx pages

I've been diving into Python on my own for the past few months. My initial project involves creating a browser driver test case with the Selenium RC web driving framework (I'm avoiding importing webdriver to keep things simple). The goal is to ha ...

How can I handle returning different types of Observables in my Angular application?

I can't seem to get an observable to return properly. The mergeMap function inside my code doesn't appear to be executing at all. Here are the relevant snippets of code: book.service.ts import {HttpClient, HttpHeaders} from '@angular/comm ...

ASP.NET MVC is unable to locate the resource inside the Content folder

Trying to incorporate a trackCues.vtt file stored in my solution into my view has been a challenge. I attempted to load this resource following this code: <video style="margin-top:30px;margin-bottom:30px" width="800" height="600" controls> <s ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...