Search and remove unused css styles. Tools for finding unused CSS styles


The created site will constantly expand, and one day you will realize how difficult it is to understand its CSS.

If you have already encountered similar problem, then it's time to audit your CSS code and optimize it. We've selected 15 tools to help you do just that. Some of them will help reduce CSS file size, others will improve page performance.

1. Type-o-Matic

Type-o-matic is a Firebug plugin that can analyze the fonts used on website pages. This plugin displays a report in the form of a table with information about the properties of the fonts used ( family, size, color and more).

Although the report is presented in tabular form, you can easily edit this list by combining or removing fonts that are similar in style.

2.CSSCSS


The tool analyzes your CSS files for duplicates. This will reduce CSS size and it is much more convenient to work with them in the future. The tool is very easy to install - it is implemented as a Ruby extension package, and can be launched from command line.

3. CSS Lint


This tool will help you identify problems in your CSS code. The tool checks the basic syntax of styles and also applies a set of rules to code that is suspicious. All rules are pluggable, so you can easily change them.

4. CSS Colorguard


Often you come across clients who want to use colors that you didn’t even know existed. CSS Colorguard will help you create the necessary color schemes, and will warn you if you use two identical colors.

5. CSS Dig


CSS Dig is a script written in Python that runs locally and allows you to analyze the CSS properties and values ​​of almost any site, regardless of whether the styles are located in a separate file or in the page code. The tool also helps you modify, standardize, and optimize your CSS code.

6. Dust Me


Dust-Me is a plugin for Firefox and Opera that removes unused selectors from the stylesheet. The tool takes all the CSS on your site and shows you which selectors are being used and which ones are unnecessary.

7. Devilo.us


Devilo.us is an advanced compression engine and CSS optimization-code that now supports CSS3.

8. PurifyCSS


The tool helps you get rid of unused CSS styles on website pages or web applications. It is able to detect even dynamically loaded CSS selectors in javascript code, and significantly compress the size of style files.

9. Atomic CSS


Atomic CSS will help you make your CSS files smaller. It allows you to optimize page loading speed, eliminates dependencies, and also does much more.

10. Clean CSS


CleanCSS is a multifunctional CSS optimizer. The tool takes your CSS code and makes it cleaner and smaller. You can optimize code written in different languages: javascript, json, python, html, etc.

11. PubCSS


The tool makes it easy to format CSS code for pages of academic publications. This is a library of CSS styles for formatting documents for printing and publishing on the Internet.

12.CSSO


CSSO (CSS Optimizer) is a tool that performs structural optimization of your CSS files.

13. Helium


Helium is a tool for identifying unused CSS properties across all pages of a website. It is javascript based and runs directly in the browser. Helium takes a list of site section URLs and then parses each page to produce a list of all the styles. Then it identifies unused CSS properties.

14. Strip Comments


Strip CSS Comments greatly simplifies the following tasks: removing comments from CSS files, reducing file sizes. It is also available as a plugin for gulp/grunt/broccoli.

15. CSS Shrinks


The tool allows you to easily optimize CSS files while maintaining the consistency and format of the markup. It has several tools that allow you to remove spaces and comments from a document.

Do you have any other useful CSS tools in mind? Please share them in the comments!

Translation of the article “ 15 CSS Tools to Audit and Optimize Your CSS Code” was prepared by the friendly project team

  • Translation

This article is the first in a series on the topic of taming CSS. Today we will look at technology CSS Reset.

Why is this necessary?

Each browser sets its own default style values ​​for various HTML elements. WITH using CSS Reset we can level out this difference to ensure cross-browser compatibility of styles.

For example, you use the element a in your document. Most browsers like Internet Explorer and Firefox, add a link Blue colour And underlining. However, imagine that five years later someone decided to create new browser(let's call it UltraBrowser). The browser developers didn't like the blue color and were annoyed by the underline, so they decided to highlight links in red And bold. It is on this basis that if you install base value styles for the element a, then it is guaranteed to be the way you want it to be, and not how the UltraBrowser developers prefer to display it.

But now we have no indents at all, including between individual paragraphs! What to do? Don’t lie and don’t be afraid: below our reset we will describe the rule we need. This can be done different ways: specify the indent at the bottom or top of the paragraph, specify it in percentage, pixels or em.

Most importantly, the browser now plays by our rules, and not we by its rules. I decided to do it this way:

* ( margin: 0; padding: 0; ) p ( margin: 5px 0 10px 0; )

As a result, we got what can be seen in the third example.

You can create your own reset styles if you are solving a specific problem in your project. Despite this, there is no step by step guide on creating your own CSS Reset. Rely on your own principles and your own style.

To help you make the right choice, here are a couple more links:

  1. Less is more - my choice of Reset CSS (Ed Elliott).

2. Your CSS Reset is the first thing the browser should see

Resetting styles after setting your own styles for elements is the wrong approach. In this case, you should not expect anything good from the browser display. Remember that you should always include CSS Reset first, and then all other styles.

Yes, I understand, it sounded funny, but this is one of the main mistakes of developers, young and old. Many people simply forget about this.

Some may ask logical question: why is this happening? The answer is simple: rules written lower in the text of the CSS file (and even lower in their order in the document) overwrite the rules declared earlier.

Let's not go too far off topic and continue. Let's apply Eric Meyer's styles to our example, but after descriptions of our properties, as shown in example 4. Mathematicians would say the following: “That’s what we needed to prove.”

3. Use a separate CSS document for CSS Reset

I must (no, I was by no means forced) to mention this advice. Using a separate file for CSS Reset is a common practice that is supported by big number developers.

In fact I take the position of creation one large CSS file due to the higher performance of this approach. But on this issue I am inclined to agree with the majority: CSS Reset should be placed in a separate file (usually called reset.css). In this case, you can use it in different projects without making any effort to separate it from other CSS rules.

4. Try to avoid using a universal selector

Although this concept works, its use is often not desirable due to incompatibility with some browsers (for example, this selector is not processed correctly in Internet Explorer). You should only use this technique for simple, small, static and predictable pages (if you had to do that).

This advice is especially important when you are developing solutions such as CMS themes. You cannot predict in advance how it will be used or how it will be modified. It is better to describe fundamental CSS rules for all elements than to use the unpredictable (albeit smaller) mechanism of universal selectors for this purpose.

5. Avoid Redundant Property Descriptions When Using CSS Reset

Another reason I don't like a separate file for CSS Reset is the potential redundancy of subsequent CSS property declarations. Repeating individual styles of yours among the entire set of CSS files is bad manners and should be avoided. Of course, sometimes we are too lazy to painstakingly go through a set of styles and combine some of them, but we should at least try!

Let's go back to Eric's CSS Reset. It sets default values ​​for the element's line-height, color and background body in the following way:

body ( line-height: 1; color: black; background: white; )

Let's say you already know what the element will look like body:
  1. background-color: #cccccc;
  2. color: #996633;
  3. You want to repeat a certain background image horizontally.

In this case, there is no need to create a new selector to describe your properties - you can simply include them in the CSS Reset. Let's do it:

body ( line-height: 1; color: #996633; background:#ccc url(tiled-image.gif) repeat-x top left; )

Don't be afraid to modify the CSS Reset itself. Adapt it to yourself, make it work for you. Change, rearrange, remove and add as needed in your specific case.

Eric Meyer said the following about this: “this is not a case where everyone should use CSS Reset without changes.”

The benefits of clean and organized CSS are obvious. A website with impeccable CSS will load faster and be more visible in search results. For web developers, clean CSS code serves as a clear sign of professionalism to future clients.

But, cleaning up CSS markup debris through countless design iterations and changes can be a painstaking, time-consuming process done by hand. Luckily, there are some wonderful and useful tools, which will help you automate some of the most relevant CSS aspects. On this page there are links to CSS cleaning tools that I personally checked CSS markup 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-frills tool for instantly improving your CSS. Available via OS X, iOS, or any browser, the tool uses CSS file, pasted snippet or URL, and will immediately correct and show your CSS code to the future.

CSS Lint

CSS checking tool with explanation of changes

CSS Lint offers recommendations, unlike other CSS cleaning tools. Most of them don't even talk about CSS changes, but CSS Lint gives a short explanation for each of the recommended changes. It has a range of features that focus on bugs, compatibility, performance, deduplication and accessibility that can be turned on or off.

Dirty Markup

The 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 comprehensive cleaning code. It works just like CSS, just like JavaScript or standard HTML.

CleanCSS

CleanCSS tool performs CSS optimization

CleanCSS works with a URL or an inserted piece of code and offers a variety of CSS optimization execution. You can choose between five various settings compressions that offer trade-offs between readability and file size.

Code Beautifier

Code Beautifier simple css cleanup tool

Code Beautifier is a simple CSS cleanup tool without any unnecessary features. It processes code by URL or code insertion, and cleans 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 ​​code cleanup options, this might be your ideal CSS cleanup tool.

Spritemapper

Spritemapper generates sprites, combines multiple images into a CSS stylesheet

None of the other tools mentioned optimized images, which is just as useful as optimizing the code itself. Spritemapper generates sprites, combines multiple images into a CSS style sheet with correct positioning. The result is a faster site, less quantity HTTP requests, and a more streamlined CSS style.

Topcoat

Topcoat is not a traditional CSS cleanup tool

Topcoat is not a traditional CSS cleanup tool; it's essentially a CSS development kit, a pure CSS curation approach. If you have well-written CSS, you will probably never need to clean up the CSS code.

The 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 your existing workflow and save your CSS clean offline. W3C Valdiator CSS code validation tool

W3C Valdiator does not offer code cleanup, compression or optimization tools, but it should definitely be considered in cases where the CSS code is truly broken. The above tools have their own tools, this one is made by the W3C Consortium which creates standards.

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

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

Linting is everything to us

In this section I will assume that you are using Sass. Not only because this is a reasonable assumption under current conditions, but also because misuse Sass is often the cause of codebase pollution. 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 understand a code base is linting. Linting is the process of executing a program to look for potential errors and bad practices. I believe that by making the code clean we take the first step towards good code. The etymology of the word linting can be found in this thread on StackOverflow.

Sass has a linter written in Ruby called SCSS-lint. You can set it up 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 on your directory with Sass files to identify errors. The chances are very high that a ton of errors will fall on you. Usually after this you want to stop experimenting with code cleaning. Be patient. Now you can try to make the configuration less strict regarding rules that are not very important to you (such as the color format) or take the bull by the horns and use the full power of linting.

Correcting found errors

It's time to fix what needs to be fixed. This can be done in two ways. The first is to check all the files one by one and correct all errors and shortcomings such as unsuccessful variable naming, excessive nesting of selectors and poorly formatted code. The second (my preferred) is to use search and replace. I don't know about you, but I love it 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, from 0 to 1), these types of errors are caught using the LeadingZero rule in SCSS-lint. To do this, use the regular expression \s+\.(\d+) for search (all numbers following a space with a dot), and for replacement \0.$1 (space, zero, dot 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. As easy as pie!

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

Once you're done with find/replace editing, you won't be able to escape manual editing, in those places that need to be improved (incorrect indentations, absence or excess of empty lines, missing spaces, etc.). This takes a lot of time, but it will help you a lot in the next step, so it's important to do this before moving on.

Translator's note

Some of these things can be done using SassBeautify's plugins text editors, for example sublime or atom .

Review of the project structure

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

The choice of project methodology is not so important, the main thing is that you have it and do not cause you discomfort. It could 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 that we developed in Sass Guidelines, so I'll give you some tips to help if you choose this route.

Then let's go to the abstracts directory. All variables, mixins, functions and placeholders should go here. You're free to arrange them however you like until you've got a handle on all the variables and mixins in your codebase. I also identify optional variables (and mixins) at this stage, since I often encounter variables that are used once or twice.

Once you've figured this 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 truly base styles and not component styles. Or check that the layout directory contains everything that relates to the page layout and that this code is correctly documented.

Finally, to finish things off, you need to build the components directory, which is usually a mammoth task. I advise making components as small as possible and focusing on their reuse. It doesn't matter if you increase the number of them - as long as they are contextless 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. Less. Easier. More independent.

Removing unnecessary

I believe the biggest difference between bad and good CSS this is the amount of code. CSS is very easy to grow. Some people can do almost every layout by trial and error. The ability to do anything using minimal CSS takes work, and maintaining a minimalistic approach is a real challenge.

It's been 3 years already, but this tweet by 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 - we usually end up leaving 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, we increase technical debt. There is nothing good about this.

At writing CSS I'm used to opening the developer tools in the browser and disabling each CSS declaration one by one before submitting ready code to check what they affect. If they don’t affect anything, then the first thing I ask myself is: “Why are they here?” If they turn out to be useless, I delete them. With a simple technique like this, I can ensure that only useful code and no junk is submitted to the repository.

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

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

An obvious optimization is to move the color: red declaration to parent selector, after which cascading will do the rest for us. Certainly, real 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 just as smart

It is also very common to lack understanding of the meanings of inherit , initial and currentcolor . Let's say you want the links to be the same color as the main text (they're already fairly underlined). Here's how not to do it:

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

The reason this solution fails 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 will just make things unnecessarily complicated. And finally, if the link is placed inside an element with own style(for example, in a quote), it will not match its color.

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

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

Likewise, when returning a property to its default value, it is a bad idea to set the value to a fixed value. In CSS there is an initial value for such cases. Usually it is no different from setting fixed values, but there are cases when it really plays a role, for example, when determining the direction of text in text-align property. When resetting text-align , the value left can corrupt text in RTL languages ​​(right-to-left), the output will be initial (even better is start , but this value is not supported in IE9)/.

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

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

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

This is all basic capabilities CSS. They make CSS the way it is. And these opportunities are used surprisingly rarely. 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's likely that you'll break something in the process. Let's be honest - everyone makes mistakes and it would be incredibly cool if you managed to complete such a job without some small mistake.

Therefore, I strongly recommend that you work diligently with your 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 a step from the code with the bug without suffering from conflicts.

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

Conclusion

So, I will briefly formulate the main points 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 all mainly due to poor testability of CSS. Therefore you need to be careful.

Start with linting and your code will become prettier. Do this because it will make your life easier in the future. it's the same good way overview of the state of your code without much risk (fixing syntactic dirt should not cause any problems).

Then structure your project according to your chosen methodology. No 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 start. Find reusable parts of the interface and transfer their styles to separate files. Feel free to write documentation, this will make the process easier and you will feel like you are moving forward.

Once you've cleaned up your project and sorted out 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 reduce complexity, not increase it. Don't forget to comment on anything that isn't obvious at first glance.

And finally, your commits should be regular and logical. Combine changes into small commits, each making one simple thing- this will make it easier for you to roll back changes if you do something wrong.

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







2024 gtavrl.ru.