Search code examples
cssmedia-queriesviewport-units

How to implement :root { font-size: calc(100vw / 40); } to scale font-size(s)


According to the CSS Values and Units Module Level 3, W3C Candidate Recommendation 8.1 Mathematical Expressions: ‘calc()’:

The following sets the ‘font-size’ so that exactly 40em fits within the viewport, ensuring that roughly the same amount of text always fills the screen no matter the screen size.

:root {
  font-size: calc(100vw / 40);
}

If the rest of the design is specified using the ‘rem’ unit, the entire layout will scale to match the viewport width.

I am wondering how to implement this. I assume I would need to use @media somewhere to detect the user's screen size, then set :root as shown and then use rem's for all the font-sizes. Could someone give me a simple step-by-step and/or feedback on whether this actually works? Thanks.


Solution

  • You do not need to use @media to detect the user's screen size. The beauty of vw/vh is that they adjust according to the size of the viewport automatically. Simply use vw/vh/rem for all size measurements after adding the above rule to your stylesheet and your layout will scale, even as the user resizes their browser.

    Here's a simple example. You can see that the width, height, margin-left and font-size properties all use rems or viewport units exclusively. Run the snippet, show it in full screen and resize your browser, and you'll see how the entire layout, including the h1 column and the text, scales with the width of your browser window (as indicated by the use of vw in the :root CSS rule).

    :root {
      font-size: calc(100vw / 40);
    }
    
    body, h1, h2 { margin: 0; }
    
    h1 {
      position: fixed;
      width: 15rem;
      height: 100vh;
      font-size: 4rem;
      background-color: #ccc;
    }
    
    h2, p { margin-left: 15rem; }
    
    h2 {
      font-size: 2.4rem;
      background-color: #ff0;
    }
    
    p {
      font-size: 1.2rem;
    }
    <h1>Title</h1>
    <h2>Subtitle</h2>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ea sed adversarium
       definitionem, legere malorum laboramus ne cum. Dictas corrumpit vix at, sea
       platonem senserit sapientem ne. At vel laudem audire bonorum. Perfecto posidonium
       eu has, ullum mollis inimicus eos te, sit eu novum atomorum.
    <p>Alii libris evertitur in vix, congue ocurreret ut usu, nostro dolores vulputate
       pri ex. Eu eam sint moderatius, eu eos wisi corpora, est sanctus corpora ad. Cu
       nam utamur saperet. Qui id purto quaerendum, ex usu iudico alterum voluptatibus.
    <p>Illum mucius praesent id eam, oratio habemus eum ei. Saepe docendi at est, eu mea
       perfecto voluptaria, has admodum recusabo contentiones te. Putant definitionem sea
       ea, viris tantas ad cum. Wisi melius ius ut, est te unum aliquando. Ea quo
       ancillae philosophia.