I'm trying to make a mixin that can detect whether to show dark text (if the colour passed into buttonStyles
is light), or light text (for passing darker colours). I remember there was a way to do it with LESS and wondered whether there's a SASS way.
Consider this SCSS:
$white: #fff;
$text: #393939;
$font-std: 18px;
$transition-std: 0.4s ease all;
$primary: #f8e421;
$secondary: #354052;
@mixin buttonStyles($color) {
font-size: $font-std;
color: $text;
padding: 1rem 3rem;
background-color: $color;
color: $white;
transition: $transition-std;
&:hover {
cursor: pointer;
background-color: lighten($color, 15%);
}
&:focus {
background-color: lighten($color, 10%);
}
&:active {
background-color: lighten($color, 25%);
}
}
.btnPrimary {
@include buttonStyles($primary);
}
.btnSecondary {
@include buttonStyles($secondary);
}
And this html:
<button class='btnSecondary'>secondary</button>
<button class='btnPrimary'>primary</button>
The secondary button is far more legible than the primary button. I know that I could pass in a second argument that would set the text colour, but wondered whether there's a cleaner, automatic way as with LESS? (unfortunately I can't remember how it was done with LESS)
Live demo: https://jsfiddle.net/3v0ckeq9/5/
Thank you
EDIT:
I've added this function which almost seems to work:
@function ligthOrDark($color) {
$result: red;
@if (blackness($color) == 50) { // fails with > 50 or < 50
$result: green;
}
@return $result;
}
But the issue is that SASS complains when trying to determine wether the colour is greater than 50 (or less than) but is ok with ==
. I just want to be able to determine whether the color provided is dark or light so I can apply the right color of text.
Seems that there should be options to determine the darkness or lightness here: https://sass-lang.com/documentation/modules/color#grayscale
Alternative solutions are welcomed.