Eliminating Unused CSS (2024)

Frameworks like Bootstrap or Tailwind tend to come with a lot of CSS. Often you use only a small part of it and if you aren't careful, you will bundle the unused CSS.

PurgeCSS is a tool that can achieve this by analyzing files. It walks through your code and figures out which CSS classes are being used as often there is enough information for it to strip unused CSS from your project. It also works with single page applications to an extent.

Given PurgeCSS works well with webpack, we'll demonstrate it in this chapter.

Setting up Tailwind#

To make the demo more realistic, let's install Tailwind to the project.

npm add tailwindcss postcss-loader -D

Generate a starter configuration using npx tailwindcss init. After this you'll end up with a tailwind.config.js file at the project root.

To make sure the tooling can find files containing Tailwind classes, adjust it as follows:

tailwind.config.js

module.exports = { content: ["./src/**/*.js"], theme: { extend: {}, }, plugins: [],};

To load Tailwind, we'll have to use PostCSS:

webpack.parts.js

exports.tailwind = () => ({ loader: "postcss-loader", options: { postcssOptions: { plugins: [require("tailwindcss")()] }, },});

The new configuration still needs to be connected:

webpack.config.js

const cssLoaders = [parts.tailwind()];

const commonConfig = merge([ ...

parts.extractCSS(),

parts.extractCSS({ loaders: cssLoaders }),

]);

To make the project aware of Tailwind, import it from CSS:

src/main.css

@tailwind base;@tailwind components;/* Write your utility classes here */@tailwind utilities;body { background: cornsilk;}

You should also make the demo component use Tailwind classes:

src/component.js

See Also
Unminify CSS

export default (text = "Hello world") => { const element = document.createElement("div"); element.className = "rounded bg-red-100 border max-w-md m-4 p-4"; element.innerHTML = text; return element;};

If you run the application (npm start), the "Hello world" should look like a button.

Eliminating Unused CSS (1)

Building the application (npm run build) should yield output:

⬡ webpack: Build Finished⬡ webpack: asset main.css 1.99 MiB [emitted] [big] (name: main) asset index.html 237 bytes [compared for emit] asset main.js 193 bytes [emitted] [minimized] (name: main) Entrypoint main [big] 1.99 MiB = main.css 1.99 MiB main.js 193 bytes orphan modules 261 bytes [orphan] 2 modules code generated modules 309 bytes (javascript) 1.99 MiB (css/mini-extract) [code generated] ./src/index.js + 1 modules 309 bytes [built] [code generated] css ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[0].use[2]!./src/main.css 1.99 MiB [code generated]

As you can see, the size of the CSS file grew, and this is something to fix with PurgeCSS.

Enabling PurgeCSS#

purgecss-webpack-plugin allows you to eliminate most of the CSS as ideally we would bundle only the CSS classes we are using.

npm add glob purgecss-webpack-plugin -D

You also need to configure as below:

webpack.parts.js

const path = require("path");const glob = require("glob");const { PurgeCSSPlugin } = require("purgecss-webpack-plugin");const ALL_FILES = glob.sync(path.join(__dirname, "src/*.js"));exports.eliminateUnusedCSS = () => ({ plugins: [ new PurgeCSSPlugin({ paths: ALL_FILES, // Consider extracting as a parameter extractors: [ { extractor: (content) => content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || [], extensions: ["html"], }, ], }), ],});
For exceptions, starting from 3.0 PurgeCSS includes safelist and blocklist options.

Next, the part has to be connected with the configuration:

webpack.config.js

const productionConfig = merge();

const productionConfig = merge([parts.eliminateUnusedCSS()]);

If you execute npm run build now, you should see something:

⬡ webpack: Build Finished⬡ webpack: asset main.css 7.68 KiB [emitted] (name: main) asset index.html 237 bytes [compared for emit] asset main.js 193 bytes [compared for emit] [minimized] (name: main) Entrypoint main 7.87 KiB = main.css 7.68 KiB main.js 193 bytes orphan modules 261 bytes [orphan] 2 modules code generated modules 309 bytes (javascript) 1.99 MiB (css/mini-extract) [code generated] ./src/index.js + 1 modules 309 bytes [built] [code generated] css ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[0].use[2]!./src/main.css 1.99 MiB [code generated] webpack 5.5.0 compiled successfully in 2429 ms

The size of the style has decreased noticeably. Instead of 1.99 MiB, we have roughly 7 KiB now.

Tailwind includes PurgeCSS out of the box and it can be preferable to use that. See Tailwind documentation for more information. The example above is enough to illustrate the idea, and it works universally.
uncss is a good alternative to PurgeCSS. It operates through PhantomJS and performs its work differently. You can use uncss itself as a PostCSS plugin.

Critical path rendering#

The idea of critical path rendering takes a look at CSS performance from a different angle. Instead of optimizing for size, it optimizes for render order and emphasizes above-the-fold CSS. The result is achieved by rendering the page and then figuring out which rules are required to obtain the shown result.

critical-path-css-tools by Addy Osmani lists tools related to the approach.

Conclusion#

Using PurgeCSS can lead to a significant decrease in file size. It's mainly valuable for static sites that rely on a massive CSS framework. The more dynamic a site or an application becomes, the harder it becomes to analyze reliably.

To recap:

  • 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.
  • Critical path rendering is another CSS technique that emphasizes rendering the above-the-fold CSS first. The idea is to render something as fast as possible instead of waiting for all CSS to load.

In the next chapter, you'll learn to autoprefix. Enabling the feature makes it more convenient to develop complicated CSS setups that work with older browsers as well.

Eliminating Unused CSS (2024)

FAQs

Should I remove unused CSS? ›

you should remove it if you dont plan on ever using it. leaving unused code will increase you file size and slow your website down. Plus it will confuse you or future programmers as to why the code is their in the first place.

How to solve reduce unused CSS? ›

The steps are straightforward:
  1. Backup your CSS original files. ...
  2. Open the Code Coverage Tab in Google Chrome and view per CSS file which declarations you do not need.
  3. Open the CSS file on the server (or locally) and check each unused CSS declaration . ...
  4. Check per CSS declaration whether it is not duplicated in the CSS.

How do I remove unused CSS asset CleanUp? ›

Asset cleanup is a plugin that helps you to reduce unused CSS to improve the WordPress website's pagespeed. First, it will fetch the homepage and will show you all CSS files loaded on that page. You need to review all loaded files. If you find any files that you don't need then you need to unload that file.

How to check if remove unused CSS is working? ›

How to check if Remove Unused CSS is working # The <style> element with an id wpr-usedcss will contain the resulting Used CSS for the page. At this point, you can run a PageSpeed test to see the benefits of this feature. Note: While the overall page size will decrease, the HTML response body size may increase.

Will CSS become obsolete? ›

The short answer is "no", HTML and CSS in some form will be around until after you retire. Remember Fortran (declared "dead" when C++ came out) is still around and there are lots of programs still in use, with "Fortran 2015" being discussed.

Does anyone still use CSS? ›

Dude absolutely. If all you need is to make a simple website, then html and css are really all you need. I do that everyday at my job and in my freelance business. I just make static 5 page websites for small businesses and I don't even touch react and only minor JavaScript for class toggling.

How to identify unused CSS? ›

To find unused code in your page, use the Coverage tool:
  1. To open DevTools, right-click the webpage, and then select Inspect. ...
  2. In DevTools, open the Command Menu. ...
  3. Start typing coverage, press the Down Arrow key to highlight the Show Coverage command, and then press Enter:
Dec 7, 2023

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 reduce the number of 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

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 an existing CSS? ›

Using the removeProperty() method

To remove CSS property using JavaScript, we have used removeProperty() method. The removeProperty() method is used to remove the specified CSS property in the parameter. This method removes only inline styles.

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!

What is the best way to reduce unused CSS? ›

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.

What is the impact of unused CSS? ›

How Unused CSS Slows Down Page Load. The term Unused CSS refers to CSS rules that aren't used on the current page. These rules make files larger than necessary. Since larger files take longer to download, unused CSS slows down the page load.

Is PurgeCSS good? ›

Modularity enables developers to create module extractors for specific use cases and frameworks. An extractor is a function that reads the contents of a file and extracts a list of CSS selectors that are used. PurgeCSS provides a very reliable default extractor that can work with a wide range of files types.

Is it better to have one CSS file? ›

The reason that I don't recommend doing this is because now that they're all in the same file, the cache for all of them is busted together. It's also better to use separate style sheets for better control over the order of styles.

Should you ever use important CSS? ›

Remember, use ! important sparingly and only as a last resort. Focusing on clean, specific, and well-organized CSS will lead to more maintainable and predictable styles in the long run.

Is CSS really important? ›

It is the coding language that gives a website its look and layout. Along with HTML, CSS is fundamental to web design. Without it, websites would still be plain text on white backgrounds.

Top Articles
Steam Support :: Recommended Trading Practices
ParkWhiz: Find and Book Parking Anywhere
Victor Spizzirri Linkedin
Dricxzyoki
Black Gelato Strain Allbud
The Best Classes in WoW War Within - Best Class in 11.0.2 | Dving Guides
Victoria Secret Comenity Easy Pay
Danielle Longet
What’s the Difference Between Cash Flow and Profit?
zopiclon | Apotheek.nl
Dutchess Cleaners Boardman Ohio
Overton Funeral Home Waterloo Iowa
Chic Lash Boutique Highland Village
Viprow Golf
9044906381
Dr Adj Redist Cadv Prin Amex Charge
Equipamentos Hospitalares Diversos (Lote 98)
Star Wars: Héros de la Galaxie - le guide des meilleurs personnages en 2024 - Le Blog Allo Paradise
Parent Resources - Padua Franciscan High School
Praew Phat
Apply for a credit card
Nearest Walgreens Or Cvs Near Me
Ein Blutbad wie kein anderes: Evil Dead Rise ist der Horrorfilm des Jahres
Barber Gym Quantico Hours
Maxpreps Field Hockey
Lexus Credit Card Login
Ficoforum
897 W Valley Blvd
Nurofen 400mg Tabletten (24 stuks) | De Online Drogist
Craigslist/Phx
100 Million Naira In Dollars
Selfservice Bright Lending
Solemn Behavior Antonym
Imperialism Flocabulary Quiz Answers
Ise-Vm-K9 Eol
Frommer's Philadelphia &amp; the Amish Country (2007) (Frommer's Complete) - PDF Free Download
Callie Gullickson Eye Patches
Beaufort SC Mugshots
Carteret County Busted Paper
814-747-6702
Tableaux, mobilier et objets d'art
Ehome America Coupon Code
Whitney Wisconsin 2022
DL381 Delta Air Lines Estado de vuelo Hoy y Historial 2024 | Trip.com
Headlining Hip Hopper Crossword Clue
Colin Donnell Lpsg
17 of the best things to do in Bozeman, Montana
Slug Menace Rs3
Rétrospective 2023 : une année culturelle de renaissances et de mutations
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Wayward Carbuncle Location
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 6158

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.