Scale Typography from Screen Width

by Hugo Vale Pereira

HTML

<!--
From: [https://9to5.hfbk.hamburg/] (7 fev 2024)
-->
<div class="blue"></div>
<div class="red"></div>

<h1>Title</h1>
<h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto possimus, accusantium minima illo unde maxime tempore repellat et! Cum ipsa dolores tempore libero? Voluptatibus incidunt ab iure, aut nobis deleniti.</h1>

CSS

.blue {
  width: 200px;
  background: blue;
}
.red {
  width: 400px;
  background: red;
}

div {
  height: 10px;
}

h1 {
  /*Linear Interpolation between the min and max value*/
  /*
  ((max - min) / (bigWidth-smallWidth)) * (windowSize - smallWidth) + min
  */
  line-height: 1.2; /* Evita que sejam automativamente atribuídos números inteiros na line-height, o que provoca saltos */

  --min-f: 16; /* Minimun Font Size, in px */
  --max-f: 64; /* Maximum Font Size, in px */
  --bg-w: 400; /* Biggest Screen Size, in px, from which the font is the Max size */
  --sm-w: 200; /* Smallest Screen Size, in px, from which the font is the Min size */
  /* font-size: clamp(
    (var(--min-f) * 1px),
    ((var(--max-f) - var(--min-f)) / (var(--bg-w) - var(--sm-w))) *
      (100vw - (var(--sm-w) * 1px)) + (var(--min-f) * 1px),
    (var(--max-f) * 1px)
  ); */

font-size: clamp(
    (var(--min-f) * 1px),
    ((var(--max-f) - var(--min-f)) / (var(--bg-w) - var(--sm-w))) * (100vw - (var(--sm-w) * 1px)) + (var(--min-f) * 1px),
    (var(--max-f) * 1px)
  );

}

JavaScript

let h1 = document.querySelector('h1');
let size = h1.style.fontSize;
h1.textContent = 'Title '+  window.getComputedStyle(h1).fontSize

window.addEventListener('resize', () => {
  h1.textContent = 'Title '+  window.getComputedStyle(h1).fontSize
});