Search code examples
htmlcssflexboxfontsfont-size

Avoid jumping content when using fonts with changing width


Some type of fonts such as georgia, gilroy, etc, have variable width with numbers, so number 1, has a difference width to number 5. This causes the content to constantly jump between single digit changes when using a time counter for example. I don't mind it jumps on additional digits such as from 9 to 10, or 99 to 100, but I do not want it to jump between single digit changes.

How can I use georgia font without causing below jumps? I also do not wish to have a fixed width for the time counter, because it could grow significantly and I don't want to have empty space when the time counter is small.

document.querySelector('#start').addEventListener("click", function() {
  setInterval(() => {
    document.querySelector('#time').innerHTML++ 
  }, 100) 
}); 
.flex-1 {
  flex: 1 1 0%;
}

.flex {
  display: flex;
}

.font-serif {
  font-family: Georgia;
}

.items-center {
  align-items: center;
}

.bg-blue {
  background: blue;
  width: 100%;
  height: 100px;
}
<div>
  <div class="flex items-center">
<div class="flex-1">
  <div class="bg-blue"></div>
</div>
<div class='font-serif'>
  <time id="time">0</time>
</div>
  </div>
  <button id="start">start</button>
</div>

However if I use a different font such as sans content does not jump:

document.querySelector('#start').addEventListener("click", function() {
  setInterval(() => {
    document.querySelector('#time').innerHTML++ 
  }, 100) 
}); 
.flex-1 {
  flex: 1 1 0%;
}

.flex {
  display: flex;
}

.font-sans {
  font-family: font-sans;
}

.items-center {
  align-items: center;
}

.bg-blue {
  background: blue;
  width: 100%;
  height: 100px;
}
<div>
  <div class="flex items-center">
    <div class="flex-1">
      <div class="bg-blue"></div>
    </div>
    <div class='font-sans'>
      <time id="time">0</time>
    </div>
  </div>
  <button id="start">start</button>
</div>


Solution

  • For some fonts font-variant-numeric: tabular-nums; will give fixed-width digits.

    [I didn't seem to get this to work with Georgia but pleased to hear that it works for you].