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

`Problem with the layout of the form on the website`

Experiencing some challenges with the container design for a job sheet project. As a beginner, I have been learning on the fly and following online tutorials to create functional forms. However, this particular form is not rendering correctly when viewed o ...

Deciphering the :host attribute in CSS: A guide

When using Selenium to query the CSS properties of an element, I noticed that even though the actual background color is white, the returned value for background-color is always #000000. This issue arises in an Ionic-built app. Upon inspecting with Chrome ...

Display an Open Dialog window when a Button is clicked

On a button click, I need to display an Open Dialog box. To achieve this, I am utilizing the FileUpload control for file uploading purposes, however, I prefer not to expose it to the user and would rather display a Button instead. ...

What steps can be taken to resolve the link prefetch warning in a Next.js application?

I am currently working on a Next.js application using version 13.4, and I've encountered a warning in the console: After preloading the resource at <URL>, it was not used within a few seconds of the window's load event. Please ensure that i ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

What is the reason behind my button appearing beneath my links in React?

Here is an image showcasing the current header render. The header consists of a HeaderMenu and 3 Links. While the links are functioning properly, the HeaderMenu is causing the links to be positioned below it. The HeaderMenu includes a div that wraps a Butt ...

Height problem with Semantic UI cards in Chrome on Windows

Encountering an issue specific to Chrome on Windows where the height of my .card elements is not displaying correctly. The height appears to be either too much or too little, causing the problem shown in the screenshot below. This issue seems to be isolate ...

Ensure that the height of the content in JQuery Mobile is set to 100

I'm currently working on an app using JQuery Mobile. Check out this link for my HTML code. There's a full-screen <iframe> within my page. Even though I've specified width:100%; height:100%; border:0% for the iframe, it ends up being ...

Checkbox and Ionic avatar image combined in a single line

I am currently working on a mobile app using the ionic framework. I would like to create a layout with an avatar image on the left, text in the middle, and a checkbox on the right. Can anyone provide guidance on how to achieve this? The code snippet below ...

How can I create a CSS animation that fades in text blocks when hovering over an image?

I have been trying to implement CSS3 transitions to create a hover effect where the text and background color fade in when hovering over an image. Despite my attempts with various selectors and transition types, I can't seem to achieve the desired res ...

Tips for utilizing both the Element Selector and Class Selector in Jquery

I am working with a simple table that has TDs assigned either the 'PLUS' or 'MINUS' class. My goal is to use jQuery to implement functionality for collapsing all or expanding all. When the Expand All button is clicked, I need to chang ...

What is the best way to eliminate the gap between header, content, and footer sections when in mobile view?

This issue seems to only occur in mobile mode, where the blueviolet line is coming from the background color. https://i.stack.imgur.com/VBhIp.png link to the image body { background-color: blueviolet; } header, main, footer { background-color: #ff ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

Adding custom fonts to DOMPDF: a step-by-step guide

First, I moved the dompdf library folder to /dompdf Next, I added a /fonts folder containing Roboto-Black.ttf Then, I created an index.php file <?php // Autoloader inclusion require_once 'dompdf/autoload.inc.php'; // Namespace reference ...

Tips for saving the visibility status of a <div> in your browser bookmarks?

Currently, I am in the process of developing a single webpage (index.html). The navigation bar at the top includes links to hash references (DIV IDs). If JavaScript is enabled, clicking on these links triggers a JavaScript function with the onclick attribu ...

Chrome tab freezes when scrolling with the mouse

Working on a particularly interesting bug, I've managed to replicate it using a fiddle. The issue arises when the middle mouse button is clicked over the div element containing text, causing the pointer to become stuck. Is this possibly a browser bug ...

Using HTML and CSS to Position Text Within an Image

Is there a way to position an image next to specific points on the screen so that it remains in the same place regardless of screen size? Here is what I am trying to achieve: https://i.stack.imgur.com/A5cop.png Using HTML, this is my desired setup: < ...

Display a div when hovering over a span with custom styling

Don't let the title fool you. http://jsfiddle.net/whb8A/ I'm struggling to style the text inside a span tag within a div. The h3 element shouldn't be nested in the span, but removing it makes it difficult to style with CSS. When hovering ...