Skip to main content

Start Using Sassy CSS in GoHugo

· loading · loading ·
Jared Lynskey
Author
Jared Lynskey
Emerging leader and software engineer based in Seoul, South Korea

The CSS for this site had slowly grown into one long, repetitive file, so I finally moved it over to SASS. If you’re running a GoHugo site, this is one of those changes that costs you fifteen minutes and pays for itself every time you touch a stylesheet afterwards.

Here’s how I set it up.

Why SASS at all?
#

Plain CSS gets messy once a site grows past a handful of pages. SASS gives you variables, nested rules, mixins and functions, so things like colours and common layout snippets live in one place instead of being copy-pasted everywhere. The best part for Hugo users is that Hugo Pipes compiles SCSS for you — no separate build tool, no watcher scripts.

Two pages worth keeping open while you work:

Setting it up
#

1. Sort out the assets directory
#

Hugo looks for an assets folder at the root of your project, so create one (or move yours) there. If you’d rather keep it nested inside resources, point Hugo at it in config.toml:

assetDir = "resources/assets"

2. Make a sass folder
#

Inside assets, create a folder called sass. Your SCSS files live here.

3. Add the entry point
#

Create main.scss inside the sass folder. This is the file Hugo will compile, so drop in a bit of SCSS to prove it works:

// assets/sass/main.scss

// Variables
$primary-color: #3498db;

// Mixin
@mixin center {
  display: flex;
  justify-content: center;
  align-items: center;
}

// Styles
body {
  font-family: Arial, sans-serif;
  background-color: $primary-color;
}

h1 {
  @include center;
  color: white;
}

4. Wire it into your template
#

In your head.html partial, load and minify the compiled stylesheet:

{{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify }}
<link rel="stylesheet" href="{{ $style.Permalink }}">

Just make sure the filename here matches your actual entry point (main.scss).

Splitting your styles up
#

Once things grow, split the SCSS into partials and import them from main.scss:

// assets/sass/_variables.scss
$primary-color: #3498db;

// assets/sass/_mixins.scss
@mixin center {
  display: flex;
  justify-content: center;
  align-items: center;
}

// assets/sass/main.scss
@import "variables";
@import "mixins";

body {
  background-color: $primary-color;
}

h1 {
  @include center;
  color: white;
}

That’s honestly all there is to it. Four steps, and Hugo recompiles your styles on every build. I went in expecting a fight with the asset pipeline, and it just worked.