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

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

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 open/closed principle applied to CSS
Harry Roberts · 2012-06-22 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Why you should never modify a base object
  2. When to extend
  3. Final word

A question that often gets asked of OOCSS is What happens when an object changes?. That is to say, if you have a basic object that underpins a dozen different components, what happens when changing that object will favourably impact one component, but negatively impact the other 11? With so much abstracted and shared CSS, simple changes to a base object can have massive ramifications across whole projects; how do you deal with that?

Well, the short answer is never change your base abstractions.

N.B. This article will require an understanding of the principles of OOCSS.

One way of dealing with objects in an OO language is the open/closed principle, which states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

By sticking to this we know that our base objects themselves will never change; they are closed for modification. If we want to alter their effects in some way, we extend them.

Why you should never modify a base object

The key to writing good OOCSS is keeping your base objects super simple. As simple as you can get. The nav abstraction literally just throws a list into horizontal mode; the island object only boxes off content; the media object only places image-like and text-like content side-by-side. This ties in very nicely to the single responsibility principle applied to CSS.

By making your base objects this simple, your choices become boolean; you use the object or you don’t. The object is either entirely suitable as a basis, or entirely _un_suitable.

As soon as you make the mistake of making your base objects too specific (for example, if your nav abstraction also adds padding to links) you might find that object is not entirely suited to another job for which it is almost perfect. You might find that in order to use the object you have to undo stuff in it.

A prime example of this is a mistake I made on faavorite. I made the island object carry cosmetics: instead of merely boxing off content I (foolishly) gave it a background, border and shadow style. This means that if I ever want to use the island for any different purposes, I have to undo that. Here I messed up, and made an object too specific, so I now have to decide whether it’s worth unsetting these properties in order to reuse .island, or is it better to just make something new? I removed my own boolean choice by not keeping my base simple enough.

So, if you abstract sensibly you should find that you rarely need to change a base object, you should only ever need to extend it. Extending will add styles only in specific cases, making modifications to a base object is a bad idea.

After sensible and considered abstraction you should find that base objects never need changing, you just use them or stop using them.

For example, let’s imagine you have the media object used as a base across ten different components. One of the components is a user’s avatar with their username to the right of it, another is an album listing with the album art to the left and track list to the right. The others… we won’t concern ourselves with those. You might have markup like this:

<a href="http://twitter.com/csswizardry" class="media  profile-link">
    <img src="avatar.jpg" alt="" class="media__img">
    <span class="media__body">@csswizardry</span>
</a>

<div class="media  album">

    <img src="/img/products/themirrorconspiracy.jpg" alt="" class="media__img">

    <div class="media__body">
        <h2>Thievery Corporation &ndash; The Mirror Conspiracy</h2>
        <ol>
            <li>Treasures</li>
            <li>Le Monde</li>
            <li>Indra</li>
            <li>Lebanese Blonde</li>
            <li>Focus on Sight</li>
            <li>Air Batucada</li>
            <li>Só com você</li>
            <li>Samba Tranquille</li>
            <li>Shadows of Ourselves</li>
            <li>The Hong Kong Triad</li>
            <li>Illumination</li>
            <li>The Mirror Conspiracy</li>
            <li>Tomorrow</li>
            <li>Bario Alto</li>
            <li>Guide for I and I</li>
        </ol>
    </div>
</div>

There we have two totally different pieces of content sharing the same base object, which is great!

However, let’s say you decide you want to change the display of albums on your site, you now want to have the album art full-width with the track listing below it—no longer side-by-side as the media object is.

A lot of people here would argue that using an abstraction ties you to a permanent visual style; and they would be correct! That’s the point! You can no longer use the media object here, you have to change your markup. This isn’t a problem with the abstraction, it’s a problem with its implementation.

Instead of trying to use just CSS for force the media object to display differently in this case, we stop using the media object altogether. This abstraction is no longer suitable. We open up the include that houses the markup that handles albums and we get rid of some markup; not everything can or should be done through CSS alone. We hit our boolean; do we use the abstraction or not? In this case, not.

When to extend

So above we discussed when to stop using abstractions, but what about when we legitimately need to extend them?

Let’s take another example using the media object again. Here we have an amazingly simple abstraction that places image-like content alongside textual content:

<a href="http://twitter.com/csswizardry" class="media">
    <img src="avatar.jpg" alt="" class="media__img">
    <span class="media__body">@csswizardry</span>
</a>


.media {
    display: block;
}

    .media__img {
        float: left;
        margin-right: 10px;
    }

        .media__img > img {
            display: block;
        }

    .media__body {
        overflow: hidden;
    }

        .media__body > :last-child {
            margin-bottom: 0;
        }

In this we see that there will be a 10px margin between the image and the text-content to the right. By and large this is fine, but let’s go back to our album listing example again and imagine we are still using the media object. 10px here just seems a little too cramped so what we do is extend the media object for cases where we use it for album listings, thus:

<div class="media  album">
    <img src="/img/products/themirrorconspiracy.jpg" alt="" class="media__img  album-art">
    <div class="media__body">
        ...
    </div>
</div>


.media {
    display: block;
}

    .media__img {
        float: left;
        margin-right: 10px;
    }

    /* Increase spacing if image is an album cover. */
    .album-art {
        margin-right: 20px;
    }

    ...

Here we can see how the base object remains intact but we extend it with a more specific use-case to modify its appearance. No other uses of the media object will be effected, only ones we explicitly flagged as being .album-art.

Here we make changes via extension, leaving our base—and every other instance of it—completely untouched.

Final word

If you’re using OOCSS you need to be aware that using an object is fairly boolean. You need to understand the open/closed principle and that once you’ve written an abstraction you’re committed to it (unless you fancy a large refactoring job). With this in mind avoid abstracting too early and abstract very carefully. Needing to modify an object is a big warning sign.

If you find you’re having to undo or—even worse—change base objects, you need to stop and consider where things went wrong. If an abstraction no longer becomes suitable that’s cool; we’re allowed to touch markup so just stop using it in your HTML. If you’re finding you only ever need to peg classes onto things to extend their appearance then you’re doing it right!

Do not modify your abstractions; needing to do so is a bad sign. If you need to alter things then extend them.

When working with OOCSS always keep in the back of your mind that objects are open to extension but closed to modification. This will force you to write your base objects as stripped back, abstract and reusable as possible. Modify their appearance only by extension (that is to say, by adding more classes).