DEV Community

Cover image for Writing Logic in CSS
Daniel Schulz
Daniel Schulz

Posted on • Originally published at iamschulz.com

Writing Logic in CSS

CSS is a highly specialized programming language focusing on style systems. Because of this unique use case and its declarative nature, it's sometimes hard to understand. Some folks even deny it's a programming language altogether. Let's prove them wrong by programming a smart, flexible style system.

Control Structures

More traditional, general-purpose languages (like JavaScript) give us tools like Conditions (if/then), Loops (for, while), Logical Gates (===, &&, etc.) and Variables. Those structures are named differently in CSS, their syntax is wildly different to better accommodate the specific use case of styling a document, and some of those simply weren't available in CSS up until a few years ago.

Variables

Variables are the most straightforward ones. They're called Custom Properties in CSS (although everyone calls them variables anyway, even their own syntax).

:root {
    --color: red;
}
span {
    color: var(--color, blue);
}
Enter fullscreen mode Exit fullscreen mode

The double-dash declares a variable and assigns a value. This has to happen in a scope because doing so outside of a selector would break the CSS syntax. Notice the :root selector, which works as a global scope.

Conditions

Conditions can be written in a number of ways, depending on where you want to use them. Selectors are scoped to their elements, media queries are scoped globally, and need their own selectors.

Attribute Selectors:

[data-attr='true'] {
    /* if */
}
[data-attr='false'] {
    /* elseif */
}
:not([data-attr]) {
    /* else */
}
Enter fullscreen mode Exit fullscreen mode

Pseudo Classes:

:checked {
    /* if */
}
:not(:checked) {
    /* else */
}
Enter fullscreen mode Exit fullscreen mode

Media Queries:

:root {
    color: red; /* else */
}
@media (min-width > 600px) {
    :root {
        color: blue; /* if */
    }
}
Enter fullscreen mode Exit fullscreen mode

Loops

Counters are both the most straightforward form of loops in CSS, but also the one with the narrowest use case. You can only use counters in the content property, displaying it as text. You can tweak its increment, its starting point, and its value at any given point, but the output is always limited to text.

main {
    counter-reset: section;
}

section {
    counter-increment: section;
    counter-reset: section;
}

section > h2::before {
    content: 'Headline ' counter(section) ': ';
}
Enter fullscreen mode Exit fullscreen mode

But what if you wanted to use a loop to define a recurring layout pattern? This kind of a loop is a bit more obscure: It's the Grid's auto-fill property.

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}
Enter fullscreen mode Exit fullscreen mode

This fills the grid with as many elements as it can fit, while scaling them to fill the available space, but breaking them into multiple rows when it needs. It repeats for as long as it finds items and caps them to a minimum width of 300px and a maximum width of one fraction of its own size. It's probably easier to see than to explain:

And finally, there are looped selectors. They take an argument, which can be a formula to select very precisely.

section:nth-child(2n) {
    /* selects every even element */
}

section:nth-child(4n + 2) {
    /* selects every fourth, starting from the 2nd */
}
Enter fullscreen mode Exit fullscreen mode

For really special edge cases, you can combine :nth-child() with :not(), like:

section:nth-child(3n):not(:nth-child(6)) {
    /* selects every 3rd element, but not the 6th */
}
Enter fullscreen mode Exit fullscreen mode

You can replace :nth-child() with :nth-of-type() and :nth-last-of-type() to change the scope of those last few examples.

Logic Gates

Ana Tudor wrote an article on CSS Logic Gates. Those work on the idea of combining variables with calc. She then goes on 3D modeling and animating objects with that. It kinda reads like arcane magic, gets way more insane as the article goes on, and is generally one of the best explanations why CSS in fact is a programming language.

Techniques

The Owl Selector

* + * {
    margin-top: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

The Owl Selector selects every item that follows an item. Applying a margin-top to that effectively adds a gap between the items, like grid-gap does, but without the grid system. That also means it's more customizable. You can overwrite your margin-top and adapt for any kind of content. Want to have 1rem of space between each item, but 3rem before a headline? That's easier to do with an owl selector than in a grid.

Kevin Pennekamp has an in-depth article on it that even explains its algorithm in pseudo code.

Conditional Styling

We can create toggles in our css code that switch certain rules on and off with variables and calc. This gives us very versatile conditions.

.box {
    padding: 1rem 1rem 1rem calc(1rem + var(--s) * 4rem);
    color: hsl(0, calc(var(--s, 0) * 100%), 80%);
    background-color: hsl(0, calc(var(--s, 0) * 100%), 15%);
    border: calc(var(--s, 0) * 1px) solid hsl(0, calc(var(--s, 0) * 100%), 80%);
}

.icon {
    opacity: calc(var(--s) * 100%);
    transform: scale(calc(var(--s) * 100%));
}
Enter fullscreen mode Exit fullscreen mode

Depending on the value of --s, .box it will either enable or disable its alert styles.

Automatic contrast colors

Let's take the same logic one step further and create a color variable that's dependent on its contrast to the background color:

:root {
    --theme-hue: 210deg;
    --theme-sat: 30%;
    --theme-lit: 20%;
    --theme-font-threshold: 51%;

    --background-color: hsl(var(--theme-hue), var(--theme-sat), var(--theme-lit));

    --font-color: hsl(
        var(--theme-hue),
        var(--theme-sat),
        clamp(10%, calc(100% - (var(--theme-lit) - var(theme-font-threshold)) * 1000), 95%)
    );
}
Enter fullscreen mode Exit fullscreen mode

This snippet calculates a background color from HSL values and a black or white font color, by inverting the background's lightness value. This alone could result in low color contrast (a 40% grey font on a 60% grey background is pretty much illegible), so I'll subtract a threshold value (the point where the color switches from white to black), multiply it by an insanely high value like 1000 and clamp it between 10% and 95%, to get a valid lightness percantage in the end. It's all controllable by editing the four variables at the beginning of the snippet.

This method can also be used to write intricate color logic and automatic themes, based on HSL values alone.

Cleaning up the Stylesheet

Let's combine what we have so far to clean up the stylesheet. Sorting everything by viewports seems a bit spaghetti-like, but sorting it by component doesnt feel any better. With variables we can have the best of both worlds:

/* define variales */
:root {
    --paragraph-width: 90ch;
    --sidebar-width: 30ch;
    --layout-s: "header header" "sidebar sidebar" "main main" "footer footer";
    --layout-l: "header header" "main sidebar" "footer footer";
    --template-s: auto auto minmax(100%, 1fr) auto /
        minmax(70%, var(--paragraph-width)) minmax(30%, var(--sidebar-width));
    --template-l: auto minmax(100%, 1fr) auto /
        minmax(70%, var(--paragraph-width)) minmax(30%, var(--sidebar-width));
    --layout: var(--layout-s);
    --template: var(--template-s);
    --gap-width: 1rem;
}

/* manipulate variables by viewport */
@media (min-width: 48rem) {
    :root {
        --layout: var(--layout-l);
        --template: var(--template-l);
    }
}

/* bind to DOM */
body {
    display: grid;
    grid-template: var(--template);
    grid-template-areas: var(--layout);
    grid-gap: var(--gap-width);
    justify-content: center;
    min-height: 100vh;
    max-width: calc(
        var(--paragraph-width) + var(--sidebar-width) + var(--gap-width)
    );
    padding: 0 var(--gap-width);
}
Enter fullscreen mode Exit fullscreen mode

All the global variables are defined at the very top and sorted by viewport. That section effectively becomes the Definition of Behavior, clearing questions like:

  • Which global aspects of the stylesheet do we have? I'm thinking of things like font-size, colors, repeating measures, etc.
  • Which frequently changing aspects do we have? Container widths, Grid layouts and the like come to mind.
  • How should values change between viewports? Which global styles do apply to which viewport?

Below are the rule definitions, sorted by component. Media Queries aren't needed here anymore, because those are already defined at the top and put into variables. We can just code along in out stylesheets uninterrupted at this point.

Reading the hash parameter

A special case of pseudo classes is the :target selector, which can read the hash fragment of the URL. Here's a demo that uses this mechanic to simulate an SPA-like experience:

I've written a post on that. Just be aware that this has some serious accessibility implications and needs some JavaScript mechanics to actually be barrier free. Don't do this in a live environment.

Setting Variables in JavaScript

Manipulating CSS Variables has become a very powerful tool by now. We can also leverage that in JavaScript:

    // set --s on :root
    document.documentElement.style.setProperty('--s', e.target.value);

    // set --s scoped to #myID
    const el = document.querySelector('#myID');
    el.style.setProperty('--s', e.target.value);

    // read variables from an alement
    const switch = getComputedStyle(el).getPropertyValue('--s');
Enter fullscreen mode Exit fullscreen mode

The codepen examples above work just like that.

Wrapping up

CSS is very much capable of difining smart and reactive layout systems. It's control structures and algorithms may be a bit weird compared to other languages, but they're there and they're up to the task. Let's stop just describing some styles and start making them work.

Top comments (37)

Collapse
 
seanolad profile image
Sean

Negl ten minutes ago I definitely would deny that CSS was a language. It's always had a lesser place in my mind considering I could just use javascript but I think this has changed my mind. I'm going to try to deepen my knowledge of css thanks to this post, I think there is a lot to be gained from enlarging what I know. I know damn well that it'll probably save me many hours of scrolling google. Great post!!🔥🔥👌

Collapse
 
laras126_99 profile image
Lara Schenck

Folks here might like my talk about algorithms in CSS!
notlaura.com/algorithms-of-css-sou...

Collapse
 
iamschulz profile image
Daniel Schulz

Yes! Your talk has been a huge inspiration. Can't recommend it enough

Collapse
 
well1791 profile image
Well

A lot of thanks for sharing!

Collapse
 
vyckes profile image
Kevin Pennekamp

@iamschulz Thanks for the mention!

Collapse
 
robole profile image
Rob OLeary

Thanks for putting this together. I have wanted to look further into this. Do you have an opinion on when you should use JS instead of these techniques?

Collapse
 
iamschulz profile image
Daniel Schulz

When you absolutely hit the limits of CSS. Container queries would be an example, until its native CSS counterpart is widely adopted in browsers.

I also think you should use JS alongside CSS to help accessibilty.

Collapse
 
rkallan profile image
Info Comment hidden by post author - thread only accessible via permalink
RRKallan

I don’t see where JS will help accessibility. I think it’s a plus for ui / look and feel

 
iamschulz profile image
Daniel Schulz

For example setting showing/hiding elements for screenreaders. Dis/enabling inputs. Switching out aria attributes. Stuff like that. CSS isn't the right tool for that.

Thread Thread
 
rkallan profile image
Info Comment hidden by post author - thread only accessible via permalink

Show / hide element could be done by html & css

<input type=“checkbox” /> 
<div>hi content</div>
Enter fullscreen mode Exit fullscreen mode
.input[type=checkbox] ~ div {
    display: none;
}

.checkbox:checked ~ div {
    display: block;
}
Enter fullscreen mode Exit fullscreen mode

Switching area attributes or changing is not necessary when using correct semantic element when excising.

Let me say, I haven’t yet needed JS to have correct response on screen reader.

 
iamschulz profile image
Daniel Schulz

That works on user input, but how would you hide an element on a responsive layout change? How would you set aria-expanded on a drawer? How would you try and build a mega menu in CSS only while keeping it accessible to SRs? How would you tab-lock a modal in CSS? Just because you didn't come across a use case yet doesn't mean they aren't plentiful.

Thread Thread
 
rkallan profile image
RRKallan

Responsive layout changes when browser size changed. I will use media queries.

No need for aria-expanded with HTML5 elements details & summary
Also aria-live

<details>
    <summary>Title</summary>
    <div>
        Place your content which will show / hide on press 
    </div>
</details>
Enter fullscreen mode Exit fullscreen mode

To prevent the ability to tab / focus outside your element you can use

element:focus-within {}
Enter fullscreen mode Exit fullscreen mode

A massive menu. Assumption more then multiple levels. Here I would go to talk first with business. Why so many. Levels. Looking for better better cleaner structure.
Also for menu there is no need to use aria-expanded. Show hide text based on checked
And yes for multi level menu and keyboard support there will be need JS for esc, arrows pageup and pagedown.

Thread Thread
 
iamschulz profile image
Daniel Schulz

Aria-live and focus-within don't work like you describe. Please read up on those topics. And please manually test in screen readers, keyboard only navigation and/or other assistive tech.

Thread Thread
 
rkallan profile image
RRKallan

It's magic. your response said enough. Yes the focus-within is correct not totally described. It's right when you can speek. ?? i wooul=ld me more and moer lrss

Collapse
 
rkallan profile image
RRKallan

My opinion when not to use JS, if it can be done without JS

Collapse
 
roblevintennis profile image
Rob Levin

I thought of [aria-hidden] { ... } when I saw your [data-attr='true'] based logic examples. Suppose it's an option for any attribute really. Only issue with this is its very generalized on its own.

Collapse
 
iamschulz profile image
Daniel Schulz

How's providing generalized examples a drawback?

Collapse
 
roblevintennis profile image
Rob Levin

I meant that using [aria-hidden] alone or any data attribute is overly generalized. I was not intending to communicate that you providing generalized examples is a drawback; just that usage of it alone is generalized. Hope that clarifies misunderstanding. Thanks for the article.

Collapse
 
ninofiliu profile image
Nino Filiu

I knew about the awesome CSS-only SPA-like navs thanks to :target, but I didn't know about CSS counters, thanks for sharing!

Collapse
 
yw662 profile image
yw662

I wonder...would these styles perform better than plain javascript ?

Collapse
 
iamschulz profile image
Daniel Schulz

No, you'd only add another step to the render pipeline. No Javascript is always faster than Javascript.

Collapse
 
styletheandriod profile image
Stylestheandriod

Ohh wow I love this

Collapse
 
cycool29 profile image
cycool29

Thanks for sharing. Really useful post.

Collapse
 
mrpaulishaili profile image
Paul C. Ishaili

Real Brilliant!

Collapse
 
bhansa profile image
Bharat Saraswat

crazy, crazy...

Collapse
 
nft_artsy profile image
The Volks NFT

Nice one!

Collapse
 
gregjacobs profile image
Greg

Great Article! Thank you!
I love CSS 💪🏼

Collapse
 
asifurrahamanofficial profile image
Asifur Rahaman

GOAT

Collapse
 
subhanprime profile image
Subhan Ali

this post changes my mind completely about css . i love your explination.

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more