What is the best way to horizontally center a div within an overflow scroll container?

https://i.sstatic.net/cuQFc.gif

Check out what I've created. I attempted to center a yellow div horizontally within an overflowing div, and trigger this using the scroll event.

However, as you can see, it's glitchy and behaves oddly.

The issue seems to be magnified when viewed on mobile browsers compared to desktop browsers. (Why is that?!!)

If you have any advice or tips, please share. Thank you!

https://codesandbox.io/s/quizzical-grass-c45hrm?file=/src/App.js

Answer №1

While it may not be the most sleek solution, this method is far superior to using JavaScript:

<!DOCTYPE html>
<div style="position: relative; width: 100px; height: 100px; white-space: nowrap; border: solid">
  <div style="width: 100%; height: 100%; overflow: auto">
    looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
    <div style="position: absolute; background: aqua; text-align: center; inset: 50% 0 auto; margin-top: -0.5lh">test</div>
  </div>
</div>

The position: relative outer element effectively traps the position: absolute element just beyond the scrolling box, allowing it to overlay without interfering with the scroll, thus keeping it in place while the content moves.

The conventional CSS approach tends to outperform JavaScript in terms of scrolling and animations due to its declarative nature. This is because the browser engine can optimize and leverage hardware acceleration for layout tasks more efficiently compared to JavaScript's procedural approach.

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

Chrome browser CSS trapezoid shape clickability problem

I am attempting to make a trapezoidal perspective shape clickable for the entire area. It's currently working in Firefox and IE, but I'm encountering issues with Chrome. Here is a demonstration of the shape and a link: http://jsfiddle.net/9n9uh6 ...

Navbar brand in Bootstrap 4 not centered when navbar is collapsed

I am currently working on aligning the brand-item and nav-items on mobile view. The alignment is incorrect in the mobile view. It is not centered. The "Brand" should be vertically aligned with "link1-3". In the desktop view, the alignment should be like ...

Learn the steps for creating smooth transitions between two HTML pages

Can anyone help me achieve a transition effect between HTML pages when clicking on menus or submenus? I want the page to open with a smooth transition. Thank you in advance for your guidance. I found a link that shows how to add a transition effect within ...

Animate the background image with a float effect using jQuery's timeout feature to create an up

I'm having an issue with a set of elements that have background images applied to them. Specifically, I want the planets in the images (all except the first one) to move slightly up and then back down to create a floating effect. In my jQuery code, I ...

Could this be a Vue.js memory leakage issue?

Check out this component's code: import { defineComponent, ref } from "@vue/composition-api"; const template = /* html */ ` <div> <nav> <button @click="showCanvas = !showCanvas">Toggle</button> </nav>a <can ...

Utilize SASS to easily reference SCSS files within the main.scss file in order to update the main.css

I have my webpage layout defined in different SCSS files, such as _navbar.scss and _footer.scss, along with the main.scss file (without underscore). Now, I want to include all my layout SCSS files in my main.scss so that the main.css file will contain the ...

Tips on preventing navbar from shrinking in height while resizing the page

I am working on an app that is designed to resemble a desktop operating system. Currently, I have a navbar positioned at the bottom of the page, but when the height of the page is adjusted, the navbar shrinks too much and becomes difficult to use. I have ...

Chrome fails to load webfont upon page initialization

Encountering a problem with loading a WebFont specifically on Chrome version "48.0.2564.82 m (64-bit)". The issue arises from the webfont not being applied upon page load or navigation, unless I manually refresh the page. Below is the snippet of code fro ...

Angularjs bootstrap nav directive has some bugs that need fixing

My code works fine, but there's a problem: if someone clicks outside the target area (the text label), the directive doesn't fire. Here's my directive: //directive to change active menu class in bootstrap app.directive('activeClass&ap ...

Ensure that the footer remains at the bottom of the page regardless of the content above

I am currently developing a website using bootstrap and I am facing an issue with the footer. I want the footer to always stay at the bottom of the page, but when the screen size is smaller (around 500px), the footer moves between sections. Here is the cod ...

updating the name of an HTML element with jQuery

Encountering a problem with setting the class for each li in a group of li tags: function pathContents(fileList) { var $list = $('<ul/>'); $.each(fileList, function (_, file) { $('<li/>').prop('class', &apos ...

Tips for establishing a universal onkeydown listener for all frames within a webpage?

Working with a complex legacy multi-frame webpage that needs to be compatible with IE-11 and responsive to hotkey events has brought up some challenges. It appears I can't simply declare a JavaScript method in the parent page. Rather, it seems that e ...

Can Bootswatch be installed using a package manager?

I have recently launched a small asp.net core website. Right now, all JS/CSS imports are from NPM and I am using webpack to bundle them together. Instead of sticking with the standard bootstrap template, I wanted to switch to bootswatch paper, but unfortu ...

Partial postback support for numerical values in animations

Recently, I incorporated an animation into a design: .map > img:hover { -webkit-animation-name: MapFloatingChrome; -webkit-animation-duration: 3s; -webkit-animation-iteration-count: infinite; ... to {-moz-tra ...

What is the best way to store all rows in a dynamically changing table with AngularJS?

I am facing an issue while trying to dynamically add rows for a variable that is a String array in my database. The problem is that it only saves the last value entered in the row instead of saving all of them in an array. Here is my current view code: &l ...

What is the code to create a forward slash on a webpage using HTML/CSS?

I want to create a unique parallelogram/slash design on my website. While it's simple to place two rectangles side by side, achieving the slash effect is proving to be quite challenging. Can this be done using only CSS or HTML, or does it require SVGs ...

Is there a way to navigate to an external website by clicking a button in Next.js?

<button type="button" className = {styles.googleButton}> <img className = {styles.image} src = "assets/pictures/google.jpg"></img> <p className = {styles.buttonText}> Go To Google</p> <img ...

Guide on how to assign a value to a textbox according to the selected option from a dropdown menu

I need a feature where, depending on the selection made in a dropdown menu, data should be automatically filled into the next input field. For instance, if the options in the dropdown menu are NETWORK1, NETWORK2, NETWORK3, selecting NETWORK1 should popula ...

WordPress Website Failing to Recognize @import Rule

Not really sure what's going on with the site layout, but it seems that in the style.css file, right at the beginning of the file, these two lines are not being recognized: @import "css/reset.css"; @import "css/layout.css"; It's strange because ...

Updating nested divs and spans can be achieved by targeting each element individually

Looking to make changes to a nested div and span elements. HTML: <table id="item_table" data-role="table"> <thead> <tr> <th>&nbsp;</th> <th scope="col" width="100px">Name</th> < ...