Technology News

You want enabling CSS selectors, not disabling ones

An enabling selector is what I call a selector that does a job without disabling the particular rule. I’ll explain using the following example.

Let’s say we have list items and we want to add the margin to the last one.

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<ul>

Here’s the usual, disabling way.

li {
margin-bottom: 1em;
}

li:last-child {
margin-bottom: 0;
}

First, we add margin-bottom to all elements. Then, we disable the bottom margin on the last element. I call this technique disabling selector since the li:last-child selector disables the previous selector’s rule.

But we could do better using enabling selectors.

li:not(:last-child) {
margin-bottom: 1em;
}

The selector li:not(:last-child) is enabling margin-bottom on all elements except the last one. There’s no need to disable anything. That is much readable and maintainable if you ask me.

Here’s another version of the enabling selector for the same example.

li + li {
margin-top: 1em;
}

In this version, we add margin-top to all elements that have a previous sibling, which means to all elements except the first one, which doesn’t have a previous sibling.

There you have it, enabling selectors that do a better job in less code. Here’s the demo:

Teaching as a Side Hustle for Engineers
5 Ways to Keep Your Operations Lean

Related Articles

Good Meetings

good-meetings
Like it or not, meetings are essential to a good working environment and communication. Therefore, it’s crucial that we work on making them as productive as possible. Today we’ll explore…

3 Privacy Fixes Most People Never Make

3 Privacy Fixes Most People Never Make
It’s a new year, and a perfect time for fresh starts, especially when it comes to privacy. If you made your way to our channel because you care about privacy,…

Top 10 Free Resources For Learning React.js

top-10-free-resources-for-learning-react
The frontend ecosystem is dominated by React.js. It’s one of the fastest rising JavaScript frameworks on the web with no signs of slowing down, and there’s plenty of job opportunities…