How do you remove unused CSS from a website? 🇧🇷 CSS tricks (2023)

DigitalOcean offers cloud products for every stage of your journey. start with$200 Free Credit!

I would like you to know the following in advance:This is a difficult problem.If you landed here hoping to be directed to a tool you can run that will tell you exactly what CSS to remove from your project, well...there are tools out there, but I caution you You from being very careful with them becausenone of them can tell you the whole story.

I know what you want. You want to run the tool, remove what it tells you and you'll have a faster website in 2.2 minutes. I'm sorry but I will disappoint you.

I think you should have a healthy dose of skepticism about such a tool. None of them are accuratelyingFor you, they often just don't have enough information to provide you with safe and actionable results. That doesn't mean you can't use them or that you can't. Let us go for a walk.

Die Motivation

I would guess controller #1 for wanting to remove unused CSS is this:

You used a CSS framework (e.g. Bootstrap), included the full CSS file for the framework, and used only some of the provided patterns.

I can relate. CSS frameworks often don't provide easy ways to decide on exactly what you're using, and customizing the font to make it work that way can require a level of expertise your team doesn't have. That might even be the reason why you initially looked for a framework.

Suppose you load 100 KB of CSS. I would say that's a lot. (As of this writing, this page is ~23 KB, and there are quite a few pages and templates. I'm not doing anything special to reduce the size.) You have suspicion or evidence that you are missing some of these bytes use. I can identify the cause of the alarm. If you had a 100kb jpg that you could compress to 20kb by dragging it into a tool, that's great and worth it.But the win for CSS is even more important because CSS gets loaded in the head and blocks rendering.. The JPG is not.

😬 Watch "Coverage".

Chrome DevTools has a "Coverage" tab that tells you how much of your CSS and JavaScript is being used. For example, if I'm just visiting the CSS Tricks homepage...

How do you remove unused CSS from a website? 🇧🇷 CSS tricks (1)

It tells me that 70.7% of mystyle.cssThe file is not used. I'm assuming that's correct and that the rest of the CSS is used elsewhere. Not only did I download a huge library of styles on this site; I hand-wrote every line of it, so I have my doubts that more than 2/3 of it is not used worldwide.

I figured I could start "burning", then click on different areas of the site and watch the dead count go down as different pages are rendered with different HTML, but unfortunately it does so too when the page refreshes becomes. Not very useful for getting a multi-page view of CSS coverage unless you have a one-page app I think.

I hate to say this, but I find it pretty pointless to look at code coverage. To me it paints a horrible picture of all this unused code on the site exploiting my doubts, but all I can do is worry about it.

This might have given you the idea that unused CSS needs to be discovered and removed in the first place.

my main concern

My biggest concern is that you look at something like code coverage and see your unused lines:

How do you remove unused CSS from a website? 🇧🇷 CSS tricks (2)

and you goPerfect! I will remove this CSS!And he does, only to find out that it wasn't used at all and that it was causing major styling problems across the site. Here's the thing: You don't actually know if a CSS selector isn't being used unless:

  1. Check the coverage on every page of your entire website...
  2. while all the JavaScript is running...
  3. under every possible status combination...
  4. on all possible combinations of media queries that you have used.

Checking your home page doesn't count. Verifying all your top-level pages doesn't count. you have to dig througheveryoneside, including states that aren't always the most important ones, not to mention all the peripheral scenarios. Otherwise, you might remove the dropdown style for the credit card selection dropdown in the popup modal that appears for users with a deactivated account who have logged in during their grace period and also have a gift card to apply for.

This is too complex for automated tools to promise their approach to work perfectly, especially when considering the unknowns of browser context (different screen sizes, different features, different browsers) and third-party vendors.

Here is an example of my concern:

PurifyCSS Online takes a few URLs and immediately provides a copy and paste CSS snippet that can be used

Here I paste my css-tricks.comClean CSS onlineand always new CSS.

¡Uy!

How do you remove unused CSS from a website? 🇧🇷 CSS tricks (3)

It gave me the option to enter other URLs (which is nice), but there are tens of thousands of URLs in CSS tricks. Many of them are quite similar, but they all have the potential of using selectors. I get the impression that you didn't run any JavaScript since everything that got into the page via JavaScript wasn't formatted. even deleted mine:hoverconditions

Perhaps you can see why my confidence in these tools is so low.

part of a construction process

Reines CSSIt will likely be used as a build process tool rather than an online interface. Your docs contain instructions for Grunt, Gulp, and Webpack. For example global files to check and process them:

var content = ['**/src/js/*.js', '**/src/html/*.html'];var css = ['**/src/css/*.css'];var options = { // Write clean CSS in this file. Output: './dist/purified.css'}; purify(content, css, options);

This gives you a lot more opportunity for accuracy. This content blob could be a list of all the templates, part files, and JavaScript that your website creates. This can be hard to maintain, but you'll certainly get more precision. It doesn't take into account content in data stores (e.g. this blog post living in a database) and third-party JavaScript, but maybe that doesn't matter to you or you can explain it differently.

PurgeCSS, a competitor of PurifyCSS,warnsto your comparison technique:

PurifyCSS can work with any file type, not just HTML or JavaScript. PurifyCSS works by looking at all the words in your files and comparing them to the selectors in your CSS. Each word is considered a selector, which means many selectors can be considered abused. For example, you might have a word in a paragraph that matches a selector in your CSS.

So keep that in mind too. It's silly how it compares possible selector matches, which is both clever and dangerous.

UnusedCSS is an online service that crawls your website for you.

Manually configuring a tool to look at every page of your website from all angles is certainly a chore and something that needs to be kept in sync from day to day as your codebase evolves. Interestingly, the online servicecss in useIt attempts to overcome this burden by crawling the website itself based on a single URL you provide.

I have enrolledpaid outservice and pointed to CSS tricks. I'll admit, just looking at the results makes it seem a lot more accurate:

How do you remove unused CSS from a website? 🇧🇷 CSS tricks (4)

It also allows you to download the clean file and offers many customization options such as: B. enabling/disabling the selectors you really want/don't want (e.g. you're sure you really do). need), as well as the prefix and removing duplicate selectors.

I enjoyed the higher accuracy of the online tracking service,but there was a lot of noise, and I can't see how I could practically fit it into a daily build and release process either.

The tools are usually used in post-processing

Let's say your CSS was created with Less or Sass, then use a post processor to compile it into CSS. I would probably include automatic cleanup of unused CSS at the end of any other CSS preprocessing you do. I like this…

  1. Sass
  2. PostCSS / Autoprefixer
  3. [ Clean up unused CSS ]
  4. Production CSS

That makes sense and it's kinda funny to me. not you reallyarrangethe style generated by unused CSS. Instead, just clean it up at the end of the build. I think JavaScript has been doing this for a while so there is precedent, but it still strikes me as odd because a CSS codebase is so handy. This setting almost encourages you to dump CSS somewhere, since there's no penalty for overdoing it. It removes any incentive to understand how CSS is applied and used.

PurgeCSS is another tool that takes explicit input and gives you the results.

PurgarCSSis another player in the untapped CSS market. A side thing I like is thatclearly explain how it differsfrom other tools. For example compared to PurifyCSS:

The biggest flaw of PurifyCSS is the lack of modularity. However, this is also its greatest advantage. PurifyCSS can work with any file type, not just HTML or JavaScript. PurifyCSS works by looking at all the words in your files and comparing them to the selectors in your CSS. Each word is considered a selector, which means many selectors can be considered abused. For example, you might have a word in a paragraph that matches a selector in your CSS.

PurgeCSS solves this problem by providing the ability to create an extractor. An extractor is a function that takes the contents of a file and extracts the list of CSS selectors used in it. Allows seamless removal of unused CSS.

PurgeCSS seems to be the big dog at the moment. Many people use it and write about it.

Although PurgeCSS needs a special configuration to work with Tailwind, it seems like Tailwind and PurgeCSS are two peas in one pod. As a matter of fact,Their docs recommend using them togetherand offersa CLIto use it in a build process.

I think the gist of it is this: Tailwind produces this big CSS file full of useful selectors. But they don't intend for you to use everything. You use these utility selectors in your HTML to create your entire layout, then use PurgeCSS to display all your HTML, and remove any unused utility selectors in your production CSS.

Still, it will be an ongoing maintenance issue to notify you of every template on your website (JavaScript, HTML or other) while manually configuring everything that relies on third-party resources and knowing that all data coming from a datastore are unlikely to be seen at during a build process, so you'll need to account for that manually.

My favorite technique: Have someone who is really familiar with your CSS codebase be aware of the problem and try to fix it over time.

Maybe this feels like a veteran's approach that needs to adapt with the times, but hey, this seems like the most practical approach to me. Because this problem is so difficult, I believe hard work is the answer. It's about understanding the problem and working on a solution over time. A frontend developer who is closely related to your frontend will after a while understand what is used and used in CSS land and be able to narrow it down.

One extreme testing approach I've seen is to use a (i.e.Hintergrundbild: url(/is-this-used.gif?selector);) in the CSS block and then checks the server logs over time to see if that image has been accessed. If accessed, it has been used; if not, it wasn't.

But perhaps my favorite tool in the potential toolbox is this:

Visual Regressionstests

Screenshots as much as possible of your website, such as B. All major pages and pages treated in different states, as well as different browsers and screen sizes. These screenshots are taken from your master branch in Git.

Then, before the branches are merged into Master, take all these screenshots and compare them to the screenshots in Master. Not manually, but programmatically.

That's itpercyit does, so check this out:

There have been other attempts at visual regression testing tools over the years, but Percy is the only one I've seen that makes clear sense to me. I don't just have to take screenshots; I want to compare them so I can see the visual differences between them. I don't just want to see the differences; I want to approve or reject them. I also want this permission to block or allow merges and I want to be able to control the browser before the screenshot is taken. I don't want to manually update the comparison images. It's all bread and butter, Percy stuff.

Full Disclosure:Percy has previously sponsored things on CSS tricks here, including the video above, but not this post.

The relationship to Atomic CSS and CSS-in-JS

I'm sure a lot of people reading this would say: I don't have unused CSS because the tools I use generate the CSS you need and nothing else.

Hey, that's great.

maybe that's how it isatomizer. maybe that's how it isTachyonenthat you run tooUnCSSand you are very careful with it. maybe it's hertailwind+PurgarCSSCombo that's all the rage right now.

Perhaps you approach styles in a different way. If you tightly couple JavaScript components and styles like React and Emotion, or just use CSS modules with whatever, less unused CSS is a benefit of CSS-in-JS. And because tree churning and code splitting occur in many JavaScript-based build processes, you not only have less CSS, you only load what you need at the moment.there are compromisesalthough to all this

How to avoid unused CSS in future projects?

I think the future of styling lies in a conscious split between global styles and components. Most styles are component-only, but there are global style options that clearly leverage cascading (e.g. global typography defaults).

When most of the styling is confined to components, I think there's less opportunity to accumulate unused styles, as it's much easier to focus on a small block of HTML and a small block of CSS that directly relate to each other stand. . And as the components die or evolve, the style dies or evolves with it. CSS packages consist of components that are actually used.

CSS-in-JS solutions naturally go in this direction since styles are bound to components. That's really the main point. But it is not mandatory. I like the generic approach ofCSS-Module, which is pretty much strictly for the style area and doesn't require you to use any specific JavaScript framework.

If this all seems theoretical or out of scope, and you just have a Bootstrap site where you're trying to reduce the size of all Bootstrap CSS, I recommend starting with using Bootstrap from source instead of the final default . distributed package. The source is SCSS and was built from a series of high-level includes. So if you don't need certain parts of Bootstrap, you can remove them.

How do you remove unused CSS from a website? 🇧🇷 CSS tricks (5)

good luck gang

FAQs

How do I remove unused CSS from CSS? ›

If you want to remove unused CSS entirely, you can use a tool such as PurifyCSS to find out how much CSS file size can be reduced. Once you get the CSS code you should eliminate, you have to remove it manually from the page. If you want to deep dive into a manual solution, you can read the CSS-tricks in-depth article.

How do I get rid of unused CSS plugins? ›

Navigate to the CSS tab of the plugin settings, you will see a toggle to remove unused CSS. You can also clear the CSS cache from here. The plugin also includes options for: Lazy loading.

How do I manually delete unused CSS in WordPress? ›

On the post edit screen, you'll find the Asset CleanUp box just below the post editor. The plugin will automatically fetch and list all the files and assets loaded when a visitor views this page on your website. You can then simply unload the unused CSS or JavaScript files that you don't need on that page.

How do I 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.

Why remove unused CSS? ›

Reducing unused CSS rules can reduce render-blocking behaviour to speed up your page load and improve your visitors' page experience. By default, CSS files are considered render-blocking as they delay First Paint until the browser has finished executing them.

How do I get rid of unused? ›

The tried-and-true method for deleting apps from your Android phone or tablet is simple: Long-press on the app's icon until the app shortcut's popup shows up. You'll either see an "i" button or see App Info; tap it. Next, select Uninstall. It's simple and works on every Android device I've ever used.

How do I stop CSS from being cached? ›

All you need to do is add a version URL parameter to the end of your href like so ? version=1 . The browser will notice the new version and stop caching the stylesheet. All changes in your stylesheet will be reflected in your browser.

Can I delete a CSS file? ›

You can't delete CSS files through Javascript on the browser because that's a client-side scripting language.

How do I reduce the number of CSS files? ›

There are three basic optimizations you can make to limit the amount of data transferred in the delivery process: CSS minification, CSS file length reduction by reducing unnecessary code, and. CSS compression to deliver a smaller file that the browser can still read.

How do I remove additional CSS from Wordpress? ›

If you used a plugin, then your custom css code is 100% in your database. You can acces the phpmyadmin, select your database and search in it a class or piece of code that you want to remove it. Once you find the table and row, you can easily edit it and delete the css code that you want.

How do I get rid of unused CSS in Chrome? ›

Unminify JavaScript and CSS in your browser
  1. Open Chrome DevTools. Control + Shift + I. ...
  2. Open the Command Menu. Control + Shif t +P. ...
  3. Type + click the following: "Show Coverage"
  4. Click the reload button to reload the page and to see which code is loaded.
  5. Then double click on the JS or CSS file that you want to unminify.
23 Feb 2021

How do I remove all CSS from a class? ›

To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.

How do I clean unused codes? ›

Here's a general process for finding and deleting unused code:
  1. Find a piece of code that you suspect to be unused: a function, CSS class, template file, image, etc.
  2. Check the current code doesn't seem to use it.
  3. Check the history to try and find when it was last used.
  4. Delete it!
18 Apr 2022

How do I remove unused CSS from VS code? ›

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. ...
  2. Install Grunt. ...
  3. Open your project folder. ...
  4. Install UnCSS and CSSMin. ...
  5. Create a gruntfile. ...
  6. Run Grunt.
4 Mar 2019

How to check unused CSS online? ›

The Coverage tab in Chrome DevTools can help you find unused JavaScript and CSS code. Removing unused code can speed up your page load and save your mobile users cellular data.

How to remove CSS from HTML? ›

Use the style. removeProperty() method to remove CSS style properties from an element, e.g. box. style. removeProperty('background-color') .

What can you do with unrecyclable waste? ›

Waste that can't be recycled, or isn't biodegradable can be used as fuel in EfW (energy from waste). These facilities burn waste, the process produces steam which is used to make electricity by powering a steam turbine. That turbine in turn generates heat for local businesses and homes.

What are my least used apps? ›

From the Settings app, tap Apps, and then, from the Apps page, tap Unused Apps. Accessing the Unused Apps feature in Android 13.

Is removing cache good? ›

It is a good idea to clear your browser cache because it: prevents you from using old forms. protects your personal information. helps our applications run better on your computer.

Is clearing cache risky? ›

Generally speaking, yes it is safe to clear your browser cache... When you clear your browser cache, you are simply telling your web browser to delete the temporary files that it has automatically downloaded in order to show you a website.

Is clearing cache harmful? ›

You should clear cached data on Android periodically, depending on how heavily you use your Android device. Obsessively clearing your Android cache would be counterproductive, since the point of saving temporary files is to make your regular app experience smoother.

How do I remove all CSS from a website? ›

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

How do I remove CSS style from my website? ›

Open the webpage. Click on the extension icon in your browser's toolbar. Select CSS tab. Disable All CSS: click on Disable All Styles to turn off and on all style formats.

Why is my CSS file so big? ›

CSS files can contain unnecessary characters, such as comments, whitespaces, and indentation. In production, these characters can be safely removed, to reduce file size without affecting how the browser processes the styles. This technique is called minification.

What is a good CSS file size? ›

If you are clever about it, it won't be much larger than 15kb. Ideally you are the designer and it matches your design/pattern library. If not, then you are a developer and you work closely with the designer to define all the CSS classes. The reason I say that: CSS is design .

What is too big for a CSS file? ›

For comparison, a good size CSS should be under 150KiB, perhaps 200KiB maximum. In the case that your CSS is over that, you may have some optimizations you can do. A few points of optimization: Unused CSS.

How do I remove a specific CSS property? ›

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 to remove unused CSS and JS in WordPress with plugin? ›

Removing Unused CSS and JavaScript With a WordPress Plugin
  1. Install the Plugin. The first thing you need to do is install the plugin. ...
  2. Enable Test Mode. Before starting to remove unused CSS and Javascript code, you need to switch your WordPress site to test mode. ...
  3. Start Unloading CSS and JavaScript. ...
  4. Test and Commit.
11 Jan 2022

Should you remove unused code? ›

First of all you should always use a source control tool to manage your projects and hence removing unused code is a good practice as you can always go back using source control to get the removed code.

How to deactivate CSS? ›

To disable CSS , the easiest way is to install the "Web developer toolbar" extension for FireFox or Chrome (https://chrispederick.com/work/web-developer/). Once this is in place, click on the "CSS" menu, then "Disable all styles".

Can you remove a school from CSS? ›

Updating Colleges/Programs and other data - You can add and/or remove colleges and programs at any time before you submit your application. Additionally, you can change data until you submit your application.

What is meant by dead code? ›

In some areas of computer programming, dead code is a section in the source code of a program which is executed but whose result is never used in any other computation. The execution of dead code wastes computation time and memory.

How do I reduce unused JavaScript and CSS? ›

If your website is running on WordPress, you can remove the unused JavaScript from its pages using special plugins. For example, you can use AssetCleanUp, which also allows you to disable unused JavaScript files. Another option is to detect unused JS with Chrome DevTools and delete unnecessary files.

What is the easiest clean code to read? ›

Clean code is a reader-focused development style that produces software that's easy to write, read and maintain. Knowing how to produce clean code is an essential skill for software developers. Often, you may be tempted to consider your work complete when the application operates as expected.

What is unset CSS? ›

The unset CSS keyword resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.

What is reboot in CSS? ›

Reboot, a collection of element-specific CSS changes in a single file, kickstart Bootstrap to provide an elegant, consistent, and simple baseline to build upon.

How do you refresh a CSS page? ›

Anytime you make changes to CSS, JavaScript and are viewing the page you've updated - you will see this concern. You can force a refresh by pressing CTRL+F5 on the browser and that will get the latest version.

How do I remove CSS from Chrome? ›

For Chrome: Open Dev Tools (inspect element). Go to "network" tab. Select any css file and right-click: "Block request url".
...
  1. Open Developer Tools ( CTRL + SHIFT + I )
  2. Select the Style Editor tab.
  3. There you should see all sources of CSS in your document. You can disable each of them by clicking the eye icon next to them.

How do I disable all CSS on a page? ›

Open the webpage. Click on the extension icon in your browser's toolbar. Select CSS tab. Disable All CSS: click on Disable All Styles to turn off and on all style formats.

What are the 3 methods of CSS? ›

CSS can be added to HTML documents in 3 ways:
  • 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 did CSS stand for? ›

CSS is the acronym of “Cascading Style Sheets”. CSS is a computer language for laying out and structuring web pages (HTML or XML).

References

Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated: 08/06/2023

Views: 5538

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.