Fit Text with CSS Variables

Fit text to the viewport with CSS variables! All you need is to know the number of characters, which a little JS can help with…

See the Pen Fit Text with CSS Variables by Shaw (@shshaw) on CodePen.

Created on March 19, 2020 Updated on March 20, 2020. A Pen by Shaw on CodePen.


<div data-fit-text>Fit Text</div>
<div data-fit-text>With CSS Variables</div>
<div data-fit-text>Some longer text that wants to fit, too...</div>
<div data-fit-text>Don't forget this text!</div>
<div data-fit-text>It can work with really long text if you really want, but that's gonna be hard to read...</div>


[...document.querySelectorAll("[data-fit-text]")].forEach(el => {
  // We just need the length of the string as a CSS variable..."--length", el.innerText.length);


@import url("");

[data-fit-text] {

html {
  height: 100%;
  display: flex;
body {
  margin: auto;
  text-align: center;

html {
  background: #fbc490;
  color: #084177;
Latest posts by W3TWEAKS (see all)


Leave a Reply

Your email address will not be published. Required fields are marked *