Search code examples
csssveltesapper

Using relative sizes with rem units in Sapper


I am using Sapper to create a web app and want to use relative font sizes.

I have set fixed font sizes for different media queries on the body element. Then I want to use rem units for the font-size in subsequent text elements of Svelte components to adjust the font-size to the viewport.

HTML (Svelte component)

<h1>Title</h1>

CSS (of the Svelte component)

h1 {
  font-size: 2rem;
}

Global CSS of Sapper

body {
  font-size: 12 px;
}

@media (min-width: 600px ) {
  body {
    font-size: 15px;
  }
}

I would expect that the local component CSS is able to read the font-size on the global body element and therefore adjust the font-size in h1 to the viewport size. However, no action is seen. In contrast, using em units works fine.


Solution

  • For Svelte to not remove unused CSS selectors you can use the :global modifier.

    To change the font size used by rem values you should style html, not body.

    Example (REPL)

    <h1>Hello!</h1>
    
    <style>
      :global(html) {
        font-size: 12px;
      }
    
      @media (min-width: 600px) {
        :global(html) {
          font-size: 15px;
        }
      }
    
      h1 {
        font-size: 2rem;
      }
    </style>