
Robert H. answered 02/21/21
Front End Engineer with 6+ Years of CSS Experience
There are a few ways to reduce your CSS file size. I'll break them up into different technologies used below.
Custom CSS
This one is unfortunately very manual. Manual upkeep involves using best practices which include: keeping to the site 'theme' ( branding ), and only using inline-styles if you absolutely need to.
Sticking to brand guidelines is very helpful when deciding on design changes. Generally, there are enough restraints ( assuming you adhere to the brand guidelines ) that the less is more approach works better. This also helps reduce your custom CSS code.
Custom code by default is not minified. Minified means removing all the spaces (that are helpful for humans to read) therefore reducing the characters in the overall CSS file. This could be helpful in reducing the CSS file if applicable.
Custom code by default is not compressed. Text compression basically substitutes duplicated phrases/words with smaller temporary binary represenation. Here is a quick definition from AT&T:
Text files include a variety of different file types, including HTML, JavaScript, CSS, . txt, etc. Text compression typically works by finding similar strings within a text file and replacing those strings with a temporary binary representation to make the overall file size smaller.
Compilers
If you use any of the popular CSS frameworks (Bootstrap or TailwindCSS), you can leverage SaSS or PostCSS to reduce the pre-written CSS from each framework. This option requires you to be familiar with a text code editor (Visual Studio Code, Sublime Text, etc.) and there is a bit of setup and training involved. This is really helpful if you are working on-site that doesn't use a lot of the pre-written CSS styles.
Advice: if you reduce the pre-written code to a minimum, I would consider using a different framework or writing your own code. You lose the advantage of the Content Delivery Networks (CDN) if you compile the code yourself.
Refactoring
There is another technique that can help you manage your own custom code. Here is the definition of refactoring:
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.
Refactoring tends to happen as new technologies are released and your sites need to change. A quick example using CSS is CSS Variables. CSS variables have been out for a few years but only in the last year or so did most browsers support them. This means custom styles in your stylesheet were highly likely to be duplicated and harder to manage. if CSS variables are properly set up, they can be an asset to change your entire site on the fly. A quick hex code change in one location versus using Ctrl + F and adjusting each one manually.
These ways are generally the best routes I have found to reduce the CSS delivery to browsers.
Let me know if you have any other questions,
Robert