Removing unused CSS in a Django template-based project

Bevan Steele
Rock and Null
Published in
2 min readFeb 4, 2023

When productionizing a web app there are many best practices you can do to improve the performance of the deployed app. One of those best practices is to purge all the unneeded CSS classes and elements for quicker download times, and potentially faster performance when the browser is parsing through the CSS file (this is especially important in bigger sites where a huge CSS file might make the site perform slow).

This is almost a trivial task if you are working with a modern client-side JS framework. But if you are developing a web app using Django's template language with some CSS library (such as Bulma or Bootstrap), and potentially using HTMx for more dynamic behavior, this is not an easily solved problem.

These CSS libraries are great and allow you to develop web apps fast and easily, with the downside that they provide a single huge CSS file. Some of them do offer more modular CSS files in case you want to make the effort. But even in that case, you will include more classes that you will actually use (for instance there might be a module for all the button classes - but you will most probably use only a single style of buttons).

When I searched online I couldn't find an "industry standard" solution to this problem. What I ended up doing was using the popular tool PurgeCSS along with a quick Python script to generate the appropriate command. What the PurgeCSS tool does is search for all your HTML files, gather all the CSS classes used, and then "purge" all the unused ones from the CSS file. You just need to declare all the HTML files you have.

Continue reading this post in our official blog…

--

--