惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

CSS Wizardry

Front-End’s Missing Metric: The TBT Window Meet Your Users Where They Are with Obs.js Better Browser Caching with No-Vary-Search font-family Doesn’t Fall Back the Way You Think What Is CSS Containment and How Can I Use It? When All You Can Do Is All or Nothing, Do Nothing Obs.js: Context-Aware Web Performance for Everyone Low- and Mid-Tier Mobile for the Real World (2025) The Fastest Site in the Tour de France Making Sense of the Performance Extensibility API Why Do We Have a Cache-Control Request Header? HTML Is Not a Programming Language… Build for the Web, Build on the Web, Build with the Web Licensing Code on CSS Wizardry A Layered Approach to Speculation Rules Designing (and Evolving) a New Web Performance Score Core Web Vitals Colours The Ultimate Contract Templates for Tech Consultants: Protect Your Business and Get Paid Optimising for High Latency Environments Cache Grab: How Much Are You Leaving on the Table? blocking=render: Why would you do that?! Correctly Configure (Pre) Connections The Three Cs: 🤝 Concatenate, 🗜️ Compress, 🗳️ Cache What Is the Maximum max-age? How to Clear Cache and Cookies on a Customer’s Device The Ultimate Low-Quality Image Placeholder Technique Core Web Vitals for Search Engine Optimisation: What Do We Need to Know? The HTTP/1-liness of HTTP/2 In Defence of DOM­Content­Loaded Site-Speed Topography Remapped Why Not document.write()? Speeding Up Async Snippets Critical CSS? Not So Fast! Measure What You Impact, Not What You Influence Optimising Largest Contentful Paint Measuring Web Performance in Mobile Safari Site-Speed Topography Speed Up Google Fonts Real-World Effectiveness of Brotli Performance Budgets, Pragmatically Lazy Pre-Browsing with Prefetch Making Cloud.typography Fast(er) Time to First Byte: What It Is and How to Improve It Self-Host Your Static Assets Tips for Technical Interviews Cache-Control for Civilians Bandwidth or Latency: When to Optimise for Which ITCSS × Skillshare What If? CSS and Network Performance The Three Types of Performance Testing Getting to Know a Legacy Codebase Image Inconsistencies: How and When Browsers Download Images Identifying, Auditing, and Discussing Third Parties My Digital Music Setup Measuring the Hard-to-Measure Finding Dead CSS The Fallacies of Distributed Computing (Applied to Front-End Performance) Ten Years Old Relative Requirements Airplanes and Ashtrays Performance and Resilience: Stress-Testing Third Parties Refactoring Tunnels Little Things I Like to Do with Git Writing Tidy Code Configuring Git and Vim Base64 Encoding & Performance, Part 2: Gathering Data Base64 Encoding & Performance, Part 1: What’s Up with Base64? Code Smells in CSS Revisited Typography for Developers Moving CSS Wizardry onto HTTPS and HTTP/2 Ack for CSS Developers A New Year, a New Focus Preparing Vim for Apple’s Touch Bar Choosing the Correct Average CSS Shorthand Syntax Considered an Anti-Pattern CSS Wizardry Newsletter Nesting Your BEM? Improving Perceived Performance with Multiple Background Images Continue Normalising Your CSS Pure CSS Content Filter Pragmatic, Practical, and Progressive Theming with Custom Properties Refactoring CSS: The Three I’s Speaker’s Checklist: Before and After Your Talk Improving Your CSS with Parker The Importance of !important: Forcing Immutability in CSS Mixins Better for Performance Managing Typography on Large Apps White October Events Workshop Partnership BEMIT: Taking the BEM Naming Convention a Step Further Travelling Like You Want to, When You Have To Contextual Styling: UI Components, Nesting, and Implementation Detail Subtleties with Self-Chained Classes Immutable CSS Can CSS Be Too Modular? More Transparent UI Code with Namespaces When to use @extend; when to use a mixin The Specificity Graph CSS Wizardry Ltd.: Year 1 in review CSS Guidelines 2.0.0
Cyclomatic Complexity: Logic in CSS
Harry Roberts · 2015-04-26 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Cyclomatic Complexity

For the longest time, we’ve been saying that CSS doesn’t have logic. By that, we meant that there was no control flow or way of programmatically manipulating it. This inherent lack of logic has been used as an argument in favour of using preprocessors (to provide that missing feature), and as an argument against using preprocessors (CSS was never meant to have logic, so we shouldn’t go introducing it).

However, I recently hit upon a way of thinking that made me realise that CSS does include logic, and the fact that it’s rarely viewed as such is probably also why we end up with such poor CSS at all.

I found myself explaining compound selectors to a client as being made up of the subject—the thing we’re actually interested in—and its conditions. For example:

div.sidebar .login-box a.btn span {
}

In this compound selector, the subject is span, and the conditions are IF (inside .btn) AND IF (on a) AND IF (inside .login-box) AND IF (inside .sidebar) AND IF (on div).

That is to say, every component part of a selector is an if statement—something that needs to be satisfied (or not) before the selector will match.

This subtle shift in the way we look at how we write our selectors can have a huge impact on their quality. Would we really ever write (pseudo code):

@if exists(span) {

  @if is-inside(.btn) {

    @if is-on(a) {

      @if is-inside(.login-box) {

        @if is-inside(.sidebar) {

          @if is-on(div) {

            # Do this.

          }

        }

      }

    }

  }

}

Probably not. That seems so indirect and convoluted. We’d probably just do this:

@if exists(.btn-text) {

  # Do this.

}

Every time we nest or qualify a selector, we are adding another if statement to it. This in turn increases what is known as its Cyclomatic Complexity.

Cyclomatic Complexity

In software engineering, Cyclomatic Complexity is a metric which concerns itself with the number of ‘moving parts’ in a piece of code. These moving parts are usually points within some control flow (if, else, while, etc.), and the more of them we find, the greater our Cyclomatic Complexity. Naturally, we want to keep our Cyclomatic Complexity as low as possible, as greater complexity means that, among other things,

  • code is harder to reason about;
  • there are more potential points of failure;
  • code is harder to modify, maintain, or reuse;
  • you’re left with more outcomes and side effects to be aware of;
  • and code is more difficult to test.

Applied to CSS, we’re basically looking at the number of decisions a browser has to make before it can or cannot style something. The more if statements in our selectors, the greater the Cyclomatic Complexity that selector has. This means our selectors are more fragile, because they have a greater number of conditions that must be satisfied in order for them to work at all. It means our selectors are less explicit, because introducing if statements unnecessarily can lead to false positive matches. It makes our selectors far less reusable, because we’re making them jump through way, way more hoops than they need to.

So Instead of binding onto a span inside of a .btn (and so on) we would be far better off creating a new class of .btn-text to bind onto. This is far more direct, as well as being more terse and more robust (more @ifs lead to more brittle selectors that have a greater chance of breaking).

The trick is to write your selectors how the browser parses them: right to left. If your first question is is there a span? then your net is being cast far too wide. This is why you then have to qualify the span with so many conditionals: to narrow the selector’s reach. You need to start at the other end; write something unambiguous and explicit and forgo the conditions entirely.

Instead of your selectors casting a really wide net that catch way too much of the DOM—and then having to trim that catch down via conditions—it is far more succinct and robust to just catch much less of the DOM in the first place.

Cyclomatic Complexity is quite an advanced principle to try and apply to CSS, but if we look at it as just that—a principle—we can start to visualise and even measure the complexity in the ‘logic’ powering our selectors, and we can then begin making much better decisions based on it.

Some good rules of thumb:

  • Think of your selectors as mini programs: Every time you nest or qualify, you are adding an if statement; read these ifs out loud to yourself to try and keep your selectors sane.
  • Keep your Cyclomatic Complexity to a minimum: Use a tool like Parker to actually get metrics about your selectors’ mean Cyclomatic Complexity (Identifiers Per Selector).
  • If you don’t need the checks, don’t put them in there: Sometimes nesting in CSS is necessary, but most of the time it is not. Even the Inception Rule should not be trusted.
  • Start thinking about your selectors from the right first: Start with the bit you know you want and then write as little extra CSS as possible in order to get a correct match.
  • Brush up on Selector Intent: Make sure you’re writing the selectors you intend, not just the ones that happen to work.

Your selectors are the most fundamental aspect of your CSS architecture; make sure you’re writing sane and simple ones.