Is it possible to add hugo if conditionals in scss files?

To keep your CSS out of the templates, you can do this in baseof.html:

{{ $classes := slice
  (printf "kind-%s" .Kind)
  (printf "type-%s" .Type)
}}
<body class="{{ delimit $classes " " }}">

On the home page, the body element is rendered as:

<body class="kind-home type-page">

On posts/post-1/, the body element is rendered as:

<body class="kind-page type-posts">

Then add specificity to your rules as needed.


You can also target a particular page by adding an id attribute to the body element.

{{ $classes := slice
  (printf "kind-%s" .Kind)
  (printf "type-%s" .Type)
}}

{{ $path := "" }}
{{ with .File }}
  {{ $path = .Path }}
{{ else }}
  {{ $path = .Path }}
{{ end }}
{{ $id := print "h" (substr (sha256 $path) 0 7) }}

<body class="{{ delimit $classes " " }}" id="{{ $id }}">

Producing something like:

<body class="kind-home type-page" id="h24a58f3">

This is a bit fragile, because the id will change if you rename a file or directory in the content path.

1 Like