Tools for finding unused CSS styles

You have just joined an existing project to replace a departing developer. Or maybe they just took up their old project a few years later. You feel horror and disgust when you look at the code. You can only do one thing: clean up this whole mess. Have you encountered something similar before? Almost certainly, sooner or later, everyone faces this.

You know that cleaning up CSS is a big task. There is a lot to be done in a limited time - especially when clients / bosses / colleagues strongly advise not to touch what works. You don't even know where to start.

Linting is our everything

For this section, I'll assume you're using Sass. And not only because this is a reasonable assumption in the current environment, but also because misuse of Sass is often the cause of codebase contamination. Although this article will be useful for those who do not use preprocessors, so you should read it to the end.

The first thing I'm used to doing when I need to deal with the codebase is linting. Linting is the process of executing a program looking for potential mistakes and bad practices. I believe that by making our code clean we are taking the first step towards good code. The etymology of the word linting can be found in this thread on StackOverflow.

Sass has a Ruby linter called SCSS-lint. You can customize it yourself, or download the configuration recommended by Sass-Guidelines to get started right away. Also Node.js has sass-lint, they are not 100% compatible and may work in different ways.

Try running SCSS-Lint in your Sass directory for errors. Chances are very high that you will get a ton of mistakes. Usually after that you want to stop experimenting with code cleaning. Be patient. Now you can try to make the configuration less restrictive with regards to rules that are not very important to you (such as the format for defining colors) or take the bull by the horns and use the full power of linting.

Correction of found errors

It's time to fix, what needs to be fixed. This can be done in two ways. The first one is to check all the files in turn and fix all errors and shortcomings such as unsuccessful naming of variables, excessive nesting of selectors and poorly formatted code. The second one (my preferred one) is using find and replace. I don't know about you, but I love regular expressions and I always like to use them in my work.

Suppose you want to add a missing zero in all floating point numbers (that is, 0 to 1), errors of this type are detected using the LeadingZero rule in SCSS-lint. To do this, use the regular expression \\ s + \\. (\\ D +) to search (all digits following a space with a period), and to replace \\ 0. $ 1 (space, zero, period and the found number). And if you are concerned about the BorderZero linter rule, then you can replace all border: none rules with border: 0 in your editor using search / replace. Easy peasy!

I recently created the scss-lint-regex repository on GitHub to collect all the regexes for linting in one place. Be sure to take a look at it if you're having problems with linting on a large project. And be careful with find / replace, sometimes it leads to unexpected side effects. After each change, run a git diff to find out what has changed, this will ensure that you don't add bugs to your code.

After you finish editing with search / replace, you will not be able to avoid manual editing in those places that need to be refined (wrong indents, absence or excess of blank lines, missing spaces, etc.). It takes a long time, but it will help you a lot in the next step, so it's important to do this before moving on to it.

Translator's note

Some of these things can be done with SassBeautify plugins in text editors like sublime or atom.

Revision of the project structure

What really worries me a lot when I join an existing project is the lack of proper project architecture. Perhaps at the very beginning of the work there was some kind of project, but over time things get out of control and the original idea is lost. But it's still incredibly important.

The choice of the project methodology is not so important, the main thing is that you have it and not cause you discomfort. It can be SMACSS, 7-1 or ITCSS - the choice is yours. Try to restructure your code according to your chosen methodology. I tend to use the 7-1 pattern we developed in Sass Guidelines, so I'll give you some tips to help you if you choose this path.

Then let's go to the abstracts directory. All variables, mixins, functions and placeholders should be located here. You are free to arrange them however you like, until you understand all the variables and mixins in your codebase. At this stage, I also identify optional variables (and mixins), because I often have to deal with variables that are used once or twice.

Once you've figured it out, you'll have to decide which of the next two steps to take first. You can try to ensure that all the contents of the base directory are really core styles, not component styles. Or check that the layout directory contains everything related to page layout and that this code is correctly documented.

Finally, you need to tackle the layout of the components directory, and this is usually a huge task. I recommend making your components as small as possible and aiming for reusability. It doesn't matter if you increase their number - as long as they are context independent and easy to read, understand and update.

As an example of a correct and small component, I can give the following:

Quote (padding: 10px;) .quote__attribution (font-size: 80%;) .quote\u003e: first-child (margin-top: 0;) .quote\u003e: last-child (margin-bottom: 0;)

Try to think in modules. Less. Easier. Independent.

Removing excess

I believe the biggest difference between bad and good CSS is the amount of code. CSS grows very easily. Someone can do almost every layout by trial and error. Being able to do anything with a minimum of CSS takes work, and keeping a minimalist approach is a real challenge.

It's been 3 years now, but this tweet from Nicholas Gallagher remains my favorite CSS question:

Deprecation is a CSS plague. When writing styles, we often go back and forth trying new rules - in the end, we tend to leave a few completely unnecessary declarations. For example, overflow: hidden, no longer needed, or font-size, which does not change the font size. By leaving them behind, we are increasing technical debt. This is not good.

When writing CSS, I'm used to opening the developer tools in the browser and disabling each CSS declaration one at a time before submitting the finished code to check what they affect. If they don't influence anything, then first of all I ask myself: “Why are they here?”. If they turn out to be useless, I remove them. With a technique as simple as this, I can ensure that only useful code is submitted to the repository without garbage.

Clearing the CSS codebase is the same technique. Identify the component you want to clean up, open up the developer tools and try to find useless declarations. Sometimes, to remove CSS code, we need to move those styles up the tree to take advantage of the cascade. Let's consider this with the following concise example:

Parent (/ * ... stuff here ... * /) .child-A (color: red;) .child-B (color: red;)

The obvious optimization is to move the color: red declaration into the parent selector, and then cascading does the rest for us. Of course, real-life examples are usually more complex, but this example also shows that you should not forget the possibilities of "C" in the abbreviation CSS.

CSS is smart and you should be no worse

Lack of understanding of inherit, initial and currentcolor values \u200b\u200bis also very common. Let's say you want the links to be the same color as the body text (they are already underlined enough). Here's how not to do it:

A (color: black; / * Nope * /)

The reason this solution is unfortunate is obvious: if you change the body color, the link color will be out of sync with it. If you think about using a variable, it just makes things unnecessarily complicated. And finally, if a link is placed inside an element with its own style (for example, in a quote), it will not be the same color.

There is a built-in way to solve this problem in CSS, this is the inherit value:

A (color: inherit; / * Yay! * /)

Likewise, when returning a property to its default value, it is a bad idea to set a fixed value. The CSS provides an initial value for such cases. This is usually no different from setting fixed values, but there are cases where it does play a role, such as when defining the direction of text in the text-align property. When you reset text-align, the left value can mess up text in RTL languages \u200b\u200b(directed from right to left), the output will be just initial (even better start, but this value is not supported in IE9) /.

Last but not least, the value is currentcolor, which many developers don't know about. If you are one of them, do not worry, just ask yourself: “If you did not set the border color of the elements, then why does it automatically match the font color of the element?”. Yes, this is because the default border-color property is set to currentcolor (spec). Agree, everything is obvious from the title.

In my opinion, if you want to use the font color of an element, you should use currentcolor instead of a fixed value or a Sass variable.

Element (color: deeppink; border: 1px solid; / * Color is implicit with `currentcolor` * /) .element svg (fill: currentcolor; / * Fill color will be same as text * /)

These are all basic CSS features. They make CSS the way it is. And these opportunities are surprisingly rarely used. Therefore, if you decide to improve the component code, do not neglect them.

Your Git should be fine

Refactoring a CSS codebase is a lot of work. You will have to update dozens of files. And it's very likely that you will break something in the process. Let's be honest - everyone makes mistakes and it would be awesome if you can get this job done without any small oversight.

Therefore, I strongly recommend that you work diligently with the version control system (it is logical to assume that Git plays this role). This means that all commits do one single thing - ensure that you go back one step from the code with a bug without suffering from conflicts.

I know that many people find Git difficult and difficult to understand, and ways to easily master it are beyond the scope of this article. Trust me: your Git story should be like a poem if you don't want your brain to boil over.

Conclusion

So, I will briefly formulate the main theses of the article for those who are too lazy to read the entire text:

Cleaning up a CSS / Sass project is tricky because it is difficult to immediately appreciate the full impact of changing or deleting a line of CSS. This is mainly due to the poor testability of CSS. Therefore, you need to be careful.

Start by linting and your code will be prettier. Do it because it will make your life easier in the future. It's also a good way to view the state of your code without too much risk (fixing syntactic gunk shouldn't cause any problems).

Then structure your project according to your chosen methodology. It doesn't matter which one you choose, it is important that you follow it. If your project doesn't have too many components, then structuring is a good place to start. Find reusable UI snippets and transfer their styles to separate files. Feel free to write the documentation, this way the process will go easier and you will feel like moving forward.

After you've cleaned up the project and organized all the components, it's time to improve the CSS. First check what you can remove, because we always write too much code. Then try to optimize it so that it is less repetitive. Don't overdo it! Your job is to decrease the complexity, not increase it. Do not forget to comment on anything that is not obvious at first glance.

Finally, your commits should be consistent and logical. Combine your changes into small commits, each of which does one simple thing - it makes it easier for you to roll back your changes if you do something wrong.

Last but not least, don't forget to celebrate when it's over. Good luck!

The benefits of clean and organized CSS are clear. A site with flawless CSS will load faster and be more visible in search results. For web developers, clean CSS is a testament to professionalism and future customers.

But, cleaning up CSS markup in countless design iterations and changes can be a painstaking, time-consuming manual process. Fortunately, there are some great and useful tools out there to help you automate some of the most relevant aspects of CSS. On this page, there are links to CSS cleaning tools, personally I checked the CSS markup of the site on all the tools below, I advise you to do the same.

CSS cleanup tools

ProCSSor to improve your CSS

ProCSSor is a simple, no-nonsense tool for instant CSS enhancements. Available through OS X, iOS, or any browser, the tool takes the CSS file, inserted snippet or URL, and immediately corrects and displays future code for your CSS.

CSS Lint

CSS validator with explanation of changes

CSS Lint offers guidelines, unlike other CSS cleanup tools. Most of them don't even talk about CSS changes, but CSS Lint does provide a short explanation for each recommended change. It has a variety of features that focus on bugs, compatibility, performance, de-duplication, and accessibility that can be enabled or disabled.

Dirty Markup

Dirty Markup tool combines several different technologies

Dirty Markup has a unique approach to code optimization; it works when the field is filled with code and combines several different technologies HTML Tidy, JavaScript, Ace Editor, and makes complex code cleanup. It works just like CSS, like JavaScript or standard HTML.

CleanCSS

CleanCSS tool performs CSS optimizations

CleanCSS works with a URL or an embedded code snippet and offers a variety of CSS optimizations. You can choose between five different compression settings, which offer trade-offs between readability and file size.

Code beautifier

Code Beautifier simple CSS cleanup tool

Code Beautifier is a simple CSS cleanup tool with no unnecessary features. It parses the code by URL or injecting the code, and scrapes them thoroughly based on a practical variety of options. If you need to quickly clean up your CSS without getting lost in a sea of \u200b\u200bcode cleanup options, this might be your perfect CSS cleanup tool.

Spritemapper

Spritemapper generates sprites, merges multiple images into a CSS stylesheet

None of the other tools mentioned have optimized images, which is as useful as optimizing the code itself. Spritemapper generates sprites, merges multiple images into a CSS stylesheet with correct positioning. The result is a faster site, fewer HTTP requests, and more streamlined CSS.

Topcoat

Topcoat is not a traditional CSS cleanup tool

Topcoat is not a traditional CSS cleanup tool; it is essentially a CSS development kit, a pure CSS curated approach. If you have well-written CSS, you probably never need to clean up your CSS.

CSSTidy tool runs on Windows, Mac, or Linux platforms.

CSSTidy is similar to many CSS cleanup tools, but this one offers some unique attributes. CSSTidy can be invoked using the command line or PHP, and it runs on Windows, Mac, or Linux platforms. CSSTidy-cleanup tool can fit perfectly into existing workflow and keep your CSS clean offline. W3C Valdiator CSS Code Validation Tool

The W3C Valdiator does not offer tools for cleaning, compressing, or optimizing code, and should definitely be considered in cases where the CSS is indeed incorrect. The above tools have their own tools, this one is made by the W3C which creates standards.

Sooner or later, every front-end (layout designer) is faced with the task of checking the entire site for unused CSS rules. The first thing that comes to mind is to google and find some service or program that will do all the dirty work for us.

In short, I sweated, and found such solutions:

  • paid service unused-css.com
  • DustMe Selectors - FireBug extension for Mozilla
  • CSS Usage - FireBug extension for Mozilla

As for the paid service, you will go to the site, enter the site address for verification and click OK. They will write to you that the result will be sent to the mail, as a result, in a day you will receive a letter that there is already a result and it can be downloaded from the link (go and you will be asked to pay to download the result of the check). But we are not looking for easy toll routes, and we want to be able to do everything with our own hands, so we will leave the paid result to someone else.

So let's start with what software we need. First of all, we need Mozilla Firefox. After Firefox is installed, we embed the FireBug add-on into it.

Dust Me Selectors

There are no Dust Me Selectors add-ons in the official directory of browser add-ons, you can install it by clicking on the link and clicking the Install Now button (of course, you need to open the link with FireFox). The add-on was installed, the browser was restarted and a pink broomstick icon will appear in the lower right corner.

After the extension crawls the page, a window opens with three tabs: Unused selectors (unused rules), Used selectors (rules that are used) and Spider log (spider - site crawling). There are two buttons at the bottom: save document and clear scan result.

Now a little more about Spider log. It is required to enter the site address or sitemap address and press the GO! In theory, everything is clear and everything should work, but no matter how I wanted the result, the result did not work, or rather it turned out to scan a couple of pages and the addition hung, which was very sad, in a word, some kind of failure. The author claims that for the add-on to work, Mozilla version 1.5 and higher is needed (this is also a cheat [huh] I installed it, but everything works, but still not as it should be). In principle, this is the only negative and the most significant, because it was necessary to check the entire site, but it is checked for a long time (I killed half a day in this trash). The most positive thing is that if you enter the name of the site, then the add-on will build a sitemap, and it will come in handy for the next add-on CSS Usageso be sure to save your sitemap.

In principle, if you need to check one page, then this extension will help you perfectly, I will also note such a minus that every time you open the add-on, the page is scanned all the time, in short, the extension management is not very convenient, so I scored on it.

CSS Usage

The CSS Usage add-on in the official directory can be found here. Until recently, for the extension to work, you had to install Firefox 3.6.25, and at the time of this writing, the Author seemed to wake up or wake up and update the add-on, so you can put on the latest version of Mozilla. After you install this add-on and restart your browser, feel free to go to the site you want to check and as soon as the page loads, feel free to press the F12 button (the FireBug window will open) and there you will see the CSS Usage tab:

To check the page for unused rules, click the Scan button (scanning takes 30 seconds, or even less). At first glance, it seems that this extension scans only one page, what to do with the rest of the pages you ask. And remember we saved the sitemap using the Dust Me Selectors extension, although if the checked site has an html sitemap, then it is better to use it, if it is not there, then create a new site page and insert the sitemap from the Dust Me Selectors extension (if there is no possibility create a new page (see below).

Now I will describe the sequence of actions for scanning:

  1. open html sitemap
  2. press F12 - FireBug opens
  3. go to the CSS Usage tab
  4. press the AutoScan button
  5. refresh the page (press F5)

As a result, we got the first scanned page. You can save the result, or you can continue scanning further. I suggest you continue. It is easy to continue scanning, we no longer need to select anything (since we have chosen to auto-scan pages), but simply follow the first link in the sitemap (you do not need to open the link in a new window, all actions must take place in one window).

At the very beginning of the scanned page, the following symbols are indicated:

  • Line - the line of the rule
  • CSS Selector - CSS rule
  • Seen - the CSS rule used (in light green)
  • Seen before - previously used CSS rules (in dark green)
  • Unseen - unused CSS rules (in red)
  • : hover - CSS rules for elements that received focus (grayed out)
  • (2 scans) - the number of scans is shown (if you scanned the current one page, then the number 1 will be accordingly)
  • export cleaned css - save scan result

You can continue scanning further, although you will have to return to the sitemap (first minus). There is no need to rush to click, it is important that the page loads completely, you will see the autoscanning work (that is, the scan result will be displayed in the FireBug window).

The extension checks all included style files. If there are a lot of CSS rules on the site, you will have to scroll the wheel to see the crawl result:

This result is output after each style file if there is more than one.

When all pages are scanned, click on the export cleaned css link, the result will open in a new tab, select everything and save it to a file with the .css extension, before each unused rule the UNUSED tag will be indicated:

The second disadvantage of this scanning method is that this extension does not scan the pop-up (modal) windows of the site, it's a pity, so you'll have to copy the CSS rules for modal windows.

Despite the two minuses, in my opinion this is the coolest method for checking a style file for unused CSS ruleswhich exists today.

I used it to optimize two style files with a total weight of 360Kb - 18000 lines, I was shocked when I saw it. After all the manipulations with this method, we got one style file - 90Kb and 1100 lines, everyone was happy with the result, and so was I. True, the solution was sought for a long time, next time everything will be much faster, which is very pleasing.

I almost forgot. What to do if it is not possible to create a page with a sitemap? In this case, you will have to insert each link from the sitemap into the address line with handles and everything will work fine.

And by the way, if you have chosen the WordPress content management system, then in this article you can learn how to make a sitemap for it.

I also note that the paid service sends the scan result within 24 hours, and if there are 10 or 20 page templates on your site (resource), then your check will take much less time than you will spend to wait for the result from them. But, if the site has a huge number of pages and different templates are used for them, of course it is advisable to pay some $ 25 for such a service.

I hope you find this method of checking your stylesheet helpful.

From the author: It's tricky to talk about monolithic styles, as CSS files are usually bloated. Removing unused CSS should get things back on track. Before we start looking for unused styles, it's worth noting that there are many other strategies for writing maintainable styles. Our styles can be divided into logical parts (page layout, buttons, grids, widgets, etc.) and use an understandable naming system (for example, BEM). Typically, developers do this even before looking for unused rules. I think that's right, because styles have a long-term impact.

Another reason why rules are not trimmed very often is that it is simply inconvenient to find and remove unused styles in anything larger than a small web project. If the content isn't static, how do you know which rules are being used and where?

Chrome developer tool

It turns out that Chrome's developer tools already have a built in feature. I tested it on a site that I knew had a lot of styles that could be removed. The feelings were mixed. The entry threshold is very low, especially for developers who have already worked with the Chrome developer bar. You don't need to install anything, it's nice.

What you need to do to check the styles on the site:

Open the site of interest

Open the developer panel

Go to the audits tab

Select the Web Page Performance option and run

Part of the results will include “Remove unused CSS rules”. If not, then you have no unused styles. Congratulations! The result is broken down by style. The breakdown is not just by files, but by style blocks. A really useful function, since we only need the styles that we wrote. At least within the scope of this article.

Is it good?

I haven't found a super easy way to export the result from Chrome. You can copy directly from the block, but you need to expand it first. This makes parsing the results a little awkward. Running the test in a browser pushes us even further away from working with code, which may lead us to forget to test the site.

Takeaway: Helpful to start with, but not a long-term solution.

UnCSS

You can use command line tools to find unused styles. UnCSS is an interesting instance. It pulls the page through phantomJS and catches styles injected through JS. I really wanted to try this tool, as it solved my problem, because the Chrome developer panel is not at all related to editing code. With UnCSS, the result can be saved directly to a file, perfect.

Installation

I was unable to execute npm install uncss on Ubuntu. Nothing serious, it turned out I forgot a couple of dependencies. The commands I ran to install the missing libraries:

sudo apt-get update sudo apt-get install build-essential chrpath libssl-dev libxft-dev sudo apt-get install libfreetype6 libfreetype6-dev sudo apt-get install libfontconfig1 libfontconfig1-dev

sudo apt - get update

sudo apt - get install build - essential chrpath libssl - dev libxft - dev

sudo apt - get install libfreetype6 libfreetype6 - dev

sudo apt - get install libfontconfig1 libfontconfig1 - dev

UnCSS can be integrated into the build process, but we'll skip that for now. I think it's not a good idea to include it in the build process. Addy Osmani has a good article on this topic. Ideally, we want to remove unused styles directly from the code, not just filter them for the final product.

Perhaps the best solution is to do both. First, run it as a pre-build step to optimize your code. Second, run a build step to optimize styles that you have no control over.

Using the command line

uncss http://your-site.foo/\u003e unused-styles.css

uncss http: //your-site.foo/\u003e unused-styles.css

The result is split into the styles of your-site.com site and the Chrome browser, but stored in one file. My site has a font-awesome font and all icons that are not used on the home page ended up in the UnCSS output. It doesn't matter to me now. They can be hidden by running the command again and specifying ignoreSheets.

Note that ignoreSheets can accept a string (full URL of the style to be ignored) or a regular expression. Regular expression is easier because there are fewer characters and it covers possible changes to the file path.

IgnoreSheets /.*font-awesome.min.css/

This is the error message that pops up when the page timeouts. The timeout can be increased with -t N, where N is the number of milliseconds (do not use -t 360 to wonder later why the code did not wait 5 minutes).

Conclusion: UnCSS is more convenient as it is closer to the place where I edit the styles. The output file is useful for eliminating unnecessary styles. I see a use for it because of the –includeSheets option, which automatically ignores everything that comes under the regular expression. Convenient for, for example, WordPress sites, where various plugins can pull their own styles, but the developer only needs the theme styles style.css, etc.

Which tool should you use?

At first I gave the choice to UnCSS and a convenient command line. However, while I was writing this article, I tried them on a couple more sites and got less promising results. In particular, I have several sites created a couple of years ago that use a framework that uses persistent comments / *! * ... * /. They don't work well with PostCSS, so they don't work well with UnCSS. I haven't gotten into the problem yet, but perhaps the newer PostCSS version forgives such comments. However, right now this has become another barrier and I cannot fully use UnCSS in my work.

Did you like the article? To share with friends: