In my opinion, achieving this task solely with CSS might not be feasible. However, incorporating JavaScript offers a straightforward solution. Kindly inform me if I have misunderstood any of the requirements.
Resolution
To address this issue, I am resetting the --fluid-size
CSS variable during the load
and resize
events by executing the resetFluidSize
function. It is important to note that this process may impact performance as it triggers reflows each time it is executed, without any optimizations for simplicity.
I have utilized the outerWidth
method to prevent variations in zoom levels from affecting the proper scaling, ensuring consistent computed style regardless of page zoom settings.
Following calculations, I update the CSS variable using document.body.style.setProperty
.
Important Note
To view accurate values, launch the code snippet in full-page mode.
window.addEventListener('load', () => {
resetFluidSize();
window.addEventListener('resize', resetFluidSize);
});
const
minSize = 14,
maxSize = 22;
function resetFluidSize() {
const
factor = (window.outerWidth - 1280) / 640,
lerp = minSize + (maxSize - minSize) * factor,
clamp = Math.max(minSize, Math.min(maxSize, lerp)),
fluidSize = `${clamp}px`;
document.body.style.setProperty('--fluid-size', fluidSize);
/* Update the feedback display. */
document.getElementById('fluid-text').setAttribute('currentSize', fluidSize);
}
:root {
--fluid-size: 16px;
}
#fluid-text {
font-size: var(--fluid-size);
}
/* The following styles are for visual feedback purposes only */
p {
border-right: 1px solid black;
margin: 0;
width: fit-content;
position: relative;
}
p::after {
content: attr(currentSize);
position: absolute;
left: 100%;
}
<body>
<p style="font-size: 14px;" currentSize="14px">
Lorem ipsum
</p>
<p id="fluid-text">
Lorem ipsum
</p>
<p style="font-size: 22px;" currentSize="22px">
Lorem ipsum
</p>
</body>
Further Instructions
If you wish to test it locally, feel free to utilize this index.html provided on GitHub Gist.