Creating visually appealing and interactive websites is a fundamental aspect of web development. The cornerstone of web design is CSS, which lets you create a website’s layout, typography, and design. CSS is intended to separate a website’s style from its contents.
As development requirements change and websites become complex, this complexity also shows up in your CSS files, making them difficult to manage. At this point, your code can start looking cluttered, dirty, unprofessional, and difficult to read. The benefit of having clean and decluttered CSS cannot be overemphasized, as it reduces load time, improves user experience, improves search engine optimization (SEO), and demonstrates a developer’s skill and understanding of system design.
But trying to clean up a large CSS codebase manually is time-consuming and tedious, and it can delay development. In this article, we will review the most popular tools for cleaning up your CSS. But before that, we’ll consider practices that result in cluttered or unused CSS.
Jump ahead:
- Practices that contribute to unused CSS
- How to manually remove unused CSS
- PurifyCSS
- UnCSS
- CleanCSS
- Tabifier
- PurgeCSS
Practices that contribute to unused CSS
Frameworks and libraries
Throughout the course of development, you have to use external libraries and frameworks. There are countless CSS frameworks available, with many different functionalities. Although these frameworks are beneficial for development, offering many patterns and components, they increase file size.
Some of these frameworks and libraries come as a bundle of predefined styles and CSS classes. In most cases, not all the classes and styles are used in development. Installing bundled frameworks without removing the unused styles and classes results in unnecessary code and increased file size.
Continuous changes
When there are many changes and iterations happening in development, developers may forget to clean up specific CSS code that may have become obsolete and unused. This, too, can result in unused CSS.
How to manually remove unused CSS
Manually removing CSS for a large website with many pages can be time-consuming, resulting in delayed development. In the next couple of steps, we’ll illustrate how to remove unused CSS using Chrome DevTools. We’ll assume that you’re using the Google Chrome browser. Let’s dive in!
On your webpage, right click on Inspect. Run the ctrl + shift + P
command, and you’ll be presented with the command interface shown below. From there, search for the Show Coverage option:
From the Show Coverage option, select a CSS file. A solid red line next to a CSS file means it didn’t execute, while those next to a solid green line did execute. Both red and green lines mean that some CSS code was executed. This test is page-specific, meaning you have to run this test across all pages to determine how many unused CSS files are in your project.
Let’s check out another method to spot unused CSS declarations. First, on your webpage, right click on Inspect. Then, click on the arrow, like in the image below:
Then, click on CSS Overview:
Next, click on Capture Overview, and you’ll be presented with the CSS overview page, as shown below:
On this page, navigate to the Unused declarations option, and you’ll be shown the page in the image below:
Removing unused CSS following the methods outlined above can be difficult when working on a large website. These methods aren’t the best option for large projects because they aren’t efficient and scalable. Now, let’s explore some tools that can help us efficiently remove and clean CSS in our projects.
PurifyCSS
PurifyCSS removes unused CSS code from our project. It can be used in the development environment with the support of build tools like Grunt, gulp.js, or webpack to remove unused CSS classes before the project goes live.
However, it can also be used online to remove unused CSS from websites developed with CMS, like WordPress using this purifyCSS Online tool. Check out the PurifyCSS GitHub repository to learn how to use it.
The following steps illustrate how to use PurifyCSS with code snippets. Before you start, you need to have Node.js installed:
- Create a project folder, and open this folder with VScode (code editor)
- Create two files in your project folder (
index.html
andstyle.css
) - On the code editor’s terminal, run the command below to install the PurifyCSS dependency at the root directory:
npm install purify-css
- In your
index.html
file, write the following basic code:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <h1>Hello, LogRocket!</h1> <p>This is a basic purify-css illustration.</p> </body> </html>
This gives us web contents to work with. Next, write the following simple style in your style.css
:
body { font-family: Arial, Helvetica, sans-serif; background-color: aliceblue; } h1 { color: blueviolet; } #div{ margin: auto; } .header{ background-color: blue; color: white; padding: 10px; text-align: center; } .btn { background-color: blue; color: white; }
When you run this, you should have a browser output as shown in the attached image:
The next step is to implement the purify-css
functionality. To do that, create a cssPurifier.js
file in the root directory of your project and add the code below:
const purify = require('purify-css'); const content = ['*.html']; const css = ['*.css']; const options = { output: 'purifyAndMinified.css', minify: true, info: true }; purify(content, css, options, function (purifiedAndMinifiedResult){ console.log(purifiedAndMinifiedResult); });
In the code above, we implemented the purify-css
functionality and specified the output file as purifyAndMinified.css
. To execute this script, run the command below on your terminal:
node cssPurifier
This file will contain the minified and purified CSS when we execute the cssPurifier.js
script.
UnCSS
UnCSS is a powerful tool designed to remove unused CSS from your project. It effectively analyzes your CSS codebase and identifies styles not used on your webpages. However, there are some considerations and limitations to keep in mind when using UnCSS. For example, this tool is unable to directly process non-HTML pages, like templates and PHP scripts.
To use UnCSS on these pages, you need to create example HTML pages that represent the output of your templates or scripts. These generated HTML files can then be used as input for UnCSS.
Alternatively, you can set up a local development server and direct UnCSS to that server to analyze the live website. It’s important to note that UnCSS can only process the CSS that is injected by JavaScript during page load. It does not handle JavaScript that relies on user input or interactions, like button presses.
If your JavaScript dynamically adds classes or modifies styles based on user actions, you will need to use the ignore
option in UnCSS to retain those specific classes or styles. Furthermore, you can integrate UnCSS with other JavaScript build tools, like Grunt, Broccoli, or Gulp. This allows you to incorporate UnCSS into your existing development workflow and automate removing unused CSS.
It’s worth mentioning that UnCSS supports both local file paths and URLs. This means you can provide file paths using glob patterns to process local CSS files. Additionally, you have the flexibility to supply URLs, enabling UnCSS to analyze live websites or remote CSS resources. Check out this GitHub repository to start using UnCSS.
Here is an example code snippet that illustrates how to use UnCSS:
const unCss = require('uncss'); const files = ['index.html']; const options = { stylesheets: ['style.css'] } unCss(files, options, (error, output) => { console.log(output); })
Executing this code should print all the CSS used in the project on your terminal. The image below shows all the CSS components used in our sample project:
CleanCSS
CleanCSS is an efficient tool to improve and optimize CSS, Node.js, or any modern web browser. It offers various features such as minification, optimization, and compatibility. It helps reduce file size, improve performance, and enhance code readability.
Whether you have a small CSS file or a large stylesheet, CleanCSS can streamline your code for optimal usage. This repository illustrates how to use CleanCSS in your Node.js projects. The sample code below illustrates how to use CleanCSS to minify a CSS file:
const CleanCSS = require('clean-css'); const cssContent = ["style.css"] const minifiedCSS = new CleanCSS().minify(cssContent).styles; console.log(minifiedCSS);
Tabifier
Tabifier is a simple online tool that helps to optimize code. It supports HTML, CSS, and C-style codes, which are code structures where code blocks have starting and ending curly braces, and semicolons end statements:
To use Tabifier, simply paste the CSS into the input box and hit the Tabify button.
PurgeCSS
PurgeCSS is a powerful tool used to remove unused CSS from your project. It analyzes your contents and CSS files to identify CSS selectors that are not being used. It also removes unused CSS from your code, thereby resulting in smaller and optimized CSS files.
PurgeCSS is beneficial when working with a large CSS library that contains an extensive stylesheet. To learn more about PurgeCSS and how to get started, check out this comprehensive guide.
Conclusion
In this article, we considered the importance of decluttering your CSS files. We learned how to remove unused CSS from our project using Chrome DevTools as well as other popular tools like PurifyCSS, UnCSS, CleanCSS, Tabifier, and PurgeCSS.
Is your frontend hogging your users' CPU?
As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.
Modernize how you debug web and mobile apps — Start monitoring for free.