Ability to change color theme is a powerful feature and here is an easier way to achieve it while ensuring that accessibility is not compromised and text colors automatically adjusts according to the choosen theme.
$color-primary: #cde8e7;
$color-secondary: #368fa4;
$text-light: #e8e6e6;
$text-dark: #03525b;
$text-light
or $text-dark
for text-primary
and text-secondary
colors.
And we can calculate this by using the below formula.@function text-contrast($n, $w, $b) {
$color-brightness: round((red($n) * 299) + (green($n) * 587) + (blue($n) * 114) / 1000);
$light-color: round((red(#ffffff) * 299) + (green(#ffffff) * 587) + (blue(#ffffff) * 114) / 1000);
@if abs($color-brightness) < ($light-color/2) {
@return $w;
} @else {
@return $b;
}
}
$text-primary: text-contrast($color-primary, $text-light, $text-dark);
$text-secondary: text-contrast($color-secondary, $text-light, $text-dark);
background: $primary
then put color: $text-primary
and similarly for secondary.And a good way to do this will be use mixins.
@mixin primary() {
background: $color-primary;
color: $text-primary;
}
@mixin secondary() {
background: $color-secondary;
color: $text-secondary;
}
.primary-box {
@include primary;
height: 200px;
width: 200px;
...
}
.secondary-box {
@include secondary;
...
}
That's all we need to switch between different themes on the fly without losing accessiblity and maintaining proper color-contrasts for easily readable text.
Here's a codepen to play with the code
Thanks for reading all along. Let me know your feedback/suggestions in the comments.
- Ayush 🙂