I have a timer bar showing the remaining time of a contest. As the user answers more questions of the event, scrolling down, I want the timer to be fixed in its position. I know this can be achieved by setting the CSS position
to fixed
.
But fixed
needs either a width
set for the element, or left
and right
values. My problem is that the layout of the page is boxed, with margins at the left and right of the "box", and it depends on the user's viewport, how much width there is for the box in the middle...
How can I calculate the width once the page loads and then set that width to the timer bar in order for fixed
property to get the data it needs?
I tried setting it to 100%, but for position: fixed
100% means 100% of the viewport, not of the parent element, so the bar grows from the right, outside of the viewport (if you can get what I mean), since there are margins on the left and right of the boxed layout...
Use position: sticky;
.wrapper {
text-align: center;
max-width: 768px;
}
.progress {
position: sticky;
background: red;
top: 0;
}
/* tall content to cause scrollbars */
main > div {
height: 100vw;
}
<h1>Title above stickied progress</h1>
<div class="wrapper">
<div class="progress">
<progress></progress>
</div>
<main>
<div>Example of a very long step</div>
<div>Example of a very long step</div>
</main>
</div>