csslessfont-size

Emulating “relative pixels” in CSS, based on root font size


As far as I know, there is still no such thing as a “relative pixel” in CSS. (1 relative pixel == 1px, if 1rem == 16px, or proportionally changed, if not).

I'm looking for an expressive way of emulating these units.

So far the best shot I've seen is using LESS:

@font-size: 16;
@rem: @font-size*1rem;

h1
{
  font-size: 20/@rem;
}

/@ looks pretty neat as a prefix meaning “relative pixels as” [rem] (of course it's just a division operation). But it requires the LESS preprocessor.

calc(20rem / 16) seems a bit verbose due to repeating calc and 16.

Are there other ways in 2025 to emulate these units?


Solution

  • I ended up with a LESS plugin. less-lib.js:

    registerPlugin(
        {
            install: function (less, pluginManager, functions)
            {
                functions.add('rp', function (rpx)
                {
                    return new tree.Dimension(rpx.value / 16, 'rem');
                });
            }
        }
    )
    

    Using:

    @plugin "less-lib";
    .my-class
    {
        width: rp(20);
    }