How to find and remove dead CSS
- Publish Date
- Justin Searls
- Orlando, FL
Do you have a pile of old CSS styles that you’re pretty sure are no longer referenced anywhere, but that you’re nevertheless afraid to delete because you have no way to be sure that no musty corners of your site somehow depend on them to render correctly?
I’ve been saying for years that the most valuable uses for code coverage have nothing to do with testing, and today I was happy to add another great use case: gaining confidence over which styles are actually safe to delete. The approach in this screencast shows a way to record and combine the code coverage results for our site’s CSS across each web page.
Other automated approaches for identifying dead styles exist, but modern CSS has introduced so many context-dependent selectors (e.g. media queries and pseudo-elements) that nothing can beat recording coverage while manually resizing and clicking around your custom components like only you know how.
Stuff covered in this video:
- How we use our static-rails gem to host our static blog & website inside a Rails API monorepo
- CSS Tricks' overview on this topic
- A tutorial on Chrome’s DevTools Coverage drawer
- The DisCoverage Chrome extension for munging multiple coverage exports