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

推荐订阅源

L
Lohrmann on Cybersecurity
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
TaoSecurity Blog
TaoSecurity Blog
博客园_首页
Vercel News
Vercel News
Hugging Face - Blog
Hugging Face - Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Last Week in AI
Last Week in AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
The Exploit Database - CXSecurity.com
量子位
Project Zero
Project Zero
A
Arctic Wolf
小众软件
小众软件
NISL@THU
NISL@THU
C
CERT Recently Published Vulnerability Notes
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
P
Privacy & Cybersecurity Law Blog
Security Latest
Security Latest
B
Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
Schneier on Security
Schneier on Security
The Hacker News
The Hacker News
K
Kaspersky official blog
C
Check Point Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Webroot Blog
Webroot Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
人人都是产品经理
人人都是产品经理
AI
AI
Cisco Talos Blog
Cisco Talos Blog
MyScale Blog
MyScale Blog
Cloudbric
Cloudbric
B
Blog RSS Feed
S
Schneier on Security
P
Palo Alto Networks Blog

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 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
Immutable CSS
Harry Roberts · 2015-03-12 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Enforcing Immutability
  2. Working Immutably

In my recent article, More Transparent UI Code with Namespaces, I mentioned a number of times that certain classes cannot or should not be changed, bound onto, reassigned, or otherwise modified after their initial creation. We had phrases like:

Making modifications to these types of class could potentially have knock-on effects in a lot of other unrelated places. Tread carefully.

And:

It has a very specific role (often providing only one declaration) and should not be bound onto or changed.

As well as:

…we need to let others know that this class is less than ideal, and hopefully temporary (i.e. do not bind onto this).

Followed by:

Avoid modifying their styles.

With a bit of:

We do not want anyone trying to bind onto these in future selectors.

And then I said:

…do not bind onto, reuse or otherwise interface with it. […] [Hack classes] should not be relied upon or reused by other developers.

With this next:

…do not reuse or bind onto their classes.

And this:

A number of things I can reuse, but not bind onto or alter (Objects and Utilities).

And then this:

…but cannot be reused, modified, or moved.

Jeez. Wow. I guess I was really, really trying to drive a point home there. Basically that modifying, reassigning, or otherwise interfering with certain types of rule can be dangerous, and is therefore strictly prohibited.

The idea was to use pre-agreed namespaces in order to signal which rules these were; those namespaces were o- for Objects, u- for Utilities, and _ for Hacks.

We need to make sure we never touch these once they’ve been created, as to do so could have potentially terrible knock-on effects for other developers and/or other parts of the system. We need to remain confident that the use of these rules never comes with side effects.

Well, it turns out there’s already a name for things like this: Immutable Objects.

As with a lot of my work, I try to borrow paradigms from software engineering. Software Engineers have been solving these problems since long before I was even a twinkle in my father’s eye, so it’s probably going to be in my interests to see how they’d go about it.

It turns out that immutable objects are objects whose state cannot be modified after [they have been] created. That’s exactly what we’re aiming for with certain types of rule in our CSS! After we’ve created certain rulesets, they want to behave almost like constants: never changing, closed to modification, immutable.

From the Wikipedia page:

Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.

Immutable object—Wikipedia

Perfect! simpler to understand and offer higher security. This is exactly what the namespacing gives us: knowledge and, subsequently, security.

More gold from the Wikipedia page:

…if any user of a reference to a mutable object changes it, all other users of that reference will see the change. If this is not the intended effect, it can be difficult to notify the other users to have them respond correctly.

Heck yeah! This is exactly what we’re talking about with our CSS. If someone modifies a base Object or a global Utility, we’re going to propagate that change out everywhere, and we probably don’t want that.

It gets better:

In these situations, defensive copying of the entire object rather than the reference is usually an easy but costly solution.

Uh oh! Ever copied and pasted (or @extended) some declarations in order to reuse them under a safer selector? Duplicating things (or their references) in order to use them again with no side effects?

Enforcing Immutability

It’s all well and good knowing what immutability is, but we need to be able to enforce it. One potential (untested) approach would be to simply see if any class appears more than once in a project. For example:

.o-media {}

...

.c-footer .o-media {}

Here we’ve reassigned .o-media; it exists once, where it should do, but we’ve also got a modified version of it when it exists inside of .c-footer. This nesting introduces a caveat (.o-media when…) which in turn produces side effects.

Perhaps a Grunt task to find reassigned classes and show developers a warning:

WARNING: Immutable object `.o-media` has been reassigned on line 2214.

Or perhaps preprocessors could provide a specific type of selector that is immutable. We have placeholder classes that never get written out to the compiled CSS, and they use the % symbol in place of the period (.). How about something like:

Which would get compiled out to:

But would throw an error if we tried to do this:

.c-footer {

    ^o-media {}

}

For example:

error _components.footer.scss (Line 86: Cannot reassign immutable object: “^o-media”.)

Totally just thinking out loud there—there will be a number of reasons why this is impractical, I’m sure.

Working Immutably

Until we actually get ways of creating truly immutable objects in CSS, there are a number of rules and principles we can stick to:

Firstly, utilise and stick to our namespacing. Even though we can get around or break these rules, they’re a great start. If we make sure we signal these types of rule, at least we have a better chance of people modifying CSS safely.

The second thing we can do is make sure we strongly adhere to the Open/Closed Principle. Ensure that we never modify rules directly, and that we add new classes (using BEM) to extend changes forward. This ensures that we’re never going back and changing fundamental rules that underpin many other more complex bits of UI, meaning no regressions or side effects. Our immutable rules (Utilities, Objects, Hacks) remain immutable by never reassigning them and adding caveats.