I have a container with known height (height is sometimes longer then screen).
This container has a vertically and horizontally centered element (via flex
).
I was hoping to keep this element always on the screen vertically centered in the block in the visible portion of the container.
What I tried:
position:sticky; top:50%
- however this only keeps it centered on the bottom half of container.position:sticky; bottom:50%
- however this only keeps it centered on top halfposition:sticky; top: 50%; bottom:50%;
- it seems top
overrides bottom
so this is just like my first try with top:50%
onlyHere is a demo:
.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 anyway to keep it perfectly centered, while "always on screen", in the visible porition of container, both top and bottom?
Here is a screencast of my application: https://www.youtube.com/watch?v=CwYaBgolNHU
The "rawr" will be the controls for the image behind it.
I may have misunderstood your question, but can you use:
position: fixed;
top: 50vh;
?
.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: fixed;
top: 50vh;
left: 50vw;
transform: translate(-50%,50%);
}
<div class="container">
<div class="center-piece">#1</div>
</div>
NOTE: Compatibility varies across browsers..
According to caniuse.com, position: sticky
is supported on current major browsers (Not IE).
.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>
NOTES:
position: sticky
kicks in when element reaches top: 10px
of viewportposition: sticky
kicks in when element reaches bottom: 10px
of viewportIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With