Responsive Text with CSS Clamp
Creating a responsive text sizing with CSS clamp
css
scss
responsive

DEMO
Making font-size responsive is a simple task with modern CSS.
I have following React component setup for this demo as follows:
Making font-size responsive is a simple task with modern CSS.
I have following React component setup for this demo as follows:
import styles from "./style.module.scss"; const CssTextClamp = () => { return ( <main> <div className={styles.container}> <h1>h1. Header</h1> <h2>h2. Header</h2> <h3>h3. Header</h3> <h4>h4. Header</h4> <h5>h5. Header</h5> </div> </main> ); }; export default CssTextClamp;
And corresponding CSS file as follow:
.container { --font-size-xs: 1rem; --font-size-s: 1.25rem; --font-size-m: 1.75rem; --font-size-l: 2.5rem; --font-size-xl: 3rem; h1 { font-size: var(--font-size-xl); } h2 { font-size: var(--font-size-l); } h3 { font-size: var(--font-size-m); } h4 { font-size: var(--font-size-s); } h5 { font-size: var(--font-size-xs); } }
Problem with this is that font-size is static, in another word no matter the size of the window it will remain the same. There is numerous way to fix this and very common solution is CSS media query or using SASS mixins. Although this is not very hard to do, amount of code gets build up and depending on the size of the project it can quickly gets messy.

But with CSS clamp function this process becomes one liner. Let's go through how to refactor above CSS.
--font-size-xs: clamp(0.75vw, 2vw, 1vw); --font-size-s: clamp(1vw, 2.5vw, 1.25vw); --font-size-m: clamp(1.25vw, 4vw, 1.75vw); --font-size-l: clamp(1.5vw, 6vw, 2.5vw); --font-size-xl: clamp(1.75vw, 8vw, 3vw);
Now each font size is clamped with (minimum, preferred, maximum value) along with viewport width values to make the size responsive as the window size is changed (eg. 1vw = 1% of windows width). This is will work perfectly fine but it will add one issue where you won't be able to zoom in and out using ctrl +/- or ctrl scroll up/down. Let's tackle this by changing our minimum and maximum value unit to rem.
--font-size-xs: clamp(0.5rem, 2vw, 1rem); --font-size-s: clamp(0.75rem, 2.5vw, 1.25rem); --font-size-m: clamp(1rem, 4vw, 1.75rem); --font-size-l: clamp(1.25rem, 6vw, 2.5rem); --font-size-xl: clamp(1.5rem, 8vw, 3rem);
Converting the unit to rem will allow you to zoom in out the font-size while making the font-size responsive depending on the window size. Unless you really need percise control over the font size this approach is simple and effective solution.