-2

I work on a pet project. As you can see by looking at the countdown, text moves a bit when numbers change due to the difference in symbol width. I want numbers to be fixed in place so they won't move anything.

At first I tried making font nums in the font monospaced, it worked but still if the font is to change then it will break.

Then I tried wrapping numbers in a span with fixed width but the catch is the website is adaptive and changes on viewport size so on smallers screens the font becomes smaller and fixed-size span doesn't work.

How can I dynamically calculate font width and add some extra space to the wrapping span to keep the numbers in place? Or maybe there are other approaches to handle this?

magrega
  • 37
  • 7
  • 2
    _"but the catch is the website is adaptive and changes on viewport size so on smallers screens the font becomes smaller and fixed-size span doesn't work."_ - font-size relative length units exist. https://developer.mozilla.org/en-US/docs/Web/CSS/length#relative_length_units_based_on_font – CBroe May 26 '23 at 09:28
  • Does this answer your question [Force Non-Monospace Font into Fixed Width Using CSS](https://stackoverflow.com/questions/10149330/force-non-monospace-font-into-fixed-width-using-css]=) – Apodemus May 26 '23 at 09:32

2 Answers2

1

You can define the width of an element relative to the font-size of the root element using the rem unit.

Just make sure to also define the font-size of the innerText in relative size so it does not break based on changes to the root font-size.

My recommendation:
When I look at your site, I rather recommend to wrap the individual clock elements of
X hours : Y minutes : Z seconds
in 3 individual elements with fixed relative width and display: inline-block; so the value-unit pairs are not separated and stay together on one line when the line breaks for different viewport sizes.

See this post for more info: Prevent line-break of span element

Criomby
  • 76
  • 1
  • 7
0

one solution is to break it in multiple <p> tags and give the tag a fixed width

<div class="clock-container">
<p class="time">26 years, 7 months, 7 days </p><p class="time" 
style="display: inline-block;width: 978px;"> 13 hours : 28 minutes : 06</p>
<p class="time" style="display: inline-block;">seconds</p>
</div>

you can break it further for the minutes and hours.

so to leave the dynamic clock in one <p> tag example:

<span class="time" style="display: inline-block;width: 76px;">66</span>

key
  • 1,334
  • 1
  • 19
  • 39