4 Ways to Remove Unused CSS (2024)

How to remove unused CSS to reduce your app’s bundle size and maintain a clear and simple code.

4 Ways to Remove Unused CSS (1)

CSS files can easily gain redundant KBs over time. It may happen due to leftovers from historic stylings or simply because you’ve used a large CSS framework like Bootstrap (147 KB when minimized) and most probably have used only a fraction of what it has to offer. Unused CSS slows down page loading and makes maintenance much more difficult than it has to.

Removing unused CSS is especially useful when sharing reusable UI components from your project, using Bit (Github).

4 Ways to Remove Unused CSS (2)

For example, let’s say I have a simple React app with a header (‘Search’) and a search-bar component.

4 Ways to Remove Unused CSS (3)

Both the header and the search-bar component require the same global CSS. When exporting my search-bar component to a Bit collection, Bit will identify that file as a dependency.

$ bit add src/components/*

and then, let’s try to tag all tracked components

$ bit tag --all

Bit returns an error — the component is dependant on a global CSS file:

4 Ways to Remove Unused CSS (4)

I then add the CSS file:

$ bit add src/style.css
4 Ways to Remove Unused CSS (5)

Let’s export the component with its CSS to my ‘unused-css-example’ collection:

$ bit export eden.unused-css-example

My search-bar component is now in my ‘unused-css-example’ collection:

4 Ways to Remove Unused CSS (6)

The snapshot above tells us the style.css file was added to the collection as well. It is now a dependency of the search-bar. Whenever we npm install it or bit import it to a new project, we will get additional styling that has nothing to do with our search-bar component.

4 Ways to Remove Unused CSS (7)
4 Ways to Remove Unused CSS (8)

Hopefully you’re convinced by now :)

Let’s get on with the list:

This is a tool that is very effective in cleaning out unused css styles.

The cool thing with purgecss is that it can be integrated into your development workflow. PurgeCSS can be used as a CLI tool from the terminal. Install it globally:

npm i purgecss -g

Run the following command in the terminal:

purgecss --css index.css --content index.html

The above will collect the index.css (as indicated by the — css flag) and index.html (as pointed to by the — content flag) and remove all unused CSS selectors in them.

It is available in NPM registry, and can be installed like this:

npm i purgecss -D

See it is installed as a development dependency, so it doesn’t follow you when pushing into production.

We create a JS file and pour in the following code:

// purgecss.jsvar Purgecss = require('purgecss') // ES5
import Purgecss from 'purgecss' // ES6
var purgecss = new Purgecss({
content: ['**/*.html'],
css: ['**/*.css']
})
var purgecssResult = purgecss.purge()

The content and css in the object passed to new Purgecss(...) contains glob pattern that tells PurgeCSS to collect the .html and .css files in the project and purge them of unused CSS code.

The purge method is called and the purgecssResult contains the result of the cleaned css.

We run the file using the node executable:

node purgecss.js

More on the Github repository:

This is another awesome tool, just like purgecss. PurifyCSS works by grabbing all HTML files specified for process comparison against any given CSS file. It searches through the HTML files and the given CSS files, it removes redundant CSS styles and writes the purified CSS to another file, then re-links the HTML files to the purified CSS file.

According to the authors:

A function that takes content (HTML/JS/PHP/etc) and CSS, and returns only the used CSS. PurifyCSS does not modify the original CSS files. You can write to a new file, like minification. If your application is using a CSS framework, this is especially useful as many selectors are often unused.

Its usage is super easy:

npm i purify-css -D

Next, create a file (I’ll call mine purify.js) and add the following code:

// purify.jsconst purify = require("purify-css")const htmlFiles = ['*.html'];
const cssFiles = ['*.css'];
const opts = {
output: 'purified.css'
};
purify(htmlFiles, cssFiles, opts, function (res) {
log(res);
});

We extracted the purify function from the package “purify-css”.

We then set the html files and css files that we want to clean of unused styles to htmlFiles and cssFiles respectively. They hold the files in an array. Here, we used the glob pattern to tell purify-css to collect all the .html and .css files in our project and purge them.

We set the configuration in opts. We just set the file path and name of where the purified css will be stored. There are many configurations we can set, like to minify the purified css, to display how much of unused CSS were purged.

Next, we call the purify function passing the htmlFiles, cssFiles, opts and a callback function that will be called with the result of the purification when it’s completed.

So we just run the purify.js to clean out all the unused css we have:

node purify.js

Check out the Github repository :

This is also a Node module that of course :) removes unused css. Just like we did with purifyCSS, it has a JS API that we call with options to removes unused css styles.

According to the author:

UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS.

We can install it as a global module and use it from the terminal:

npm i uncss -g

and use it from anywhere in our system.

A basic command-line usage of the uncss is this:

uncss src/app/app.component.html >> usedcss.css

All the used css in src/app/app.component.html will be written to usedcss.css.

JS usage is also simple:

// uncss.jsconst uncss = require("uncss")const htmlFiles = ["./index.html"]const opts = {
csspath: "styles/",
stylesheets: ["themes.css"]
}
uncss(htmlFiles, opts, (err, res) => {
if(err)
console.error(err)
console.log(res)
})

The function uncss is extracted from the “uncss” library. We place the html Files in an array, htmlFiles. The configurations are set in the opts. Lastly, the uncss is called with the htmlFiles, opts, and a callback function with a parameter that holds the error and another that holds the result.

The uncss.js file can then be run:

node uncss.js

See more the Github repository:

This Coverage tab helps us find unused Js and CSS code.

Open your Chrome browser, go to “Developer Tools”, click on “More Tools” and then “Coverage”.

A Coverage will open up. We will see buttons for start capturing coverage, to reload and start capturing coverage and to stop capturing coverage and show results.

If you have a webpage you want to analyze its code coverage. Load the webpage and click on the o button in the Coverage tab.

After sometime, a table will show up in the tab with the resources it analyzed, and how much code is used in the webpage. All the files linked in the webpage (css, js) will be listed in the Coverage tab. Clicking on any resource there will open that resource in the Sources panel with a breakdown of Total Bytes and Unused Bytes.

With this breakdown, we can see how many unused bytes are in our CSS files, so we can manually remove them or employ any of the tools we described above.

For more on this, see:

There goes the list of tools we can use to remove redundant and unused CSS code from our web apps.

So, check out your web apps to know whether you have useless codes in your codebase, and use the tools we just described to purge them. Remember, removing unused code can speed up your page load, and save your mobile users that precious cellular data.

Do you have any addition to the list, or why some shouldn’t be there, or you have a problem with one, or just wanna talk? Feel free to drop in your comments, or just can just mail or DM me.

How to Share React UI Components between Projects and AppsA simple guide to help you easily share and reuse React components across apps, to build faster and better.blog.bitsrc.io
5 Tools for Faster Development in React5 tools to speed the development of your React application, focusing on components.blog.bitsrc.io
11 JavaScript Animation Libraries For 2019Some of the finest JS and CSS animation libraries around.blog.bitsrc.io
4 Ways to Remove Unused CSS (2024)

FAQs

What is the best way to remove unused CSS? ›

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.

How do you purge unused CSS variables? ›

css, you can remove unused keyframes by setting the keyframes option to true . If you are using Custom Properties (CSS variables), or a library using them such as Bootstrap, you can remove unused CSS variables by setting the variables option to true .

What tool checks for unused CSS? ›

Check your unused css with the chrome dev tool.

How do I manually delete unused CSS in WordPress? ›

Upon activation, you need to visit the Settings » WP Rocket page and switch to the 'File Optimization' tab. Next, you need to scroll down to the CSS Files section and then check the box next to the 'Remove Unused CSS (Beta)' option.

How to reduce unused CSS and JavaScript? ›

Prioritize using themes and plugins with modular CSS inclusion (only load necessary code to style their modules or output on the page). Minimize as much as possible the number of plugins that add a lot of code on the front-end. Use assets control plugins to remove unnecessary CSS files from bloated themes and plugins.

How to remove all CSS in HTML? ›

There is a property called all that is being proposed for resetting all CSS properties for a given element to certain CSS-wide values - the value you want to use would be unset , which resets a property to either its inherited value if it inherits by default, or otherwise, its initial value.

How do I clean up a CSS file? ›

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.

Why reduce unused CSS? ›

# How unused CSS slows down performance

Each external stylesheet must be downloaded from the network. These extra network trips can significantly increase the time that users must wait before they see any content on their screens. Unused CSS also slows down a browser's construction of the render tree.

What is purge CSS? ›

PurgeCSS removes unused CSS rules from your stylesheets to reduce their size and therefore speed up page-loads. It's very important that you configure this tool correctly, or it will remove CSS rules that you need!

How to remove CSS using CSS? ›

Use the style. removeProperty() method to remove CSS style properties from an element. The removeProperty() method removes the provided CSS style property from the element.

Does Webpack remove unused CSS? ›

Eliminating unused CSS is possible using PurgeCSS. It performs static analysis against the source. The functionality can be enabled through purgecss-webpack-plugin. At best, PurgeCSS can eliminate most, if not all, unused CSS rules.

How do I remove all CSS from a website? ›

Try this: $('link[rel="stylesheet"]'). remove(); This will remove all stylesheets (all the styles applies due to those stylesheets) from the page.

How to remove all CSS from class? ›

To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes.

How do I remove CSS from a website? ›

Hover over your page and click Edit. In the page editor, click Settings at the top of the editor. Scroll down and click Advanced Options. Under Page Stylesheets, click the x next to the stylesheet you'd like to remove.

How to remove duplicate CSS? ›

Go to the CSS file. Type (Ctrl + Shift + P) and search with “check duplicates with regex match” and select it. Paste this regex ^\. [\w\-\s\.>:,\[\]\*\=]+{ and hit Enter.

How to remove unused CSS angular? ›

This tool will analyze JavaScript and HTML file and removes the unused CSS. Create a external script file, here the following script analyze the dist folder and minimize the CSS file. Create a scripts folder under the project src directory. Update the package scripts and include purgecss command with build command.

How do I find unused JS or CSS? ›

Analyze code coverage

Click a row to open that resource in the Sources tool and display a line-by-line breakdown of used code and unused code. The URL of the resource that was analyzed. Whether the resource contains CSS, JavaScript, or both.

How to remove CSS in JavaScript? ›

The removeProperty() method removes the specified CSS property from a CSS declaration block.

How to remove all CSS in JavaScript? ›

How to Remove all CSS from a Page With One JavaScript Command
  1. Mac: Option + CMD + J.
  2. Windows: Shift + CTRL + J.
Jun 2, 2020

How do I remove all CSS from WordPress? ›

How to use the purified CSS code on your WordPress website
  1. Upload purified stylesheet. ...
  2. Remove existing stylesheets. ...
  3. Make sure all styles have been removed. ...
  4. Remove inline styles if any exists. ...
  5. Enqueue the purified CSS. ...
  6. Test your changes thoroughly! ...
  7. Adjust purified CSS code.
Jan 27, 2020

How to remove HTML CSS? ›

You cannot remove an element from the DOM tree using CSS. You can only prevent it from being rendered in the layout with display: none ; doing so does not prevent it from responding to events or cause it to be ignored by CSS selectors such as + and :nth-child() .

How to remove CSS class from HTML? ›

If you want to remove a specific class from an element and leave the others as they are, use the classList. remove() method instead.

Can I delete CSS files? ›

To remove an external CSS file from the Styles Tree: In the Styles Tree, right-click on the CSS file name. A context menu will appear, containing three commands: Add CSS rule..., Delete CSS file, and Include CSS file to.... Select Delete CSS file.

How do I remove unused CSS from Shopify? ›

How to Remove Unused Javascript and CSS?
  1. Check the Assets folder of the theme and check for unused JS and CSS files.
  2. Now remove unused CSS and Javascript files.
  3. Check and remove the unused apps, if any.
  4. If your store has not installed any app you can comment {{ content_for_header }} code in the theme. liquid.
Sep 16, 2022

Should you compress CSS? ›

It is important to minify your CSS and minimise JavaScript files so they can load faster on your web pages. There are many reasons why you should minify your CSS and JavaScript: Reduce file size: The more code there is in a file, the larger it will be. Minified code is usually much smaller than the original version.

How to remove bootstrap unused CSS? ›

The uncss page has full instructions, but to summarize:
  1. Have node. js installed.
  2. npm install -g uncss.
  3. Copy the sample file from the uncss page and name it anything with a . js extension. ...
  4. Replace the files array with your html files. ...
  5. Replace the stylesheets array with your stylesheets. ...
  6. Run node uncss.
Jan 3, 2013

Does PostCSS remove unused CSS? ›

This is a simple to use PostCSS plugin that removes CSS selectors based on your other files. This package is inspired by PurifyCSS and works the same way.

Is purge same as delete? ›

The purging process allows an administrator to permanently remove data from its primary storage location, yet still retrieve and restore the data from the archive copy should there ever be a need. In contrast, the delete process also removes data permanently from a storage location, but doesn't keep a backup.

What does it mean to purge a file? ›

Purging is the process of freeing up space in the database or of deleting obsolete data that is not required by the system. The purge process can be based on the age of the data or the type of data.

What are the 4 capabilities of CSS? ›

CSS can define color, font, text alignment, size, borders, spacing, layout and many other typographic characteristics, and can do so independently for on-screen and printed views.

What are the four 4 different methods to add CSS to a webpage? ›

Using CSS
  • Inline - by using the style attribute inside HTML elements.
  • Internal - by using a <style> element in the <head> section.
  • External - by using a <link> element to link to an external CSS file.

What are the 3 methods defining CSS? ›

Styling in CSS. There are 3 distinct methods for styling in CSS, Local style, Page-Level style, and External Styles. Each level of styling is given a different hierarchical priority (when to apply) and is used for different reasons.

How do I remove and add CSS? ›

  1. Add Class. var el = document. getElementById("div1"); // Adding Single class el. ...
  2. Remove Class. var el = document. getElementById("divID"); // Removing class el. ...
  3. Toggle Class. var el = document. getElementById("divID"); // If active is set remove it, otherwise add it el. ...
  4. Check Class. var el = document.
Jul 9, 2020

How to remove display in CSS? ›

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

How do you remove text in CSS? ›

To remove text, use the concept of remove(). Use filter to get the content not inside element tag.

Why remove unused code? ›

One way to maintain code relevance is by identifying and deleting unused code. This can streamline our codebases, making them easy to maintain, and can improve our ability to deliver commercial benefit to the organization. We come across examples of unused code, often not realizing it.

How to remove unused code in Java? ›

Delete unused code and unneeded files. In the case of an unnecessary class, Inline Class or Collapse Hierarchy can be applied if a subclass or superclass is used. To remove unneeded parameters, use Remove Parameter.

How to remove dynamic CSS? ›

How to add / remove CSS class dynamically in jQuery
  1. $('#para1'). addClass('highlight'); – Add a “highlight' css class to elements that contain id of “para1”.
  2. $('#para1'). removeClass('highlight'); – Remove a “highlight' css class from elements that contain id of “para1”.
Aug 29, 2012

How to get rid of list CSS? ›

The removal of the list bullets is not a complex task using CSS. It can be easily done by setting the CSS list-style or list-style-type property to none. The list-style-type CSS property is used to set the marker (like a disc, character, or the custom counter style) of a list item element.

How do I override all CSS styles? ›

How to Override CSS Styles
  1. Table of Contents.
  2. Cascading order.
  3. Inheritance. Example of using an element inheriting the style of the parent element: Example of overriding the style of the <p> tag:
  4. Internal Priorities. Example of overriding CSS style with the ID selector: ...
  5. ! Important. ...
  6. Related Resources.

How do I remove all styles from a tag in CSS? ›

Remove all Styles from an Element using JavaScript
  1. Use the removeAttribute() method to remove all styles from an element, e.g. box. ...
  2. The removeAttribute method will remove the style attribute from the element.
  3. If you want to remove a specific CSS property from the element's style, set the property to null .

How to remove inline CSS in HTML? ›

Setting the value of a style property to an empty string — e.g. $('#mydiv'). css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's . css() method, or through direct DOM manipulation of the style property.

How do I reduce unused CSS in hummingbird? ›

Use Fewer CSS files in the Critical Path

The best way to use less CSS files is to combine those files. In essence, this means copying the contents of one CSS file and pasting it into another. Once that is done, you have to remove the call to the extra CSS files from your HTML file.

How do I reduce unused CSS in react? ›

Open UnCSS and paste the copied HTML code inside the HTML section and also copy the CSS from your stylesheet and paste it under the CSS section and click on UNCSS MY STYLES in it will automatically generate the CSS which is required by removing the unused CSS from the stylesheet.

Does tailwind remove unused CSS? ›

By default, Tailwind will only remove unused classes that it generates itself, or has been explicitly wrapped in a @layer directive. It will not remove unused styles from third-party CSS you pull in to your project, like a datepicker library you pull in for example.

Can you Unminify CSS? ›

Installing the Beautifier.io via the command line means that we can unminify local files. It uses the same technology as the website and the Chrome extension. So you can unminify CSS, Javascript, and HTML.

How to remove CSS from class? ›

Learn how to remove a CSS class from an HTML element dynamically in JavaScript.
  1. Remove Class From Element – classList.remove()
  2. Remove Class From Element – setAttribute()
  3. Remove Class From Element – className Property.
  4. Remove Multiple Classes From An Element.
  5. Remove Class From All Elements.
Oct 18, 2022

How to remove listing CSS? ›

The removal of the list bullets is not a complex task using CSS. It can be easily done by setting the CSS list-style or list-style-type property to none. The list-style-type CSS property is used to set the marker (like a disc, character, or the custom counter style) of a list item element.

How to delete CSS file? ›

Removing a CSS file
  1. In the Styles Tree, right-click on the CSS file name. A context menu will appear, containing three commands: Add CSS rule..., Delete CSS file, and Include CSS file to....
  2. Select Delete CSS file.

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 6469

Rating: 4.3 / 5 (44 voted)

Reviews: 91% 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.