A code-efficient CSS pattern for your theming and coloring needs, inspired by OOP and CSS Variables

Let’s talk about doing more with less code.

TLDR;

The problem : theming and coloring imply exponential CSS classes

Using the Setter/Getter pattern to achieve code-efficiency in theming and coloring

1. We define CSS color variables at the:root level

:root {
--red: #f8333c;
--light-red: #f48489;
--dark-red: #df000a;
--on-red: #ffffff;
--orange: #f46036;
--light-orange: #f19d85;
--dark-orange: #dd3100;
--on-orange: #ffffff;
--yellow: #ffbf00;
--light-yellow: #f6ce55;
--dark-yellow: #b38600;
--on-yellow: #ffffff;
--olive: grey;
--light-olive: #a6a6a6;
--dark-olive: #635151;
--on-olive: #ffffff;
--green: #44af69;
--light-green: #7fc096;
--dark-green: #268045;
--on-green: #ffffff;
// .... And many other swatches
}

2. We use special CSS classes, called Setters, that take one of the root variables (for instance, — red) and translate it to a local variable (for instance — x).

.x-azure,
.xh-azure:focus,
.xh-azure:hover {
--x: var(--azure);
--light-x: var(--light-azure);
--dark-x: var(--dark-azure);
--on-x: var(--on-azure);
}
.x-blue,
.xh-blue:focus,
.xh-blue:hover {
--x: var(--blue);
--light-x: var(--light-blue);
--dark-x: var(--dark-blue);
--on-x: var(--on-blue);
}
.x-pink,
.xh-pink:focus,
.xh-pink:hover {
--x: var(--pink);
--light-x: var(--light-pink);
--dark-x: var(--dark-pink);
--on-x: var(--on-pink);
}

3. We “get” the local variables and apply it to our HTML

.b-x {
background: var( --x);
}
.b-dark-x {
background: var( --dark-x):
}
.b-light-x {
background: var( --light-x);
}
.b-on-x {
background: var( --on-x);
}
.c-x {
color: var( --x);
}
.c-dark-x {
color: var( --dark-x);
}
.c-light-x {
color: var( --light-x);
}
.c-on-x {
color: var( --on-x);
}
<div>
<div class='x-red xh-blue b-x'> This div has red background and blue on hover</div>
<div class='x-red b-x c-on-x'> This div has red background and contrasted text </div>
<div class='x-red b-light-x c-on-x'> This div has light red background and contrasted text </div>
<div class='x-red b-dark-x c-on-x'> This div has dark red background and contrasted text </div>
</div>

Final words

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store