How to Remove Unused CSS for Leaner CSS Files - KeyCDN (2024)

By Cody Arsenault

Updated on March 4, 2019

How to Remove Unused CSS for Leaner CSS Files - KeyCDN (1)

It's no secret that leaner websites run faster than bloated ones. Don't let unnecessary CSS weigh down your web projects; use the tools and techniques described below to help you remove unused CSS and improve your website's overall performance.

What is unused CSS?

No matter how experienced you are as a developer, there is a good chance that your website contains CSS that have no impact on current page elements. For example, frameworks like Bootstrap come with dozens of CSS styles that you probably don't need. If you added a feature during development and removed it later on, there could still be rules associated with that feature lingering in your style sheets. Unused CSS just adds dead weight to your applications and contributes to the growth of web page size, so you want to make sure that you have as little excess code as possible.

Why should you remove unused CSS?

Since CSS defines how content in an HTML document gets displayed, the user's browser must download and parse all external CSS files before it can start rendering content. Consequently, the more CSS a web page contains, the longer users must wait to see anything on their screens. Inlining small CSS within your HTML file and minifying your external style sheets can help optimize content rendering, but cutting out useless CSS is a far more effective strategy for improving overall performance. Combining all of these methods ensures that users see content as quickly as their internet connection will allow. Aside from slowing down your website's overall performance, excess CSS can cause headaches for developers. Clean and orderly style sheets are easier to maintain than disorderly ones. Do your users and yourself a favor by ditching unused CSS.

How to remove unused CSS manually

If you're using Chrome, the DevTools tab has a handy tool that allows you to see what code is being executed on a page on what isn't. To access this tool, follow the steps below:

  1. Open Chrome DevTools
  2. Open the command menu with: cmd + shift + p
  3. Type in "Coverage" and click on the "Show Coverage" option
  4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab

Any CSS that is next to a solid green line means that the code was executed. Solid red means it did not execute. A line of code that is both red and green, means that only some code on that line executed.

Just because a style isn't used on one page doesn't mean that it's not used elsewhere, so you should audit several pages on your site and keep track of which rules keep appearing on the unused list. You can do this by copying and saving the results of each audit into a Google Sheets document. The ones that appear the most can probably be safely removed.

Most developers have better things to do than delete unused CSS rules one by one. That's why there are a variety of tools designed to automate the process. Here is an overview of the most popular tools designed to help web developers remove unused CSS from their web projects:

1. UnusedCSS

The simple name is indicative of this program's user-friendliness. Just plug your website's URL into UnusedCSS and let it do all of the work. In addition to identifying and removing unused CSS rules, it tells you how much memory you've saved. You can try UnusedCSS out for free, but you must pay for a monthly membership to download your cleaned up CSS files. Premium members can schedule automatic CSS optimizations and have access to other features; however, it should be noted that UnusedCSS only works with live websites, so it's not useful in the testing phase.

2. PurifyCSS

PurifyCSS is a free tool that removes unused CSS from your HTML, PHP, JavaScript and CSS files before you go live. On the downside, you must manually specify which files to scan one by one, which makes the process somewhat tedious. Rather than modifying your original files, PurifyCSS outputs a new file with the optimized CSS. Since PurifyCSS doesn't work with live websites, you'll need to use it in a development setting. You may want to use PurifyCSS during development and upgrade to UnusedCSS later on.

3. PurgeCSS

PurgeCSS was inspired by PurifyCSS, so it looks very similar, but it's a bit more streamlined and intuitive to use. It works by comparing your content to your CSS files and removing selectors that don't have a match. The only major downside is that you must manually whitelist CSS not in the specified paths, which can be a headache if your website uses certain plugins such as HTML Forms.

4. UnCSS

UnCSS is more accurate than PurgeCSS since it looks at actual web pages rather than the individual files, but its slower and requires more manual set up. UnCSS is most helpful when used with other tools. For example, you can combine UnCSS with Grunt and Node.js to automate unused CSS removal.

A word of warning about removing unused CSS

The tools discussed in this tutorial are not perfect. There are a few different methods for identifying rouge CSS selectors; however, matching selectors to elements in the DOM can be tricky if you have elements that depend on APIs and third party scripts. If you want to try removing unused CSS manually, then you need to be extra careful so that you don't accidentally cripple your application by deleting something important. That said, you should know your website better than anyone else, and the DevTools auditing feature can provide some valuable insight to help you create tighter CSS from the start.

How to automate unused CSS removal with UnCSS

Now, let's see how we can use one of the tools listed above to trim down your style sheets. This tutorial, thanks to Dean Hume, will explain how to set up Node.js, Grunt, UnCSS and another plugin called CSSmin on a Windows machine to automatically remove unused CSS and minify the results.

1. Install Node.js

Download the latest distribution from the Node.js website and follow the installation instructions.

2. Install Grunt

Open Node.js and enter the following into the command prompt:

npm install -g grunt-cli

Grunt should download and install automatically.

3. Open your project folder

Using the Node.js command prompt, navigate to the folder containing the files you want UnCSS to scan. You can do this by entering the file path. For example:

cd C:TestProject

4. Install UnCSS and CSSMin

Enter the following into the Node.js command prompt:

npm install grunt-uncss grunt-contrib-cssmin --save-dev

UnCSS and the CSSMin package will be installed in the specified project folder.

5. Create a gruntfile.js file

Create a JavaScript file called gruntfile.js in your project's root directory. The gruntfile.js acts as a configuration file for plugins like UnCSS. Enter this code into the Node.js command prompt:

module.exports = function (grunt) { grunt.initConfig({ uncss: { dist: { files: [ { src: 'index.html', dest: 'cleancss/tidy.css' } ] } }, cssmin: { dist: { files: [ { src: 'cleancss/tidy.css', dest: 'cleancss/tidy.css' } ] } } }); // Load the plugins grunt.loadNpmTasks('grunt-uncss'); grunt.loadNpmTasks('grunt-contrib-cssmin'); // Default tasks grunt.registerTask('default', ['uncss', 'cssmin']);};

The above instructions tell UnCSS to scan your index.html file for unused CSS and create a trimmed down CSS file inside a folder named cleancss. The CSSmin plugin will then minify the new CSS file, which will be called tidy.css by default. The final few lines are especially important since they load and register both plugins.

6. Run Grunt

Finally, you must navigate back to your source file folder and run Grunt like so:

cd C:TestProject>grunt

That should set UnCSS and CSSmin into action. If you did everything correctly, you'll have a clean and minified CSS file waiting for you in the specified folder. Some developers have claimed that this method reduced the size of their CSS files by more than 95 percent! That's a lot of savings for minimal effort. You only have to perform the setup process once. In the future, you can just run Grunt to automatically strip your project of unused CSS.

Summary

In addition to unused CSS, your website probably has some HTML and JavaScript that it could do without. Before you start concatenating, minifying, and compressing your files, make sure they're not bloated with unnecessary code and remove unused CSS.

How to Remove Unused CSS for Leaner CSS Files - KeyCDN (2024)

FAQs

How to Remove Unused CSS for Leaner CSS Files - KeyCDN? ›

Tools to remove unused CSS

How to remove unused CSS from a CSS file? ›

How to manually remove unused CSS
  1. From the Show Coverage option, select a CSS file. ...
  2. Then, click on CSS Overview:
  3. Next, click on Capture Overview, and you'll be presented with the CSS overview page, as shown below:
  4. On this page, navigate to the Unused declarations option, and you'll be shown the page in the image below:
Aug 4, 2023

How to clean up CSS code? ›

Best practices to write a clean and efficient CSS code
  1. Start with a framework. It is recommended to use a CSS framework with each design, as it will speed up the production. ...
  2. CSS reset. ...
  3. Maintain consistency. ...
  4. Ensure it's readable. ...
  5. Avoid the ! ...
  6. Keep it DRY. ...
  7. The right usage of CSS shorthand. ...
  8. Use multiple stylesheets.

Should I remove unused CSS? ›

Unused CSS are CSS styles that are not needed to render a page correctly. They can be added as files or as internal styles for elements on a page. Even if you remove all of them, the page will display just fine to the user.

How do I remove an existing CSS? ›

setProperty() method can be used to set the required property of the style. The element of which the property has to be removed is selected and this property is applied to its style property. Setting this property to 'initial' resets the property to its initial value, removing any effect of the property.

Can I delete CSS files? ›

The number of unused CSS files has no effect on how your site ranks in Google, but if you want to delete files you don't want there is always the delete key.

What is the tool to find unused CSS? ›

To find unused code in your page, use the Coverage tool: To open DevTools, right-click the webpage, and then select Inspect. Or, press Ctrl+Shift+I (Windows, Linux) or Command+Option+I (macOS).

How to remove CSS file from cache? ›

Hard Refresh: In many web browsers, you can force a hard refresh to clear the cache. On most browsers, you can do this by pressing Ctrl + F5 (Windows/Linux) or Cmd + Shift + R (Mac) while viewing the page. This should force the browser to fetch the latest version of the CSS fi.

How do I remove custom CSS? ›

The easiest way to remove custom CSS is by simply deleting it from the Customizer. You can access the Customizer by going to Appearance > Customize in your WordPress dashboard. From there, look for the "Additional CSS" section and simply delete the CSS code that you want to remove.

How do I remove unused CSS from Chrome? ›

How to remove unused CSS manually
  1. Open Chrome DevTools.
  2. Open the command menu with: cmd + shift + p.
  3. Type in "Coverage" and click on the "Show Coverage" option.
  4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab.
Mar 4, 2019

How do I remove all default CSS? ›

The all: unset CSS property resets all CSS properties to their initial or inherited values. This means that all properties will revert back to the values that were set in the user agent stylesheet or the values that were passed down from the parent element.

How to remove internal CSS? ›

Given an HTML document containing inline and internal CSS and the task is to remove the inline CSS style from a particular element with the help of JavaScript. Approach: The jQuery attr() and removeAttr() methods are used to remove the inline style property. The attr() method sets the attribute value to empty (”).

How do I get rid of important CSS? ›

The only way to override an !important rule is to include another !important rule on a declaration with the same (or higher) specificity in the source code - and here the problem starts! This makes the CSS code confusing and the debugging will be hard, especially if you have a large style sheet!

How to reduce the number of used CSS files? ›

Here are some steps you can follow to achieve this:
  1. Use a performance analysis tool. Use a performance analysis tool like Google PageSpeed Insights, GTmetrix to identify the unused JavaScript and CSS on your website. ...
  2. Minimize your files. ...
  3. Use lazy loading. ...
  4. Remove unused apps and themes. ...
  5. Optimize images. ...
  6. Minimize HTTP requests.
Mar 6, 2023

Does PostCSS remove unused CSS? ›

js simply bundles all CSS rules into some optimized files through PostCSS. In other words, it does not automatically remove unused CSS rules. Here is where PurgeCSS comes into play! Let's learn what PurgeCSS is, how it works, and how to configure it in a Next.

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 6417

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.