Header that sticks to the top of a container as you scroll through it

Many questions arise regarding sticky elements in the DOM and the various libraries available to handle them, such as jquery.pin, sticky-kit, and more.

However, the issue with most of these libraries is that they only function when the entire body is scrolled, and require the parent container to have a default overflow setting.

https://i.stack.imgur.com/iB1Do.png

The demonstration page for Sticky-kit showcases exactly what I am looking for. In their case, they use an iframe while in mine, it's a Div with overflow: auto (an app with flexbox layout featuring fixed header, footer, and left menu, while the main content scrolls).

I want the red box 'stick me' to remain in place when scrolling through the gray box. The green elements do not scroll and stay put throughout. My criteria include:

  • The body does not scroll
  • No iframes
  • Avoid using a timeout running every 50ms

Several solutions come to mind:

  • Apply position:fixed to the red box and either a) duplicate its content (not preferred) or b) dynamically adjust the margin/padding of the gray container to keep elements below the red box (ideal but monitoring its height and adjusting the margin can be challenging). Similar to this example, although changes in header height may pose an issue: http://jsfiddle.net/KTgrS/

  • Alternatively, use position: absolute on the red box and readjust it during the scroll event of the gray box. Feasible, but retrieving the scroll 'delta' can be tricky without direct access.

Are there any other creative ideas or effective methods to make the aforementioned approaches suitable for actual production use? Support for modern browsers is sufficient.

Answer №1

Accurate solution

To easily achieve this task:

$('.greybox').on('scroll',function(event){
  $('.redbox').css({top: $(this).scrollTop()});
});

Initial response:

A better approach would be to place both the red and grey boxes in a common container.

<div class="container">
  <div class="redbox"></div>
  <div class="greybox"></div>
</div>

For applying styles:

.container
{
  position: relative;
  width: ...px;
  height: ...px;
}
.redbox
{
  position: absolute;
  top: 0px;
  height: 20px;
  left: 0px;
  right: 0px;
  background: red;
  z-index: 1;
}
.greybox
{
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  overflow: auto;
  padding-top:  20px; // height of the redbox
  box-sizing: border-box;
  z-index: 0;
}

Now, the redbox appears sticky without requiring any JavaScript or specific sticky techniques at all :-)

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

Can you explain the purpose of the #shadow-root found within elements?

Today I witnessed something out of the ordinary. Take a look at the images attached to this post. Specifically, pay attention to the input[type="text"] labeled as "1" in the screen picture. The CSS styling for it appears as follows: tab ...

Getting the date from a datetime JSON - here's how!

How can I extract the date from a JSON datetime string like 2013-11-09T00:00:00 using either Jquery or JavaScript? ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

Using an external font in JavaFX CSS

Can you style a font with CSS in a JavaFX application? I have an FXML scene and corresponding CSS file. In Java code, you can set a font using the setFont method: text.setFont(Font.loadFont("file:resources/fonts/SourceSansPro-Bold.ttf", 12)); I've t ...

What exactly is Bootstrap - a CSS framework, a JavaScript framework, or a combination

Being new to Bootstrap, I have taken the time to explore What is Bootstrap? as well as http://getbootstrap.com/. From what I understand so far, Bootstrap is a CSS framework that aids in creating responsive designs that can adapt to various devices. Essent ...

JQuery: The $.ajax function is not defined

Having trouble making an AJAX call in Symfony 5? Getting the error message "$.ajax is not a function"? You're not alone. Even after installing jQuery using composer require components/jquery, things might not work as expected. One common solution is t ...

Angular 2.0 in conjunction with D3.js does not style SVG elements using CSS

Currently, I am utilizing Angular 2.0 TypeScript along with the d3.js library to create graphics. My main focus is on applying CSS to the axis (especially shape-rendering: crispEdges;). Do you have any suggestions? Check out the code below: var vis = d3 ...

What is the best way to transfer data to another PHP file using AJAX?

Being new to ajax and lacking significant knowledge about it, I have created two PHP files - six.php and six-cuf.php. Upon user input in six.php and submission, this will trigger a call to six-cuf.php using ajax for the calculation. However, while executi ...

Guide to activating form elements using a JQuery function

I need help setting up a form with 11 rows and 11 columns. By default, the form fields should be disabled, but when I click on an "EDIT" button, they should become enabled. Any assistance would be greatly appreciated. Thank you in advance. Here is my edit ...

Unique background image is assigned to each div sharing the same class

Seeking a way to assign unique random backgrounds to each div with the .item class. Initially attempted using PHP and CSS, for example: <?php $bg = array('bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

Conceal the bootstrap hamburger icon if there are no navigation items present

I am working on dynamically populating nav-items within a navbar bootstrap component. There are instances where no nav-items are present, and during those times, I would like to hide the hamburger icon in device viewports. I have identified that the class ...

Tips on maintaining and hiding the vertical scrollbar when a popup is open, alongside the navigation bar positioned at the top of the page

After reviewing this pen, my goal is to create a popup that maintains access to the navigation bar (hence avoiding Bootstrap's Modal). However, I am facing the challenge of keeping the scrollbar visible while preventing scrolling in the background whe ...

Adding a gap between the Bootstrap navbar and jumbotron for better spacing

Upon examining the Bootstrap example provided at: http://getbootstrap.com/examples/navbar/ I noticed there is a gap between the jumbotron and the navbar. After delving into the example's CSS, I found that disabling this rule (twice): .navbar { ...

Displaying a date and time beautifully in jQuery/JavaScript by providing the day of the week along with the specific time

Does anyone know of a Javascript library, preferably a jQuery plugin, that can take datetimes in any standard format (such as ISO 8601) and convert them into user-friendly strings like: Wednesday, 5:00pm Tomorrow, 9:00am Saturday, 11:00pm I'm not c ...

Randomize checkbox selection using Javascript and Bootstrap

I'm in a bit of a bind with my webpage and could really use some help to figure it out. Here's the issue: On my website, there's a table of players. Each player has two checkboxes on their line: one to show if they are active (checked), and ...

To add an image, simply click on the designated area instead of using the traditional file input button. The image will then be displayed in the specified image container and resized on the client-side

Objective: I am aiming to enhance the image upload functionality by enabling users to click on an <img> element to initiate the file selection process, instead of using the traditional <input type="file"> button. There will be three placeholde ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...

Creating dynamic visual representations of algorithms using JavaScript

I am currently exploring how to create animations for algorithms using JavaScript. I'm curious about the process of creating algorithm animations in other languages, such as Java. Is the animation aspect typically separate from the algorithm logic? Fo ...

Display a hidden division when a radio button is selected using Javascript and Jquery

Currently, I am in the process of constructing a form that triggers a series of additional questions based on the selected answer. Below is my current working code snippet: $(".appliedWorked").click(function(){ if($(this).val()==="appliedWorkedYes") ...