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

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers 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 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
The single responsibility principle applied to CSS
Harry Roberts · 2012-04-29 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. When to use it?
    1. But!

Having just spoken at the Front-Trends conference in Warsaw, I’ve decided to expand on something which my talk mentioned a lot: classes.

My talk covered how to build big, scalable front-ends and one of the key factors involved in doing so is sensible and generous use of abstracted classes. One thing that really helps you achieve this is the application of the single responsibility principle, a method used mainly in OO programming.

Loosely, the single responsibility principle states that every module or chunk of code (a function etc) should do one job well and one job only. The benefits of this are mainly in the way of maintainability and extensibility.

If we don’t adhere to the SRP then we are likely to end up with code which does more than it should, this means that altering one part of that code could negatively impact a seemingly unrelated part of the same snippet. It also makes our code a lot less flexible in that we find our code is trying to do too much; it is too specific in its job to be portable and reusable. Abstracting chunks of functionality into several responsibilities means we can reuse a lot more of our code and recombine it over and over with other similarly abstracted chunks.

The Wikipedia article makes a much better job of explaining than I can so I would recommend giving that a quick read (it’s only short).

Also, you will find that a lot of us do this already, and perhaps without even realising. A class of .wrapper is a good example of the SRP at play; by having a single, reusable class whose sole job it is to group content we make our code a lot easier to work with. We don’t need to apply lots of widths to lots of elements; we use one extra div and delegate the width-constraining responsibility to that.

We do this because it makes sense, but we don’t do it often enough; if we start actually thinking like this all the time we find we can vastly improve our code…

The SRP is normally applied in programming circles but I have definitely found it is incredibly useful when making lean, scalable front-ends. Here’s a quick example of un-abstracted code that doesn’t follow the SRP:

<a href="/product" class="promo">Buy now!</a>


.promo {
    display: block;
    padding: 20px;
    margin-bottom: 20px;
    background-color: #09f;
    color: #fff;
    text-shadow: 0 0 1px rgba(0,0,0,0.25);
    border-radius: 4px;
}

Here we have a class for a promotional box of content. Here we are doing two things—we are defining box model and structure and we are defining cosmetics (colouring etc).

We can refactor this code to adhere to the SRP by splitting those two chunks of functionality into two classes:

<a href="product" class="island  promo">Buy now!</a>


.island {
    display: block;
    padding: 20px;
    margin-bottom: 20px;
}

.promo {
    background-color: #09f;
    color: #fff;
    text-shadow: 0 0 1px rgba(0,0,0,0.25);
    border-radius: 4px;
}

We now have two classes which each carry a single responsibility; .island boxes off content and .promo applies our promotional styling. This now means that we can do things like this, which previously we couldn’t:

<h2>Buy now with promo code: <span class="promo">0MG4WE50ME</span></h2>

Previously we couldn’t have managed this as the .promo class also carried a lot of box model; by abstracting our code into single responsibilities we can pick and choose what we want to use and where a lot more easily.

We can take this much, much further; now we also have a generic class for boxing off content! Where we once might have had:

<div id="header">
</div>

<div id="content">
</div>

<div id="sub-content">
</div>

<div id="footer">
</div>


#header {
    padding: 20px;
    margin-bottom: 20px;
    background-color: #121416;
    color: #fff;
}

#content {
    width: 640px;
    float: left;
    margin-right: 20px;
    padding: 20px;
    margin-bottom: 20px;
}

#sub-content {
    width: 280px;
    float: left;
    padding: 20px;
    margin-bottom: 20px;
}

#footer {
    padding: 20px;
    margin-bottom: 20px;
    background-color: #e4e4e4;
    color: #333;
}

We would now have:

<div class="island  header">
</div>

<div class="island  content">

    <h2>Buy now with promo code <span class=<mark>promo</mark>>0MG4WE50ME</span></h2>

</div>

<div class="island  sub-content">

    <a href="product" class="island  promo">Buy now!</a>

</div>

<div class="island  footer">
</div>


.island {
    display: block;
    padding: 20px;
    margin-bottom: 20px;
}

.promo {
    background-color: #09f;
    color: #fff;
    text-shadow: 0 0 1px rgba(0,0,0,0.25);
    border-radius: 4px;
}

.header {
    background-color: #121416;
    color: #fff;
}

.content {
    width: 640px;
    float: left;
    margin-right: 20px;
}

.sub-content {
    width: 280px;
    float: left;
}

.footer {
    background-color: #e4e4e4;
    color: #333;
}

Because we abstracted our code out we now have a really portable class for simply boxing off content!

N.B. You should also abstract your layout to a grid system, taking the floats and widths off the page components and leaving that responsibility to the grids.

Just some of the benefits of working like this are:

  1. Your CSS is a lot DRYer.
  2. You can make far-reaching changes to your designs by simply modifying a base abstraction only once.
  3. You can make safer changes because you know that when editing a class you are only ever altering one responsibility.
  4. You can combine responsibilities to make a variety of components from a lot of abstracted classes.

Now we can take it further still.

Because we have a nice .island class whose sole responsibility is to box off content then we can now do things like this:

<div class="island  content">
    ...
    <form>
        <p class="island  error">Please provide your name.</p>
        ...
        <label class="error">Name:</label>
        ...
    </form>
    ...
</div>


.island {
    display: block;
    padding: 20px;
    margin-bottom: 20px;
}

.error {
    background-color: #fce0e2;
    color: #c00;
}
.error.island {
    border: 5px solid #c00;
    border-radius: 4px;
}

Because we have our chunks of CSS only working on one thing at a time then we can reuse and combine useful things time and time again. I’ve written about this before: Class based builds are like eating at Subway.

When to use it?

There’s no definite answer to questions like this but as a general rule try and stick to the SRP any time you think that subsets of a style rule could be split out into more manageable and reusable abstractions. Any time you are coding a potentially repeatable design pattern then try and split it out as per the single responsibility principle.

But!

It’s important not to take this too far; classes should be abstracted but ideally not presentational. Classes like .round-corners for the sake of SRP are really not all that advisable.