Unloading Unnecessary CSS With Grunt

January 10, 2023 0 Comments

Using a framework like Bootstrap and Foundation is one of the fastest ways to create a responsive website. These Frameworks contain all the necessary elements, including the grid and user interface components, to create a decent and functional website. However, the Frameworks aim to serve as many web scenarios as possible. Therefore, they contain tons of predefined CSS that you may not be using on your site.

Not all styles are useful for all purposes, but if you have them everywhere, the size of your stylesheet will increase unnecessarily, which will ultimately affect the loading speed of your site. In this article, we will show you how to unload these unnecessary styles from style sheets.

First Steps

To realize this idea, we need Grunt CLI. So make sure you have it installed on your computer. You can refer to these two previous articles to learn more about it:

How to remove unnecessary modules in jQuery

Resolution of the grunting error “command not found” in the Terminal

I assume you have a project directory ready that contains HTML and CSS. I have two folders called build-this is used to store the stylesheets during the development phase. and css-this is the destination folder for the final output of the stylesheet.

Then go to the project directory via Terminal and type the following command one by one. These two commands install Grunt and grunt-uncss, the Grunt Plugin that we need to perform the task of removing unused CSS.

Basic configuration

Create a file named Gruntfile.js in your project directory. Open the file in a Code editor and enter the following Codes. The Code is the basic configuration of the Plugin; grunt-uncss retrieves the stylesheet links from the .html, look for CSS selectors that are not used in the specified .html and send the output to css/style.CSS.

Optional Configuration

grunt-uncss offers a number of options. Assuming that you want to ignore some selectors, you can include the Ignore parameter and specify the selectors. You can also control Grunt-css to be processed only for specific style sheets, rather than for those extracted from the HTML file with the style sheets parameter. Configure the output path according to the needs of your project.


The only class that does not exist in the HTML file is .fourth-div. The class has been removed from the stylesheet. Launch Terminal and type grunt to run the task configured in Gruntfile.js.

Open the two CSS files. You will see that the .the class selector for the fourth div has already been removed because it is not used in the HTML code. If you have a lot of unused styles, this trick can help you significantly reduce the size of the stylesheet file.

Leave a Reply

Your email address will not be published. Required fields are marked *