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

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

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 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 CSS Guidelines 2.0.0
CSS Shorthand Syntax Considered an Anti-Pattern
Harry Roberts · 2016-12-12 · via CSS Wizardry

Written by on CSS Wizardry.

There’s a very small but surprisingly significant (and even more surprisingly frequent) issue I spot a lot in other peoples’ code, either when working directly with it, refactoring it, or auditing it: the use of shorthand syntax in CSS.

Typically we would view shorthand syntax as a benefit: fewer keystrokes, fewer lines of code, less data over the wire. Sounds great! However, it comes with a rather troublesome side effect: it often unsets other properties that we never intended to modify.

When we write something like:

.btn {
  background: red;
}

…we’re likely to get a red background colour applied to our button. But what we’re really saying is this:

.btn {
  background-image: initial;
  background-position-x: initial;
  background-position-y: initial;
  background-size: initial;
  background-repeat-x: initial;
  background-repeat-y: initial;
  background-attachment: initial;
  background-origin: initial;
  background-clip: initial;
  background-color: red;
}

Simply by using the shorter syntax, we have implicitly decided that we want no image to start top-left, repeat x and y, to scroll with the element, and so on…

Nearly every problem, bug, or regression in CSS at scale is happens because we did too much too soon, and further down the line we’re being affected by that. What this basically comes down to is the fact that, with CSS, you should only ever do as little as you need to do and nothing more.

Misusing shorthand syntax is a surefire way to do too much too soon, as thus it should be avoided. CSS is a lot harder to undo than it is to do.

In this example, what we really wanted to say was this:

.btn {
  background-color: red;
}

Here we’ve done exactly what we needed to do, and absolutely nothing else.


One such example I encountered on a client project earlier this year looked a little like this:

.base-class {
  background-position: 0 0;
  background-repeat: no-repeat;
}

.base-class--modifier {
  background: radial-gradient(...)
}

The developer had—understandably—used a gradient syntax generator to create their rather complex radial gradient, but they found that things weren’t rendering correctly at all. Their gradient syntax was correct, autoprefixer was working just fine, but for some reason their page looked really, really broken.

They couldn’t work out at all what was going wrong, to the extent that an issue was raised which simply said ‘Get Harry to look at the gradients’. Enough years of experience told me instinctively what to look for, and sure enough, I found it: hidden away in the Sass for generating gradients was the background shorthand.

This is a problem commonly found in gradient generators, so:

  1. go and update your own gradient generators right now;
  2. submit pull requests to projects that you know to be using shorthand syntax;
  3. double check your copy/pasted syntax that you get from online generators.

The background example is just one of many instances in which we shouldn’t be using shorthand. Another very common use-case is vertical centring using margin: 0 auto;:

.wrapper {
  margin: 0 auto;
}

The problem here is that in order to use shorthand to define auto only once—but use it on both the left and right—we had to make a decision about top and bottom as well. That was a decision we shouldn’t have made, because now we’re explicitly removing any top or bottom margins that may have been intentionally introduced elsewhere.

If all you want to do is centre a div, then don’t mention anything to do with its top and bottom edges. Favour the longhand version:

.wrapper {
  margin-right: auto;
  margin-left:  auto;
}

Run a quick grep over your CSS project for the string 0 auto right now and see what you find.

Exceptions

So far we’ve looked at the problem with inadvertently unsetting other properties, but there is a scenario in which shorthand would be okay. Take for example:

Here we aren’t inadvertently unsetting anything because we do want all four sides to carry 10px padding. Here, shorthand makes complete sense. Also:

.btn {
  padding: 12px 24px;
}

…and:

.foo {
  margin: 12px 17px 16px 10px;
}

Here—although I’d question the use of magic numbers—we are still explicitly setting all four sides, so, again, this use of shorthand would still be okay.

The key thing to remember is that shorthand is bad when it’s affecting properties that you don’t actually need to modify.


This kind of action—the inadvertent unsetting of other properties—is particularly problematic in modular and composable systems, where many different classes may be used in conjunction with one another to form more complex composites. Units of code that cannot be combined without collision or conflict are said to lack orthogonality, an important principle in the design of software.

  • Always favour the longhand. It might be more keystrokes, it might be more repetitive, it might be less DRY, but it’s more accurate.
  • Only write as much as you need and not a single bit more. Most CSS issues are caused by applying things too broadly; avoid it.