I’ve been playing around more with writing and customizing my own Sass functions and mixins. This is a function I’ve seen out there in various iterations that I styled out as if I were an accomplished Potions Master.
The function chooses the appropriate contrast of text colour depending on what the background colour is set as. There’s definitely room for expanding the complexity as far as achieving a more ‘true’ contrast rather than just returning straight up #000
or #FFF
. In this instance, I used lightness, which is a built-in method that returns the lightness value from the RGBA component.
The basic structure is the following:
@function let-the-light-in($color) {
// What you want to occur happens in here.
}
let-the-light-in
being your chosen name for your function and $color
being the variable that you will be passing to it to utilize to get to the end goal.
And this is the conditional that is placed inside that uses that built-in method to figure out the lightness of your colour and compare it to the halfway point of the scale (1-100).
@if (lightness($color) > 50) {
// If lighter, return dark colour
} @else {
// If darker, return light colour
}
The final product involves tucking that conditional “if this, do that – or otherwise do THIS” inside the function.
// Final function to shift font colour based on background lightness.
@function let-the-light-in($color) {
@if (lightness($color) > 50) {
@return #000000; // Lighter background returns dark color
} @else {
@return #ffffff; // Darker background returns lighter color
}
}
I set some colour variables to apply to my different beakers and then used my function to return the desired colour based on the variable that was passed to it.
// Gillyweed. &.gillyweed {
background: $gillyweed;
border: rem(10) solid $gillyweed; color: let-the-light-in($gillyweed); }
Check out the CodePen below to see the finished product in action with some sweet bubble animations thrown in.
See the Pen From Darkness Comes Light, Part Two by Allison Tarr (@allisonplus) on CodePen.0