Is there any way to find unused CSS in a website?

2019-01-16 14:52发布

Is there any way to find unused CSS in a website?

I'm trying to clean up a project I just inherited.

5条回答
forever°为你锁心
2楼-- · 2019-01-16 15:31

Chrome 59 has built-in coverage display for CSS and JavaScript since 2017-04: https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage

You can enable it by opening the dev tools, then the command menu (Cmd+Shift+P on Mac or Ctrl+Shift+P on Windows and Linux), and then type "show coverage".

查看更多
爷、活的狠高调
3楼-- · 2019-01-16 15:35

To add to @cweiske suggestion, Google Chrome has a no nonsense way of uncovering where your "unused" and "never will be used" selectors are.

I have posted a screen capture of how to launch the CSS Coverage tool with step by step markers.

It is a reliable way to figure out where you really are not using stuff.

enter image description here

查看更多
萌系小妹纸
4楼-- · 2019-01-16 15:39

There is so much that can be said about best-practice methods for CSS. I'll try to stick to the main points.

Use a CSS reset.

Try to remove really general CSS statements like h1 {} and #container em {}. You're much better off using h1.section-title and #container em.important {}, because that way if you choose to use h1 or em a different way somewhere in your document, you don't have to worry about overriding any existing code.

Don't be too specific in your CSS selectors if you don't have to. You really only need to have high degrees of specificity if being in a specific section changes how the element is going to be displayed. Otherwise, to make your code for your block class reusable, #container .content .block ... could be reduced to .block ... in many cases.

Look for commonalities in your CSS and see if you can create reusable classes. If you have similar blocks class="favorites" and class="popular", turn it into class="block block-favorites" and class="block block-popular", and put the commonalities into .block.

Get in the habit of making areas in your CSS have an auto-width (can be done implicitly) so that they grow to the width of your containers. This makes it incredibly easier to move sections from a narrow portion of your website to a wide portion of your website without having to change any code.

Commenting your code and breaking it down into sections usually helps make code more readable.

You'd be surprised how much cleaner your code looks when you implement more powerful CSS selectors. Most of them are cross-browser compatible (Internet Explorer 7 and later).
Some valuable resources: When can I use... - Quirks Mode on CSS Selectors - w3 on CSS Selectors

Answer moved from:
Best Practices for Cleaning up Existing CSS/unused styles

查看更多
时光不老,我们不散
5楼-- · 2019-01-16 15:42

Dust-me Selectors is a Firefox plugin that finds unused selectors.

查看更多
祖国的老花朵
6楼-- · 2019-01-16 15:51

I just ran into this and remembered your question: http://github.com/geuis/helium-css

查看更多
登录 后发表回答