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

The scrolling content is positioned beneath the primary header and navigation bar

I'm currently in the process of designing a website where, upon clicking a navigation button, part of the page scrolls while the top header & nav bar remain fixed. Although I've managed to get the scrolling functionality to work and keep the top ...

Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one? I've noticed that most examples involve creating a new element. parent().append("<span>" + $input.attr('placeholder') + "</span>"); Is there a way to make the placehol ...

What is the best way to handle JSONp response parsing using JavaScript?

I'm relatively new to working with Javascript and I am currently attempting to retrieve data from an External API located on a different website. My goal is to extract the information, parse it, and then display specific parts of it within my HTML pag ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Tips for Showing Empty Data in a Nonexistent `<td>` Element within a Table

This particular query appears to be quite simple... I am seeking the HTML code for creating a table: <table> <tr> <th>Heading 1</th> <td>or</td> <th>Heading 2</th> </tr> <tr> ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

How can I dynamically update a div without refreshing the page by using an onclick event on a

When working on my project, I found helpful insights from this Stack Overflow thread. The structure of template-comparison.php involves fetching code from header.php to ensure the page displays properly. However, the actual "fetch code" process remains un ...

Updating Hiddenfield Value Issue in Jquery

Having an issue with Jquery: <input type="hidden" id="is_subpage" value="FALSE" /> <input type="hidden" id="is_page" value="TRUE"/> <input type="hidden" id="page_id" value="0"/> <input type="hidden" id="page_domain" value="{tic}" /&g ...

Reorganize Information in Table with the Help of jQuery's each Method

I have a collection of data retrieved from the database with varying prices and some redundant information. Here's a snapshot of the data: The desired format for the data is shown in this table: My attempt to organize the data using jQuery, specific ...

Is it possible to trigger a reflow prior to initiating a lengthy JavaScript operation?

Ready to face the criticism, I understand that this question has been asked many times before, and I am aware that there are likely more efficient ways to achieve what I'm trying to do... In a JavaScript function, I have a process that can take up to ...

Organizing grid elements within the popper component

I am struggling to align the labels of options in the AutoComplete component with their respective column headers in the popper component: https://i.stack.imgur.com/0VMLe.png const CustomPopper = function (props: PopperProps) { co ...

Bug in ZURB Foundation Topbar causes incorrect highlighting of links on mobile when clicked

While utilizing the ZURB Foundation Topbar, I have encountered a bug that I find frustrating. When navigating the 2nd level drop downs and clicking on a link (li elements), the active highlight flickers to one of the elements above before taking you to the ...

Can CSS stylesheets be set up to automatically load based on the browser being used to access the website?

I am inquiring because I recently completed a beautiful homepage design and, after viewing the website on Chrome and Safari on OSX, I noticed that certain elements were broken when I opened it in Firefox. In addition, an issue I was experiencing with the ...

Tips for eliminating the pesky "ghost" line that appears in your coded HTML email

Check out this Sample Code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <title></title> & ...

Placing a div with absolute positioning inside another div with absolute positioning raises the question of how it functions when the outer div is not set to position: relative

Trying to grasp the concept, I experimented with the following setup: <div id="Outer"> <div id="Inner"></div> </div> In this scenario, the outer div has a relative position and the inner div has an absolute position. This allo ...

Having difficulty passing a variable between two different PHP files

When attempting to modify data in the database for a specific user column, I encountered an issue. The code that I created only alters the data for the last user in the database, rather than the current user. For instance: Let's say I am logged in as ...

Trigger the datepicker to open by clicking anywhere within the TextField in MUI

I am trying to enhance my date picker functionality by displaying it when users click anywhere within the field, not just on the calendar icon. Below is the picker: https://i.stack.imgur.com/mrAui.png export function DatePickerField(props) { ...... ...

The <a> tag is failing to cover the appropriate section of the <div> element

I am facing the following issue: HTML: <div id="about" class="menu1"> <a href="#">About</a></div> <div id="aboutsub"> <div id="team" class="menu2"> <a href="">Team</a></div> &l ...

Web server decides on "Multiple Options" while utilizing %3F instead of "?" in the URL

I have been using the Lazarus-IDE for a project and encountered an issue with one of its components that doesn't accept "?" in the URL for online help info. I attempted to encode "?" as "%3F" in the URL, thinking it was the correct encoding, but both ...

Transform the image background on mouse hover using CSS

On my php page, I am dynamically visualizing thumbnails. To ensure that they are all the same size, I use the following method: <a class="zoom" href="..."> <img src="thumb/default.png" width="130" style="background-image:url(thumb/<?php echo $ ...