Home > Blockchain >  Fixed element's width
Fixed element's width

Time:10-24

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...

CodePudding user response:

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 >
    <div >
        <progress></progress>
    </div>
    <main>
        <div>Example of a very long step</div>
        <div>Example of a very long step</div>
    </main>
</div>

CodePudding user response:

You can use the 'vw' CSS unit to get a percentage of viewport width. For example width: 50vw; would set it to 50% of the current viewport width.

You can also use calc() to do calculations. For example, if I know I want something to be a third of the current viewport width I could set width: calc(100vw/3);

  • Related