Lesson Overview

CSS Minification

Compress CSS files in Hugo to be smaller so they load faster
2 minutes 349 words

CSS minification is the process of removing a lot of the whitespace and blank lines in our CSS files. Whitespace is good for humans to easily read the code, but it is unnecessary for computers and it causes the files to be a much larger size than they need to be, and larger files = slower download = bad time for users waiting.

Minify

Hugo provides a feature to minify custom CSS files, just like we learned about Hugo’s ability to compress images.

Previously we created a styles.css file in our static folder. If this file is still empty then you do not need to do anything, but if you have written some CSS, follow the steps below:

  1. Move the styles.css file out of the static folder and into the assets folder.
  2. Open the baseof.html and replace the line <link rel="stylesheet" href="/styles.css"> with the following:
{{ $style := resources.Get "styles.css" | minify | fingerprint }}
<link rel="stylesheet" href="{{ $style.Permalink }}">

Now our styles will be processed by Hugo and Hugo will generate a new file when we build and deploy our site, this new file will be minified and fingerprinted to avoid browser cache issues.

Fingerprint

The fingerprint function is something that is done to prevent browsers from caching our CSS when it’s changed. Typically browsers will download a CSS file and keep it in cache (or memory) so the next page that is loaded with the same CSS file will load much faster. The browser uses the name of the file to do this so if the name does not change then it does not re-download the file.

But what if we change something inside the file and deploy it to our server? The browser won’t know because the name is the same. So fingerprinting is a way to get around that, and it adds a random string of numbers and letters to the name of the file so the browser knows when to update it’s cache.

Our styles.css file will now look like this: styles.sdfgj12344sfg.css and the browser will re-download it from our server when it changes.

Share this page