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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.