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

An Introduction to the Rollup.js JavaScript Bundler

Exploring the Potential of the Metaverse: A New World Awaits
Rollup.js is a next-generation JavaScript module bundler from Rich Harris, the author of Svelte. It compiles multiple source files into a single bundle. The benefits include: development is easier to…

How to Manage your Entire Marketing Budget

How to Manage your Entire Marketing Budget
Managing a marketing budget can be difficult, especially if it’s your first time doing it. There are many different things to consider, and it can be tough to know where…

Top Benefits Of Hybrid Events

Top Benefits Of Hybrid Events
Audience engagement is a major objective of every event. Marketers want to organize something that would remain in their audience’s minds for years to come.  However, not everyone can attend…

Beautify GitHub Profile

Exploring the Potential of the Metaverse: A New World Awaits
It wasn’t long ago that Nick Sypteras showed us how to make custom badges for a GitHub repo. Well, Reza Shakeri put Beautify GitHub Profile together and it’s a huuuuuuge…