Better fluid typography - 2.2 Beta

I don’t like any of existing typography calculators because they all start shrinking your fonts too early, while your window width is still > than width of your containers. There’s more clever way to do this if you add max-width and min-width to your typography formula. The down side is - it can’t be done just with CSS, so I wrote some calculator for myself with JS (+jQuery). Here’s a function from my app that does all the math:

/**
 * Quick math for clamp
 * html font-size should be 62.5%, so 1rem = 10px
 *
 * Δ for width: 1140 - 360 = 780px
 * Δ for font: 60 - 30 = 30px
 * Ratio: 30 / 780 = 0.03846px for 1px of width
 * In vw: 0.03846 * 100 = 3.846vw
 * 3.846 * 360 / 100 = 13.85px
 * 30 - 13.85 = 16.15
 * font-size: clamp(30px, 3.846vw + 16.15px, 60px);
 * Now pixels can be converted to rems
 *
 * @param shrinkSizePercent - how much you wanna reduce font size in %
 * @param maxSizeRem - maximum font size in rems
 * @returns {string} - CSS clamp
 */
function getClamp(shrinkSizePercent, maxSizeRem) {
	console.log(shrinkSizePercent);
	const containerWidth = parseInt($('#site-width').val());
	const oneRemPx = parseInt($(':root').css('font-size').replace(/\D/g, ""));

	const maxSizePx = maxSizeRem * oneRemPx;
	const minSizeRem = maxSizeRem * (1 - shrinkSizePercent / 100);
	const minSizePx = minSizeRem * oneRemPx;

	const slope = (maxSizePx - minSizePx) / (containerWidth - 360); // px per 1px viewport change
	const slopeVW = slope * 100; // convert to px per 1vw
	const interceptPx = maxSizePx - slope * containerWidth;

	// Convert to rems
	const slopeVWFinal = round(slopeVW, 3);
	const interceptRem = round(interceptPx / oneRemPx, 3);
	const minSizeRemFinal = round(minSizeRem, 3);
	const maxSizeRemFinal = round(maxSizeRem, 3);

	return `clamp(${minSizeRemFinal}rem, ${slopeVWFinal}vw + ${interceptRem}rem, ${maxSizeRemFinal}rem)`;
}

For containers with width = 1440px this calc gives me:

/* Major Third: 1:25 ratio */
--text-fluid-h1: clamp(4.901rem, 2.659vw + 3.97rem, 7.001rem);
--text-fluid-h2: clamp(3.921rem, 2.127vw + 3.176rem, 5.601rem);
--text-fluid-h3: clamp(3.136rem, 1.701vw + 2.541rem, 4.48rem);
--text-fluid-h4: clamp(2.509rem, 1.361vw + 2.032rem, 3.584rem);
--text-fluid-h5: clamp(2.008rem, 1.089vw + 1.626rem, 2.868rem);
--text-fluid-h6: clamp(1.606rem, 0.871vw + 1.301rem, 2.294rem);

So my fonts starts shrinking exactly on 1440px window width. And they stop shrinking at 360px because I hardcoded this value into JS (I just thought I never wanna change it).

2 Likes