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

推荐订阅源

博客园 - 【当耐特】
WordPress大学
WordPress大学
T
The Exploit Database - CXSecurity.com
博客园_首页
MyScale Blog
MyScale Blog
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
F
Full Disclosure
V
V2EX
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News: Ask HN
Hacker News: Ask HN
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Martin Fowler
Martin Fowler
PCI Perspectives
PCI Perspectives
S
Security @ Cisco Blogs
Recorded Future
Recorded Future
Help Net Security
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
Microsoft Azure Blog
Microsoft Azure Blog
K
Kaspersky official blog
G
GRAHAM CLULEY
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
CERT Recently Published Vulnerability Notes
U
Unit 42
T
Tor Project blog
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
MongoDB | Blog
MongoDB | Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

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
Writing DRYer vanilla CSS
Harry Roberts · 2013-07-05 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Featured case study: NHS

When dealing with code, we often strive to make things DRY. DRY code usually means two things:

  1. Less actual code, meaning smaller file sizes, less for the user to have to download, more efficient code, etc.
  2. Less to have to maintain; not repeating yourself means that you can make fewer changes to your codebase.

Simple, obvious stuff, I’m sure you’ll agree.

When we talk about DRY CSS, we usually mention things like OOCSS, abstractions, variables in Sass, etc. However, there is a way of DRYing out CSS at a much more fundamental and far smaller level. This is just going to be a short tip-style post covering how and where you can spot the chance to DRY things out in your regular/‘vanilla’ CSS.

When DRYing out code for maintainability, it is preferable to DRY out the things most likely to change, even if that does result in more code at the end. Take the following example:

.foo {
    border-top: 1px solid red;
    border-bottom: 1px solid blue;
}

This is a fairly innocuous looking snippet of CSS; we simply want to pop different coloured borders on the top and bottom of a div. However, we have some repetition here; we have the words 1px and solid twice. If you ever want to change the border style on this div, you have to change two words. Not a big deal, right? But it’s still literally twice as many (i.e. double) what you should need to change. Extrapolate this example across an entire site then all of a sudden you have 200% as much code as you need in these cases.

Let’s rewrite this CSS a little more verbosely, but a lot DRYer (in terms of code that is likely to change):

.foo {
    border-width: 1px 0;
    border-style: solid;
    border-top-color: red;
    border-bottom-color: blue;
}

Or even:

.foo {
    border: 0 solid red;
    border-width: 1px 0;
    border-bottom-color: blue;
}

Far more CSS, but far less repetition! If we want to change the width of the borders we can do so in one go; if we want to change the style of border then we can make that change once. Even though there is more code, there is less repetition of the parts that are most likely to change. It doesn’t matter that the word border is written four times as you could never really change that, only delete it.

Featured case study: NHS

How I helped the NHS rapidly build a brand new product.

Read case study…

Another decent example, using borders again:

.bar {
    border-top: 1px solid #ccc;
}

    .bar > li {
        border-bottom: 1px solid #ccc;
    }

Here we are simply applying a border to the top of a list and the bottom of all its lis, to create a bookended border effect. Again, though, not too DRY. Let’s rewrite it:

.bar,
    .bar > li {
        border: 0 solid #ccc;
    }

.bar {
    border-top-width: 1px;
}

    .bar > li {
        border-bottom-width: 1px;
    }

Once again, more code, but far DRYer. We can change the colour and style of both the list’s and its li’s borders in one go.

Another example (and these really are only examples):

.page--home {
    background: url(home.jpg) center center no-repeat;
}

.page--about {
    background: url(about.jpg) center center no-repeat;
}

.page--work {
    background: url(work.jpg) center center no-repeat;
}

.page--contact {
    background: url(contact.jpg) center center no-repeat;
}

Again, a lot of repetition. Not in absolute terms, but certainly more than is necessary. We can DRY that out by rewriting it as:

.page {
    background-position: center center;
    background-repeat: no-repeat;
}

.page--home     { background-image: url(home.jpg); }
.page--about    { background-image: url(about.jpg); }
.page--work     { background-image: url(work.jpg); }
.page--contact  { background-image: url(contact.jpg) }

Abstracting out the repeated parts and avoiding using shorthand means writing a few more lines of code, but massively trims down the amount of repetition.

All of these examples are pretty tame, but they should hopefully serve as a decent springboard from which you can extrapolate and extend the idea of rewriting your code to avoid repetition; more specifically, the repetition of the parts of your CSS that are most likely to change.