CSS color-contrast

A useful article by Lea Verou on CSS color-contrast.

On compliance vs readability: Generating text colors with CSS

:root {
  --example-bg-color: pink;
}

.example {
  background-color: var(--example-bg-color);
  color: lightgrey;
  display: flex;
  place-content: center;
  padding: 2lh;

  .example__content {
    border: 1px solid #000;
    display: flex;
    flex-direction: column;
    gap: 1lh;

    > * {
      margin: 0;
      padding: 0;
    }
  }
}

@supports (color: contrast-color(white)) {
  .example {
    /* Set contrasting text color automatically */
    color: contrast-color(var(--example-bg-color));
  }
}

example

a test here

Note: if your browser does not support contrast-color(), the text will be lightgrey as defined in the first rule and black if your browser supports it.

Browser support — contrast-color

  • 147
  • 147
  • 146
  • 26
  • 26
Data from MDN Browser Compat Data