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

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

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 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
Mixins Better for Performance
Harry Roberts · 2016-02-25 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. The Experiment
  2. Making Things More Realistic
  3. Mixins Are Better for Performance

When it comes to preprocessors, one of the most frequent questions I’m asked is Mixins or @extend? I’ve always been quite vocal about this topic, and I firmly believe you should avoid @extend for a number of reasons:

  1. It alters your source order, which is always risky in CSS.
  2. It creates awkward groupings in your code, putting unrelated selectors together.
  3. It is very greedy, @extending every instance of a given subject, not just the one you actually wanted..
  4. It can get really out of control, really fast.

@extend is now widely considered an anti-pattern, so its usage is thankfully fading out, but we’re not quite there yet.

I was workshopping with a client yesterday and was asked about the mixin vs. @extend situation, to which I gave my usual answer of Don’t use @extend, ever!, and in return I was asked But isn’t @extend better for performance? It generates less code.

It is true that @extend (when used correctly) will produce less CSS, but my answer was a firm no: mixins are better for performance.

I answered the question with quite some confidence, despite having never actually done any tests. The reason for my confidence was a pretty solid theory that I had:

Because gzip favours repetition, surely we’ll get a better compression ratio if we share the exact same declarations, say, 1000 times, than if we shared 1000 unique classes twice.

Y’see, when people talk about the performance of mixins, they’re usually thinking about filesize on the filesystem. But because we have gzip enabled (you do have gzip enabled, right?), we should be thinking about filesize over the network.

My thinking was that once we’ve gzipped our CSS, files with greater repetition of identical strings will end up being smaller than files whose repetition is less frequent, regardless of the size of the files on the filesystem. I posited that a bigger file would end up smaller after gzip if that extra filesize was comprised of repeated string.

I got back to my hotel room and decided to put my theory to the test.

The Experiment

Here’s what I did.

  1. I created two CSS files.
  2. Each file had 1000 unique classes, generated using Sass:

    @for $i from 1 through 1000 {
      .#{unique-id()}-#{$i} {
        ...
      }
    }
    
  3. I gave each class a unique declaration, simply reusing the same random string that formed the name itself by using the parent selector, and I put some nonsense strings either side of that:

    @for $i from 1 through 1000 {
      .#{unique-id()}-#{$i} {
        content: "ibf#{&}jaslbw";
      }
    }
    
  4. I then chose three simple declarations that would remain the same across all 1000 classes:

    color: red;
    font-weight: bold;
    line-height: 2;
    
  5. In one file, I shared these declarations via a mixin:

    @mixin foo {
      color: red;
      font-weight: bold;
      line-height: 2;
    }
    
    .#{unique-id()}-#{$i} {
      @include foo;
      content: "ibf#{&}jaslbw";
    }
    
  6. And in the other I shared them via @extend:

    %foo {
      color: red;
      font-weight: bold;
      line-height: 2;
    }
    
    .#{unique-id()}-#{$i} {
      @extend %foo;
      content: "ibf#{&}jaslbw";
    }
    

All of these test files (and more) are available on GitHub.

This left me with two files made up of totally unique classes and 1000 unique declarations, and with three identical declarations shared in two different ways.

The filesizes of these should not surprise you in the slightest:

  • mixin.css came in at 108K.
  • extend.css came in at 72K.
  • This gives a difference in filesize of 36K.
  • Using mixins was 150% larger than using @extend.

This is exactly what I expected—mixins do produce more CSS than @extend does.

But! We have to remember that we should not be worried about filesize on the filesystem—we only care about the sizes of our gzipped files.

I minified and gzipped the two files and got the results I expected:

  • mixin.css came in at 12K.
  • extend.css came in at 18K.
  • This gives a difference in filesize of 6K.
  • Using mixins was 33.333% smaller than using @extend.

Amazing! We’ve gone from mixins being 1.5× larger than using @extend, to mixins being 0.3× smaller than using @extend. My theory seems correct!

Making Things More Realistic

I do feel that the test files were pretty fair—creating unique strings for class names was designed to hinder compression, so that we could more accurately test the effects of gzip on our actual subject: the shared declarations.

That said, the test files were pretty unrealistic, so I decided to make things a little more reasonable.

I grabbed the compiled CSS from an existing project, made two copies of it, and I @imported each of my test files into each project respectively. This meant that my test files were surrounded by some 1794 lines of actual, realistic CSS.

I compiled each new test file and these were the results:

  • mixin.css came in at 16K.
  • extend.css came in at 22K.
  • This gives a difference in filesize of 6K.
  • Using mixins was 27% smaller than using @extend.

The absolute numbers seem trivial (a mere 6K), but in relative terms, we can achieve a 27% saving over the wire simply by opting to use mixins to repeat declarations over and over, as opposed to using @extend to repeat a handful of selectors.

Mixins Are Better for Performance

My tests showed pretty conclusively that mixins end up being better for network performance than using @extend. The way gzip works means that we get better savings even when our uncompresssed files are substantially larger.

This means that the performance argument for @extend is non-existent. As well as being bad for your CSS, @extend is bad for performance. Please stop using it.