Halloween Sale 15% off Ends in See the plans
SCSS

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.

Don’t have WPIDE yet? Install it on your site

Code

// 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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.