Sass mixins for Increased Contrast Mode (and Dark Mode)
Posted 22nd June 2021 in CSS and Development
When I added a high contrast version of my website I used an almost-identical SCSS (Sass) mixin to the one I use for Dark Mode. It’s a riff on the mixin Will Moore from 1Password wrote about in late 2018, and here’s how it looks:
@mixin high-contrast($background: null, $colour: null) {
@media screen and (prefers-contrast: more) {
@if ($background != null and $colour != null) {
background-color: $background;
color: $colour;
@content;
}
@else if ($background != null and $colour == null) {
background-color: $background;
@content;
}
@else if ($colour != null and $background == null) {
color: $colour;
@content;
}
@else {
@content;
}
}
}
This allows us to do any of the following:
- Style the text colour only:
@include high-contrast(black, white);
- Style the background only:
@include high-contrast($background: black);
- Style the background and text colour:
@include high-contrast($colour: white);
- Style something other than background and text colour:
@include high-contrast() {
border-color: white;
} - Style the background, text colour and something else:
@include high-contrast(black, white) {
border-color: white;
} - Style the background and something else:
@include high-contrast($background: black) {
border-color: white;
} - Style the text colour and something else:
@include high-contrast($colour: white) {
border-color: white;
}
Pretty handy!
I mentioned I do the same for Dark Mode, and that mixin is almost identical; it’s just the name of the mixin and the media query that’s called that change:
@mixin dark-mode($background: null, $colour: null) {
@media screen and (prefers-color-scheme: dark) {
@if ($background != null and $colour != null) {
background-color: $background;
color: $colour;
@content;
}
@else if ($background != null and $colour == null) {
background-color: $background;
@content;
}
@else if ($colour != null and $background == null) {
color: $colour;
@content;
}
@else {
@content;
}
}
}
The @includes
work exactly the same, substituting high-contrast
for dark-mode
.