With Hugo depreciating the old libsass I needed to convert my theme to either dartsass or vanilla css. I opted for modern vanilla css with nesting and layers.
Converting from sass to css nesting was some work but here I want to talk about how to handel building the css files with Hugo pipes. With css layers the order of the style files does not matter except for the line that first declare the order of the layers.
Below is how I opted to implement it. Any alternative solution would be very interesting to hear about!
This is the partial that loads all the styles for the Zen theme.
- It compiles all files that start with a underscore “_” in to a large “styles.css”.
- Minify and fingerprint the files in production only.
- Add the layer init line inline before any other styles to set the layer order.
- Separately add the mobilmenu as well as print style files.
The layer init file:
@layer reset, fonts, vars, base, layout, components, mobilemenu, print, zen;
The style partial:
{{ $main_style := resources.Match "css/_*.css" | append (resources.Match "css/**/_*.css") | resources.Concat "css/styles.css" -}}
{{ $mobile_style := resources.Get "css/mobilemenu.css" -}}
{{ $print_style := resources.Get "css/print.css" -}}
{{ if ne hugo.Environment "development" -}}
{{ $main_style = $main_style | minify | fingerprint -}}
{{ $mobile_style = $mobile_style | minify | fingerprint -}}
{{ $print_style = $print_style | minify | fingerprint -}}
{{ end -}}
{{ with resources.Get "css/layers-init.css" }}<style>{{ .Content | safeCSS }}</style>{{ end }}
<link rel="stylesheet" href="{{ $main_style.RelPermalink }}">
{{ if $.Param "mobilemenu" -}}
<link rel="stylesheet" href="{{ $mobile_style.RelPermalink }}" media="screen">
{{ end -}}
<link rel="stylesheet" href="{{ $print_style.RelPermalink }}" media="print">
The file structure for css files.
css:
base:
_document.css
_forms.css
_grouping.css
_headings.css
_images.css
_links.css
_tables.css
components:
_anchor.css
_box.css
_button.css
_cards.css
_center.css
_clearfix.css
_cookieconsent.css
_disabled.css
_flex-group.css
_flex-inline.css
_footer.css
_grid-group.css
_grid-stack.css
_header.css
_hidden.css
_icon-inline.css
_language-selector.css
_list-straight-left.css
_messages.css
_meta.css
_overlay.css
_pager.css
_responsive-video.css
_spacing.css
_tables.css
_tags.css
_visually-hidden.css
_wrap.css
layouts:
_layouts.css
reset:
_reset.css
_colors.css
_custom.css
_fonts.css
_variables.css
_zen.css
layers-init.css
mobilemenu.css
print.css
See more in my blog post Convert my Hugo theme sass styles to vanilla css with nesting and layers – xdeb.org