<h1>Variable font weight based on contrast preference</h1>
<p>Humans perceive white on black vs black on white differently.</p> 
<p>In dark mode, the light colored font appears to be thicker or glow a bit more, even though weight and <abbr title="grade: adjust the stroke thickness of a typeface without changing its width, spacing, or kerning">GRAD</abbr> are unchanged. The CSS in this demo counterbalances that by using the font's <abbr title="grade: adjust the stroke thickness of a typeface without changing its width, spacing, or kerning">GRAD</abbr> axis and a negative value, shrinking the perceived thickness of the font without affecting layout. It also takes the user's <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-contrast">preferred contrast preference</a> into account.</p>
<p>Subtle, but appreciated.</p>
@font-face {
  font-family: "Roboto Flex";
  src: url('https://assets.codepen.io/2585/RobotoFlex') format('truetype');
}

@layer demo {
  body {
    --base-grade: 0;
    
    font-variation-settings: "GRAD" var(--base-grade);
  }
  
  @media (prefers-contrast: more) {
    body {
      --base-grade: 700;
    }
  }
  
  @media (prefers-contrast: less) {
    body {
      --base-grade: -50;
    }
  }
  
  @media (prefers-color-scheme: dark) {
    body {
      --base-grade: -50;
    }
  }
  
  @media (prefers-color-scheme: dark) and (prefers-contrast: more) {
    body {
      --base-grade: 150;
    }
  }
  
  @media (prefers-color-scheme: dark) and (prefers-contrast: less) {
    body {
      --base-grade: -150;
    }
  }
}

@layer demo.support {
  html {
    color-scheme: light dark;
    height: 100%;
    display: grid;
  }
  
  body {
    display: grid;
    place-content: center;
    padding: 1.5rem;
    gap: 1lh;
    font-family: Roboto Flex;
  }
  
  h1, p {
    margin: 0;
    text-box: trim-both cap alphabetic;
  }
  
  h1 {
    max-inline-size: 30ch;
    text-wrap: balance;
    line-height: 1.5cap;
  }
  
  p {
    max-inline-size: 60ch;
    text-wrap: pretty;
  }
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.