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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

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
When using IDs can be a pain in the class...
Harry Roberts · 2011-09-12 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Reusability
  2. Wild card
    1. Remove IDs completely?
  3. Final word

N.B. Since authoring this article I have decided that a blanket ban is sensible. Save yourself many potential headaches and never use IDs in your CSS files.

There have been a few articles flying about lately which tell you never to use IDs in CSS selectors. I always get a little concerned when articles like this command rather than advise, they often neglect to take into account context and necessity. I’m going to try and offer up one decent reason here as to why IDs might trip you up unnecessarily (and how you can avoid the pitfalls).


ID selectors are fine, valid and perfect for styling unique parts of pages. They’re HTML/CSS basics, you can use one ID per page and style the relevant element with #the-id-you-chose.

IDs, as well as being non-reusable, carry quite a high specificity, take the following:

<p id="intro" class="excerpt">Lorem</p>

#intro{ color:blue; }
.excerpt{ color:green }
p{ color:red; }

Even though we define #intro first–thus expecting it to be overwritten by subsequent matching selectors–it still takes precedence over any other rules. This is the IDs heightened specificity, and this is where you can come unstuck…

Reusability

One argument against using IDs is that they can’t be reused, but to my mind this is a weak argument. The whole point of using an ID is that it’s unique; if you want to reuse something you’d use a class. Developers know this, developers aren’t stupid so to tell them not to use an ID because it’s not reusable is, in my opinion, quite patronising.

Also, some things just can’t be reused. Some designs would be wholly impossible to have, say, two content areas in. You couldn’t reuse that even if you wanted to.

Wild card

That is wild card meaning a person or thing whose influence is unpredictable or whose qualities are uncertain and not to be confused with the CSS wildcard selector (*{}).

One of the main and, in my opinion, most valid arguments against using IDs is that they can introduce specificity headaches where you want them least, and it can be a total nightmare fighting your way back out.

Using an ID in a selector instantly adds a specificity wild card (note, not wildcard), and you might not want this effect. It is, in a way, similar to !important; it is a trump card that will override nigh on all other types of selector. You probably don’t always want this.

The best way to illustrate this is with a specific example.

Let’s imagine you’re building a site and one of the requirements is to have a reusable Twitter widget that needs to be placable wherever the client chooses. Let’s for example say they want to kick things off with having the widget in the header and also in-page, at the bottom of an article. The Twitter widget’s styling must remain consistent.

So, let’s look at some example code.

Here we can see that we have a small specificity problem, the #header a rule has a lot higher specificity than .tweet a and therefore the links in the widget adopt the header’s (unreadable) colour. Remember that the Twitter widget’s styling must always remain the same so this is not ideal whatsoever.

We can work around this by adding a new selector to the .tweet a rule Or, even worse, we could add an !important to the relevant declaration. Shudder…

Now, you don’t need me to tell you that this is far from a nice solution, as soon as that widget gets put in the #footer we may well have to add yet another selector, which will prove a maintainability nightmare. This is not a very future-proof fix.

This is where using IDs can be a pain for you, where a specificity trump is introduced.

A better fix: add a class instead of (or as well as) the ID on that header div, thus: http://jsfiddle.net/csswizardry/gTZGq/3/

That now brings the specificity gap way down to, well, zero. Removing the ID means that you now don’t have to fight yourself out of a self-induced specificity war.

I did mention that you can add a class as well as the ID or remove the ID completely. It depends…

Remove IDs completely?

We’ve covered where IDs can trip us up and be but they serve a purpose other than style-hooks; they can be used as fragment identifiers for marking landmarks in the page.

I’m sure you’ve seen ‘Skip to navigation’ or ‘Jump to content’ links in pages, and these wouldn’t work without our IDs so we need to keep those in as well as adding our new class.

So, as is the case with most development conundrums, it’s all about context. You know your context better than I, or anyone else does, so don’t let anyone else tell you what to do. If you want to keep an ID for completeness or for fragment identifiers then do, it’s totally your call.

Final word

So yeah, IDs aren’t evil, they’re perfectly valid and a blanket ban on them is stupid. Use your own knowledge and context of the project to use the most suitable and sensible solution.

Don’t stop using IDs, just be aware of where they can cause you headaches and know where to sensibly circumvent them. Anyone telling you not to use them at all is not wrong, but they’re definitely not right…