Truly responsive text with CSS CALC function

Responsive text

I know that we can make text responsive by using media queries but personally I am not keen on this approach

Firstly it is a bit cumbersome to write and secondly the transitions are not smooth as the viewport reduces, the text “jumps” when passing the transitions

So I thought I would share how implement
responsive text by the use of CSS Calc function

So let’s say I want text to start at 12px up to 400 pixels screen width then increase to a maximum of 24px at resolutions of 1920 width and above

So we have all the requirements for the calculation

So we know our resolution range and our text sizes, all we need to do is formulate how to calculate the correct text size from the screen resolution

So lets start with the full width of the screen as a vh parameter, namely 100vh

We can then calculate the number of pixels remaining after the base 400 pixels is removed with 100vh – 400px

We then divide that by the max size minus the minimum size to calculate a ratio

(100vw – 400px) / (1920 – 400)

Finally we “size” the pixel by multiplying the base size by the max pixel size by the minimum

So we end up with a formula of

16px + (24 – 16) * (100vh – 400px) / (1920 – 400)

We then simply wrap that in a CSS CALC function within a class definition, something like

.front-page-title-top {

font-size: calc( 24px + (24 - 12) * ( 100vw - 400px ) / ( 1920 - 400 ));

}

Simply apply that class to any text and it will be truly responsive. The text will then scale smoothly as the page size reduces

OK, really old browsers don’t support CALC but most do now

NOTE CALC is really fussy about spaces, it requires them in certain places, the editor will prompt you if spaces need to be inserted. In the example above the spaces are not there to beautify it, they are required.

Community Page
Last updated: