Course contentsShow
← Web Development
Lesson 1419 of 2,98225. Build Tools and BundlersFree lesson

Tree Shaking CSS

Removing unused CSS with tools like PurgeCSS and bundler integrations.

Tree Shaking CSS

You'll learn how to automatically remove unused CSS from your production bundles using specialized tools and bundler integrations.

The Problem with Unused Styles

Just like tree shaking removes unused JavaScript code, tree shaking CSS eliminates styles that aren't actually used in your application. CSS frameworks and libraries often ship with thousands of lines of code, but you might only use a fraction of them. That's like packing an entire wardrobe for a weekend trip—you're carrying unnecessary weight.

How CSS Tree Shaking Works

Unlike JavaScript, CSS doesn't have an explicit import/export system that bundlers can analyze. Instead, CSS tree shaking tools scan your HTML and JavaScript files to identify which class names, IDs, and selectors are actually referenced, then strip out everything else.

PurgeCSS is the most popular tool for this job. It works by:

  1. Analyzing your content files (HTML, JS, templates)
  2. Extracting all class names and selectors used
  3. Removing any CSS rules that don't match
  4. Outputting a much smaller stylesheet

Integration Patterns

Most modern bundlers support CSS tree shaking through plugins:

  • Vite can integrate PurgeCSS or use built-in CSS code splitting
  • Webpack uses plugins like purgecss-webpack-plugin
  • Tailwind CSS has PurgeCSS built directly into its configuration

You typically configure which files to scan and which patterns to preserve, especially for dynamically generated class names. The process runs during production builds, not development, so you keep full CSS available while coding.

Key Takeaway: Tree shaking CSS removes unused styles from your production bundles by scanning your markup and code for referenced selectors, dramatically reducing file sizes—especially when using large CSS frameworks.