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.
index.html
<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>
script.js
[...document.querySelectorAll("[data-fit-text]")].forEach(el => {
// We just need the length of the string as a CSS variable...
el.style.setProperty("--length", el.innerText.length);
});
style.css
@import url("https://fonts.googleapis.com/css?family=Poppins:600&display=swap");
[data-fit-text] {
html {
height: 100%;
display: flex;
}
body {
margin: auto;
text-align: center;
}
html {
background: #fbc490;
color: #084177;
}
Leave a Reply