Ensure the element remains visible at all times using the CSS property "position: sticky"

I have a container with a specified height that can sometimes be longer than the screen.

Within this container, I have an element that is both vertically and horizontally centered using flex.

I wanted to ensure that this element remains vertically centered on the screen within the visible area of the container.

Attempts made:

  • position:sticky; top:50% - but this only centers it in the bottom half of the container.
  • position:sticky; bottom:50% - however, this only centers it in the top half.
  • position:sticky; top: 50%; bottom:50%;
    - the top property seems to override bottom, resulting in the same as the first attempt with top:50% only.
  • I experimented with negative values, but it did not produce the desired effect.

A live demonstration can be viewed here:

.container {
  height: 1200px;
  background-color: rgba(0, 0, 0, .7);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
.center-piece {
  background-color: green;
  position: sticky;
  top: 50%;
}
.center-piece2 {
  background-color: steelblue;
  position: sticky;
  bottom: 50%;
}
<div class="container">
  <div class="center-piece">
    #1
  </div>
  <div class="center-piece2">
    #2
  </div>
</div>

Is there a way to perfectly center the element while keeping it "always on screen" within the visible portion of the container, both at the top and bottom?

Watch a screencast of my application here: https://www.youtube.com/watch?v=CwYaBgolNHU

The "rawr" will serve as controls for the image behind it.

Answer №1

It seems there may have been some confusion in the question, but have you considered using the following CSS:

position: fixed;
top: 50vh;

?

.box {
  width: 500px;
  height: 300px;
  background-color: rgba(255, 100, 0, .7);
  color: black;
  margin: auto;
  position: fixed;
  top: 50vh;
  left: 50vw;
}
<div class="box">
  This is a centered box.
</div>

Answer №2

PLEASE NOTE: Browser compatibility may vary.

Based on information from caniuse.com, the use of position: sticky is supported in most major browsers (excluding IE).

View Example on jsFiddle

.container {
  height: 1200px;
  background-color: rgba(0, 0, 0, .7);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
.center-piece {
  background-color: green;
  position: sticky;
  top: 10px;                         /* 1 */
  bottom: 50%;
  left: 50%;
  transform: translate(-50%,50%);    /* 2 */
}
.center-piece2 {
  background-color: steelblue;
  position: sticky;
  bottom: 10px;                      /* 3 */
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div class="container">
  <div class="center-piece">#1</div>
  <div class="center-piece2">#2</div>
</div>

IMPORTANT NOTES:

  1. position: sticky becomes active when the element reaches top: 10px of the viewport
  2. Understanding CSS positioning and transform for centering elements
  3. position: sticky becomes active when the element reaches bottom: 10px of the viewport

Answer №3

To achieve the desired effect, consider utilizing either postition:absolute; or position:fixed; instead of relying on position:sticky;

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

Place two pictures in the center of a div container

Here is a div setup that I am working with: <div id="browsers"> <h2>Title</h2> <p>Text recommending the use of either Chrome or Firefox.</p> <a href="http://google.com/chrome/"><img src="img/64-chrome.png" /> ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

`Problem with CSS in Firefox, functions properly in Chrome`

Can someone please check to see if they can find what I'm overlooking? It's working perfectly in Chrome 10 but not in Firefox 4. The aim is for it to look like an iPhone keyboard. http://jsfiddle.net/pfqdr/ UPDATE: http://jsfiddle.net/pfqdr/6/ ...

What is the best way to smoothly transition in an image that is dynamically set using Angular?

I am using Angular to set a background image for my page, but the current loading behavior is not visually appealing as the image loads from top to bottom. I would like to implement a fade-in effect or load the image from a blurry view to enhance the user ...

What could be the reason behind the failure of this :after element?

I am facing an issue with the preloader on my webpage where the animation is not displaying as expected. The animation should appear on top of a dark black background before the page fully loads, but it seems to be missing. The CSS for the animation works ...

Creating a progress bar with blank spaces using HTML, CSS, and JavaScript

Upon running the code below, we encounter an issue when the animation starts. The desired effect is to color the first ten percent of the element, then continue coloring incrementally until reaching 80%. However, as it stands now, the animation appears mes ...

Keywords: <footer>, <aside> not encompassing all aspects of the HTML on the content page

Recently, I have been transitioning my codebase from .NET webform to .NET Core: In the _Layout.cshtml, elements like <hr> and <section> span the entire width (e.g. 100%) of the html page as expected. However, when I insert similar tags in the ...

HTML Download resource

When attempting to create a download link for a file, I found that clicking the link only opened the file in my browser instead of initiating a download. This issue occurred while using Internet Explorer. Here is the code snippet I used: <html> < ...

Altering column names in a Pandas DataFrame

I am working on code that generates a table with dates and predictions from a previous machine learning model gv = pd.date_range(str(d1), periods=15) lst_output = pd.DataFrame(lst_output) pred_log = lst_output.apply(np.square) pred = pred_l ...

Is it possible to use styled-components to specifically style a child class within a component?

Hey there, I'm currently working with a mui Badge component and am trying to customize the appearance of the small circle. This is what I have so far: const BadgeStyled = styled(Badge)` & > .muibadge-badge: { background-color: #d3d4d7; ...

Tips for shifting a div to the left with AngularJS

I am working with a div structure that looks like the following: <div class="col-xs-1 scroll-button"><i class="glyphicon glyphicon-chevron-left"></i> </div> <div class="customer-ust-bant col-xs-22" id="letters"> <box n ...

Horizontal Alignment of UL and DIV elements

Having trouble aligning a DIV and UL horizontally? Take a look at the code snippet below: <div class="col-md-12"> <div class="box-header"> <h4 class="box-title">Title</h4> </div> <ul id="menuOnglet" cla ...

Nav bar width remains stagnant despite varying content lengths

My navigation bar looks great with 5 objects, but as soon as I add 3 more, it suddenly drops below the main header. Why is this happening? 5 Objects: 7 Objects: HTML: <div id="header"> <div class="w960"> <div id="logo"> ...

Avoid conflicts by using a selector for styling in the jQuery plugin

I am a beginner to jQuery and recently created a plugin using jQuery UI widget factory. The plugin is functioning well, but I have been using inline styling which may become complex for larger files. For larger projects, I have the option to use classes. ...

I'm trying to use Javascript to dynamically remove rows, but my code seems to be causing some issues

When a user enters text into a form, it is stored in a variable called 'userInput'. I have an HTML table with the ID "myTable". My goal is to use JavaScript to iterate through the table and remove all rows where the value of the 3rd column does n ...

In need of a solution for the blank space issue in my HTML/CSS slideshow. How can I

I am experiencing an issue with my slideshow where there is a blank area on the right side. I have tried several solutions but haven't had much success resolving it. Any suggestions would be greatly appreciated. Thank you! Link to image JSFiddle lin ...

Switch up the animation direction after the vimeo video finishes playing

My video module has a splash screen that reveals a full-screen video when clicked for screen sizes 667+. I want to reverse the animation after the video ends and return to the splash screen. I'm unsure of how to approach this or if it's even poss ...

Attempting to store user input in the database

Currently, I am using XAMPP and following a tutorial to set up a website. The webpage allows users to submit their first name and last name, which should then be stored in a database. However, when testing the functionality, I keep encountering this error ...

The Ajax success function is failing to trigger after receiving a 200 network response

I have a basic HTML page that loads jquery 3.3.1 and an external script file called script.js. I am using a simple node http-server to serve the static page. The data.json file is also in the same folder as the HTML file. However, even though the network c ...

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...