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

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

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 Cyclomatic Complexity: Logic in CSS 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
Shoot to kill; CSS selector intent
Harry Roberts · 2012-07-17 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. It’s all about the key selector…
  2. Real-life example
  3. Exceptions
  4. Final word

One type of CSS in particular makes me cringe every time I see it; poor selector intent. Poor selector intent means carpet bombed selectors whose key selector has way too broad a reach; a selector like .header ul{} as opposed to one like .main-nav{}; .widget h2{} instead of .widget-title; article > p:first-child{} as opposed to .intro{}. Selectors whose intent isn’t specific enough.

It’s worth noting that selector intent is something I completely made up at some point today; if you think there’s a better name then please let me know!

Let’s take a closer look at the .header ul{} example. Let’s imagine that ul is indeed the main navigation for our website. It lives in the header, as you might expect, and is currently the only ul in there; .header ul{} is fine, right? Not really. I mean sure, it might work, but it’s not very good. It’s not very future proof and certainly not explicit enough. As soon as we add another ul to that header it will adopt the styling of our main nav and the the chances are we won’t want it to. This means we either have to refactor a lot of code or undo a lot of styling on subsequent uls in that .header to remove the effects of the far reaching selector.

Your selector’s intent must match that of your reason for styling something; ask yourself ‘am I selecting this because it’s a ul inside of .header or because it is my site’s main nav?’. The answer to this question will determine your selector.

It’s all about the key selector…

What determines the impact of a selector is its key selector. The key selector is a very important thing in the world of CSS as browsers read selectors right to left. This means the key selector is the last one before the opening {, for example:

.header ul      { /* ‘ul’ is the key selector */ }
.ul li a        { /* ‘a’ is the key selector */ }
p:last-child    { /* ‘:last-child’ is the key selector */ }

As I discuss in Writing efficient CSS selectors, the key selector plays a big part in CSS efficiency, so it’s worth bearing that in mind, but where selector intent is concerned this is basically the place you need to be looking to see how far reaching your selector is. html > body > section.content > article span{} is a ridiculously convoluted and terrible selector that no one anywhere would ever write (right?) but despite how specific and disastrously over the top it is, its key selector (span) is still very, very broad. It doesn’t matter so much what comes before your key selector, it’s only the key that really matters.

As a general rule you should try and avoid any key selector that is a type selector (basically an element, like ul or span or whatever) or a base object (e.g. .nav or .media). Just because something is the only .media object in your content area it doesn’t mean it always will be.

Let’s keep looking at the .header ul{} example. Let’s assume our markup is thus, as we’re using the nav abstraction:

<div class=header>

    <ul class=nav>
        [links]
    </ul>

</div>

We could select this in one of several ways:

.header ul{
    [main nav styles]
}

This is bad because as soon as we add any other ul to our header it will look like our main nav. This is dangerous but thankfully easily avoidable.

Secondly we could use:

.header .nav{
    [main nav styles]
}

This is marginally better than the .header ul example, but barely so. We can now safely add another ul without risk, but we can’t add anything else with a .nav class; that means adding sub-navs or breadcrumbs will be a nightmare!

Finally, our best solution would be to add a second class to the ul; a class of .main-nav:

<div class=header>

    <ul class="nav main-nav">
        [links]
    </ul>

</div>

.main-nav{
    [main nav styles]
}

This is good selector intent; we are selecting this element now for exactly the right reasons, not coincidental/circumstantial ones. Now we can add as many more uls and .navs to that .header and the scope of our main nav styles will never reach anything else. We’re no longer carpet bombing!

Keep your key selector as explicit and specific as you possibly can, preferring for it to be a class over anything else. Applying specific styling through a vague selector is dangerous. A generic selector should always carry generic styling and if you want to target something in particular you should perhaps add a class to it. Specific intent requires a specific selector.

Real-life example

A really good example of where I messed up on this myself is on a project I did at Sky; I had a selector which was simply #content table{}. (Eww, I even used an ID!!!) This is a troublesome selector for three reasons; firstly it uses an ID which is a big no, secondly it has a lot higher specificity than it needs to and lastly—and most importantly—it has a poor selector intent. I wasn’t wanting to style these tables because they were in #content, that was just how the DOM landed so that’s how I chose to target them. Entirely my bad.

For the first few weeks this was fine but then all of a sudden we needed to add some tables inside #content that didn’t want to look anything like the previous ones. Uh oh. My previous selector was far too far reaching, I was now having to undo a blanket style I’d set on every table in the #content div. If I’d had a better selector intent then instead of:

#content table{
    [foo styles]
}
#content .bar{
    [undoing foo styles]
    [bar styles]
}

I should/would have had:

.foo{
    [foo styles]
}
.bar{
    [bar styles]
}

And a lot less headaches. By thinking ahead and having a lot more considered selector intent then I would have had a much easier time…

Exceptions

Of course there are always exceptions. It’s perfectly reasonable to have selectors like .main-nav > li where your key selector is a type selector. It also makes perfect sense to target every a inside something like this:

html{
    color:#333;
    background-color:#fff;
}

/* Inverted colour scheme for promotional items. */
.promo{
    color:#fff;
    background-color:#333;
}
    .promo a{
        color:#fff;
        text-decoration:underline;
    }

That is a reasonably sensible far-reaching selector where it does make sense to style every a in a pretty carpet bombed manner.

Final word

In general, instead of carpet bombing your elements, shoot to kill; target them specifically and explicitly. Make sure your selector intent is accurate and targeted.

Think more carefully about why you want to target something and pick a more explicit and sensible selector; refine your selector intent. Do you mean:

or do you really mean:

Do you want:

or do you really want:

Is it wise to select:

or would a safer bet be:

Consider your CSS selectors’ intent; are you being specific enough? Are your selectors matching things for the right reasons, or is it just happy circumstance? Shoot to kill. Be a CSS sniper, not a CSS carpet bomber.

Incidentally, opting to switch out a longer selector like .header ul for something like .main-nav will also help reduce specificity and increase selector efficiency; win-win-win!

It is also worth noting that Jonathan Snook wrote something similar called the depth of applicability