How automatically find out unused css in an html page and delete them?

2.2k views Asked by At

I want to have an automatical way to find unused CSS in a static HTML page (no javascript, all CSS code are embedded) and delete them.

I currently manually search for the unused CSS. But this is not efficient. It seems that there is not such a way yet. But I want to doublecheck to make sure.

EDIT: A standalone command line tool is preferred.

1

There are 1 answers

12
Laaouatni Anas On

1. purify css

use this tool at this link: https://purifycss.online/

It searches through the HTML files and the given CSS files, it removes redundant CSS styles and writes the purified CSS to another file, then re-links the HTML files to the purified CSS file.

enter image description here



2. coverage - devtools

there is functionality on devtools called "coverage"

https://developer.chrome.com/docs/devtools/coverage/

that make you see how many bytes are used,
and how many aren't.

enter image description here

you can also use it to see what selectors aren't useful!

enter image description here

the blue lines means: CSS is used
the red one means: CSS isn't used


as mentioned by @quentin

the pseudoelements, pseudoclasses are red by default.

so try to debug the normal CSS with this dev tools tool.

also for debugging you need to use first the app, then see what CSS you really used for the things, and debug.
I tried now: if you use the website also :active, :hover not become red



3. make CSS to CDN

the tool that I suggest you is jsdelivr

why cdn?

  • cache: that makes your CSS cachable for a year,

    • so you install the CSS to the device, and then the device will not install it anymore.
      saving time, and network resources.
    • there isn't any code to do, it automatically does it for you.
  • minify: the CSS code will be minified,

    • so spaces and tabs will be deleted
    • the code will be only in one line.
    • long variables, became one character vars.
  • simple: you can make every Github or npm file a CDN easily.
    like this: https://cdn.jsdelivr.net/gh/user/repo@version/file