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.
- theposition:sticky; top: 50%; bottom:50%;
top
property seems to overridebottom
, resulting in the same as the first attempt withtop: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.