Utilize CSS to position an element absolutely above the scrollbar

I'm encountering an issue with CSS absolute positioning, where the element appears above the scrollbar...

Here is my code:

document.addEventListener("DOMContentLoaded", () => {
    const h1 = overflow.querySelector("header h1")
    overflow.onscroll = e => h1.classList.toggle("static", overflow.scrollTop > h1.offsetTop)
})
body {
     font-family: Arial;
}
#app {
     height: 80vh;
     width: 80vw;
     margin: 10vh auto;
     position: relative;
}

#overflow {
     overflow: auto;
     height: 100%;
}

#app header {
     background: lightblue;
     padding: 1rem;
}

#app header h1,
#app header h2,
#app header p {
     margin: 0;
}

#app header h1.static {
    position: absolute;
    top: 0;
    left: 0;
    background: lightblue;
    padding: 1rem;
    width: 100%;
    box-sizing: border-box;
}

#app main {
     padding: 1rem;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" type="text/css" href="./style.css">
    <script type="text/javascript" src="./script.js"></script>
</head>
<body>
    <div id="app">
        <div id="overflow">
            <header>
                <h2>SubTitle</h2>
                <h1>Main Title</h1>
                <p>Some extra text</p>
            </header>
            <main>
                ... (long Lorem Ipsum text omitted for brevity) ...
            </main>
        </div>
    </div>
</body>
</html>

The desired behavior is for the title to move along with the scroll but using a sticky position is not working in this case... The current issue is that while it works correctly, the scrollbar overlaps the absolute element when scrolling...

Any suggestions on how I could resolve this?

Thanks in advance!

EDIT: Running Firefox on Xubuntu Linux, here's the observed result: https://i.stack.imgur.com/7XSjX.gif

Answer №1

When dealing with your situation, one important factor to consider is the scroll width. Additionally, you must also take into account the height of the "fixed" header in order to prevent any content from abruptly shifting.
To illustrate, here is a sample implementation:

overflow.onscroll = () => {
  const h1 = overflow.querySelector('h1')
  const header = overflow.querySelector('header')
  if (overflow.scrollTop > h1.offsetTop){
    header.style.height = header.offsetHeight + 'px';
    h1.classList.add('fixed');
    h1.style.right = overflow.offsetWidth - header.clientWidth  + 'px';
  }else{
    h1.classList.remove('fixed');
    h1.style.removeProperty('right');
    header.style.removeProperty('height');
  }
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: Arial;
}

#app {
  height: 80vh;
  width: 80vw;
  margin: 10vh auto;
  position: relative;
}

#overflow {
  overflow: auto;
  height: 100%;
}

#app header {
  background: lightblue;
  padding: 1rem;
}

#app header h1.fixed{
  position: absolute;
  top: 0;
  left: 0;
  background: lightblue;
  padding: 1rem;
  pointer-events: none;
}

#app main {
  padding: 1rem;
}
<div id="app">
  <div id="overflow">
    <header>
      <h2>SubTitle</h2>
      <h1>Main Title</h1>
      <p>Some extra text</p>
    </header>
    <main>
      <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.</p>
      [Content repeats multiple times for demonstration purposes]
    </main>
  </div>
</div>

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

another option besides the nextElementSibling

I have a unique code that applies a style to the following div when another div is clicked, using nextElementSibling. var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("clic ...

What is the best way to conceal a CSS div through PHP if the div is empty?

I need some help refining my previous question to ensure clarity. Is there a straightforward method for hiding a div when it doesn't contain any information, without causing confusion for the client? This specific div receives information from Jooml ...

The styling for material UI's default endAdornment is lacking accuracy

My Autocomplete component from material UI v5 includes a default endAdornment icon. However, the icon appears to have the CSS property top:unset, causing it to be styled incorrectly. Here is the code for rendering the Autocomplete: <Grid item xs={3}> ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

Generating custom-styled entries using Word VBA

I have set up styles in my Word document, such as My_Style (which I use for titles). I am looking to create entries for illustrations that correspond to the number from that particular style. Here is the code snippet I am using: Sub Macro4() ' &apos ...

Guide on adjusting the size of an image based on either its width or height dimensions

Currently, I am retrieving product images from an API but unfortunately, they do not have consistent dimensions. My goal is to display these images within a 250x250 div. In some cases, the image is in portrait orientation and should be scaled based on its ...

Unable to choose an input form within a CSS div

Just installed a jQuery responsive menu tab but encountering issues with selecting forms to input values. It seems like a CSS problem that I cannot identify. Please assist me in resolving this issue. Below is the HTML code snippet: <div class="contai ...

Tracking the progress of reading position using Jquery within an article

Here is an example of a reading progress indicator where the width increases as you scroll down the page: http://jsfiddle.net/SnJXQ/61/ We want the progress bar width to start increasing when the article content div reaches the end of the article c ...

Enhance the appearance of a custom checkbox component in Angular

I developed a customized toggle switch for my application and integrated it into various sections. Recently, I decided to rework it as a component. However, I am encountering an issue where the toggle switch button does not update in the view (it remains t ...

Scroll bar for multiple selection select tag without using div element (not supported in firefox)

.selector select[multiple="multiple"] { border-radius: 0; height: 200px; margin: 0 0 0 -1px; max-width: 368px !important; padding-left: 3px; width: 368px !important; } <select id="id_included_packages_from" class="filtered" multiple="multipl ...

How can I ensure my card div is responsive in Bootstrap?

My current section consists of only 6 cards, with 3 cards in a row of 2. When the screen size reduces (to mobile phone size), I want each card to be on its own row, displaying one by one as the user scrolls. Although it functions as desired when I resize ...

The art of fluidly positioning elements in Bootstrap columns

My goal is to showcase objects in 3 columns using Bootstrap 4. However, when I implement the code provided, the objects are only displayed in a single column, as shown here: example of 1 column layout. What I actually want is for the objects to be arrange ...

Working with CSS styles for the <datalist> element

I currently have a basic datalist drop-down menu and I am looking to customize the CSS to match the style of other fields on my website. However, as someone new to web design, I am unsure of how to go about this process. Check out the code here: http://j ...

Section is obstructing the view of Other Section above

I am struggling to create a responsive design for these two sections, both of which display quite similarly in line. Here are the resolutions for desktop and tablet/mobile: https://i.sstatic.net/XWbSP.png https://i.sstatic.net/3KLyY.png I suspect the is ...

The background is obscured from view because of its current positioning

The issue I am facing is that the background color of the <ol> list is not showing correctly. This problem arose after I floated the label to the left and the input to the right. How can I resolve this? The desired outcome should be: My current resu ...

Having trouble getting the CSS 3 Spin feature to work?

Using webkit for previewing in chrome. The spinning circles I created are not working properly (definitely not an HTML issue.) #loader-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; } #loader { display: inline-bl ...

<div class="firstHeaderClass"> What exactly is this?

Struggling to eliminate a recurring header across all my webpages for customization, I've hit a roadblock in identifying the source of this repeating header. Upon stumbling upon this code snippet in the header section, my efforts to decipher its ...

Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious. JS const gri ...

jQuery Animation Issue: SlideDown Effect Not Working as Expected

I'm feeling quite confused about this situation. I've been attempting to utilize the slideDown function in jQuery, but when I click on the 'information' div, it just jumps instead of animating smoothly. I suspect that one of the cause ...