# Buttons With Automatically Readable Text (SCSS)

> Styles buttons from one brand color and picks black or white text automatically based on how light the color is, with matching hover and focus states, so button text always stays readable.

- Type: SCSS
- Runs: Site-wide header
- Category: [Accessibility](https://wpide.com/library/category/accessibility/)
- Tags: contrast, buttons, scss
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/a11y-auto-contrast-buttons-scss/

## Code

```scss
// Brand colors; button text color is chosen automatically.
$wpide-primary: #2271b1;
$wpide-secondary: #f0b849;

@function wpide-text-on($bg) {
    $brightness: (red($bg) * 299 + green($bg) * 587 + blue($bg) * 114) / 1000;
    @if $brightness > 150 {
        @return #111111;
    }
    @return #ffffff;
}

@mixin wpide-button($bg) {
    background-color: $bg;
    color: wpide-text-on($bg);
    border: 2px solid darken($bg, 12%);

    &:hover {
        background-color: darken($bg, 8%);
        color: wpide-text-on(darken($bg, 8%));
    }

    &:focus-visible {
        outline: 3px solid wpide-text-on($bg);
        outline-offset: -5px;
        box-shadow: 0 0 0 3px darken($bg, 20%);
    }
}

.wp-block-button__link,
.wp-element-button,
.button-primary {
    @include wpide-button($wpide-primary);
}

.is-style-secondary .wp-block-button__link,
.button-secondary {
    @include wpide-button($wpide-secondary);
}
```

## Notes

Change $wpide-primary and $wpide-secondary; the brightness formula is an approximation, so still check final colors with a contrast checker.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Buttons With Automatically Readable Text (SCSS)" in its snippet library and add it in one click; or create a new SCSS snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
