UnCSS: Remove Unused CSS
UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS, ensuring your final stylesheets are as lean as possible.
This is essential for modern web development, as smaller stylesheets lead to faster page loads, improved rendering times, and a better user experience.
Key Features
- Unused Style Removal: The core functionality of UnCSS is to parse your HTML files and stylesheets, and intelligently determine which CSS rules are not being used.
- JavaScript-Injected Styles: UnCSS uses a headless browser environment (
jsdom
) to execute JavaScript on your pages, so it can correctly identify styles that are added dynamically on page load. - Multi-File Support: You can run UnCSS across any number of HTML and CSS files, making it suitable for projects of any size.
- Flexible Integration: UnCSS can be used as a command-line tool, a Node.js module, or a PostCSS plugin, fitting seamlessly into your existing development workflow.
- Highly Configurable: With a rich set of options, you can customize how UnCSS processes your files, including ignoring specific selectors, handling different media queries, and more.
How It Works
UnCSS follows a straightforward process to remove unused rules:
- Load & Execute: The HTML files are loaded into
jsdom
, a JavaScript implementation of the DOM. Any scripts that run on page load are executed. - Parse Stylesheets: All linked and provided stylesheets are parsed using
PostCSS
to create a structured representation of the CSS rules. - Filter Selectors: UnCSS then queries the
jsdom
instance for each selector found in the stylesheets. If a selector doesn't match any elements in the DOM, it is marked as unused. - Generate Clean CSS: Finally, the unused CSS rules are removed, and the remaining, clean CSS is generated as the output.
For a more in-depth explanation, see the How It Works guide.