Cleaning up the CSS codebase. Tools for finding unused CSS styles

4 out of 5

Many developers are faced with the fact that after some time working on a project, in files CSS styles appear, about which it is impossible to say for sure whether they are used or not. This often happens when you are working in a team and more than one person is working on the styles. Or, for example, there were several developers before you, and you decided to change something, or the designer conceived a small redesign. In general, there are many options, but the result is the same - "dead" selectors are given to the browser.

Everything would be fine if there are one or two of them, but if your file contains five to six thousand lines, then there is no doubt about it - not all selectors are used, which means that by removing unnecessary ones, you can lighten files and speed up page loading. Today we will consider various programs, plugins and services for cleaning CSS files from unnecessary styles.

Firefox extensions

Considers styles included in the page through , @import and... It can analyze both a single page and the entire site. At the end, you will receive a list of selectors that are not used on the site.

This is an extension for FireBug that allows you to find unused selectors both on a single page and throughout the site. In total, you will receive a list of all your selectors, among which those marked in red will be unused.

Web services

Online tool to check which of the selectors of this file are not used on specific pages of the site. The downside is that you cannot evaluate the entire site as a whole (or rather, you can, but it is long and inconvenient).

Desktop editors

A list of code editors who, in one way or another, are able to find unused CSS styles.

TopStyle (Win)

This one can also find selectors that are used on pages, but for which there is no description in the CSS files.

IntelliJ IDEA (Win, Mac, Linux)

A cross-platform editor designed primarily for working with Java.

Conclusion

In my opinion, the most successful of these tools is Dust Me. Analyzing the entire site takes less than a minute, after which you just need to find and remove the specified selectors.

By the way, if one of you uses an editor or service that is not on this list, then write in the comments, I will add. Thank you all for your attention ;-)

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. There is only one thing you can do: clean up this whole mess. Have you encountered something similar before? Almost certainly, sooner or later, everyone is faced with this.

You know that cleaning up CSS is a big task. There is a lot that needs 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 figure out a codebase is linting. Linting is the process of running a program that looks for potential mistakes and bad practices. I believe that making our code clean is 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 differently.

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 specifying 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 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 (my preferred) 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 for search regular expression\ s + \. (\ d +) (all digits following a space with a period), and to replace \ 0. $ 1 (space, zero, period and the number found). 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. As easy as pie!

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 replacement, 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 indentation, 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 is important to do this before moving on to it.

Translator's note

Some of these things can be done with the SassBeautify plugins at 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 move on to the abstracts directory. All variables, mixins, functions and placeholders should be located here. You are free to arrange them however you wish until you have dealt with 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>: first-child (margin-top: 0;) .quote>: last-child (margin-bottom: 0;)

Try to think in modules. Smaller. Simpler. Independent.

Removing excess

I believe that 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 the real plague of CSS. 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, which is no longer necessary, 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 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. Consider this with the following succinct 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 the "C" in the abbreviation CSS.

CSS is smart and you should be no worse

Lack of understanding of inherit, initial and currentcolor values ​​is 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 the 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 it to a fixed value. The CSS provides an initial value for such cases. It usually does not differ from setting fixed values, but there are cases where it does play a role, for example, when determining the direction of text in the text-align property. When you reset text-align, the left value can mess up the text in RTL languages ​​(directed from right to left), the output will be exactly initial (even better start, but this value is not supported in IE9) /.

The last but not the least important value is currentcolor, which many developers do not know about it. 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 what it is. And these opportunities are surprisingly rarely used. Therefore, if you decide to improve the component code, you should 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 is 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 buggy code 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 difficult because it is difficult to immediately assess the full impact of a change or deletion. CSS strings... 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 the same good way reviewing the state of your code without 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 delete, 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 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!

Hello dear readers of the blog site. This is a small note from the series "to myself as a keepsake." There was an idea to remove extra lines from the stylesheet. Over the seven years of the blog's existence, a lot of things have changed, but the lines in the STYLE.CSS file remained (just in case, or simply forgot to remove them). Now it seemed to me that it began to weigh too much, and therefore the idea arose to clean it.

Doing this manually is quite difficult and unnecessary. There are ways this process automate. Some of them did not work for me, I had to pay for something and I considered it unnecessary. In the end, I used the semi-automatic method, which I will write about in the next few paragraphs. Looking ahead, I can say that I managed to reduce the size of the CSS file almost in half, which even surprised me a little.

Search options for CSS styles that are unnecessary for the site to work

Replacing the style file (its contents - the old deleted, and the new inserted, and then saved the changes through the file) with a new (broken) visible changes on the site did not cause (so far, in any case, did not reveal). All in all, I am very satisfied and recommend giving it a try. Fast, simple and convenient (and also free).

Good luck to you! See you soon on the pages of the blog site

you can watch more videos by going to
");">

You may be interested

How to increase website loading speed to the maximum and optimize server load
CSS - what is it, how cascading style sheets are linked to html code using Style and Link
Optimizing and Compressing CSS in Page Speed ​​- How to Disable external files styles and combine them into one to speed up loading How to set the alternation of the background color of the rows of tables, lists and other Html elements on the site using the nth-child pseudo-class
What is CSS for, how to connect cascading style sheets to Html document and the basics of the syntax of this language
List style (type, image, position) - Css rules for customization appearance lists in Html code
How to get a fast website - optimization (compression) of images and scripts, as well as reducing the number of Http requests

From the author: It's tricky to talk about monolithic styles, as CSS files tend to be bloated a lot. 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 truncated so 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 there is already a built-in feature in Chrome developer tools. I tested it on a site that I knew had a lot of styles to remove. 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. Really useful function, since we only need the styles that we wrote. At least within the scope of this article.

Is it good?

I have not found super easy way 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 the code, which may lead to the fact that we 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 inserted 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 run npm install uncss on Ubuntu. Nothing serious, it turns 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 inserting it into the build process is not the most good idea... Addy Osmani has a good article on this topic. Ideally, we want to remove unused styles right from the code, not just filter them for the final product.

Perhaps the best way out is to do both. First, run it as a prebuild 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/> unused-styles.css

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

The result is split into site styles your-site.com and Chrome browser but are stored in a single file. My site has font-awesome and all icons that are not used on home page, got into 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 by using -t N, where N is the number of milliseconds (do not use -t 360 to later wonder 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, sites in WordPress, where various plugins can pull their own styles, but the developer only needs the theme's style.css, etc.

Which tool should you use?

First, I gave the choice to UnCSS and 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 delved into the problem yet, but maybe more a new version PostCSS forgives such comments. However, right now this has become another barrier and I cannot fully use UnCSS in my work.

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 the following solutions:

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

Regarding 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, a letter will come in a day that there is already a result and it can be downloaded from the link (go and you will be prompted 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 will 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 broom icon will appear in the lower right corner.

After the extension crawls the page, a window will open 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 the document and clear the 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 versions 1.5 and higher (this is also a scam [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 be useful to us for the next add-on. CSS Usage so 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 catalog can be found here. Until recently, for the extension to work, you had to install Firefox version 3.6.25, and at the time of this writing, the Author, as it were, woke up or woke up and updated the add-on, so you can bet on latest version Mozill's. 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, you need to 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 new page then more on that 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 obtained 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 auto-scanning of 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 to use (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 correspondingly)
  • 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 operation (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 result of the crawl:

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 there will be an UNUSED tag:

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 rules which 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 shenanigans using 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 find out 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.

Did you like the article? To share with friends: