Skip to content

Instantly share code, notes, and snippets.

@zaydek-old
Last active September 1, 2019 06:54
Show Gist options
  • Save zaydek-old/9e7618dd625ab1bd377ac91316b20d2b to your computer and use it in GitHub Desktop.
Save zaydek-old/9e7618dd625ab1bd377ac91316b20d2b to your computer and use it in GitHub Desktop.

Of all the interesting applications of CSS variables, I find the idea of what I'm calling a CSS combinator idiom both subtle and interesting. The idea is to think about CSS in terms of a hierarchical programming model instead of something flat, which I believe is the default interpretation of how to use CSS variables.

Here's the idea; in CSS we can build abstractions from fundamental building-blocks.

p       { color: red                 ; }
.red    { color: red                 ; }
.red    { color: var(--red          ); }
.danger { color: var(--danger       ); }
.danger { color: var(--danger, --red); }

Through this abstraction chain, we've gone from imperative to semantic, functional CSS with a fallback variable. This is idea because the util classes can be both reused and changes to the implementation class will propagate throughout the website. This, and users can define a semantic variable such as --danger and not feel afraid if it's unset because a global --red can be assumed to be set.

As great and modern as this all is, we have one crucial limitation. With this code, we are assuming that --danger should be consistent in all places and I think that's too great an assumption to make. Despite that we can define --danger once in the :root, how can we create subclasses that inherit some but not all of their parent classes' characteristics?

.little-dangerous { --danger: <little-dangerous>; }
.extra-dangerous  { --danger: <extra-dangerous >; }

Now, we've transitioned to describing ideas as nouns e.g. .danger to describing ideas as combinations of nouns and adjectives e.g. .little-dangerous and .extra-dangerous. This idiom is both simple and powerful for authoring subclasses and instances of subclasses, where subclasses are defined in the HTML, and instances are defined in class list e.g. class="danger extra-dangerous".

Here's a proof-of-concept CodePen: https://codepen.io/zaydek/pen/ejyKOd?editors=1100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment