New Head CSS

So this site is for experimenting with CSS it means every page has different CSS on it. There are various ways to add the CSS.

The old ways

I used several ways to add CSS previously. One way was to simply add style tags in the document itself. Style tags don’t belong in the body section of an HTML document although this does work but was always rather unsatisfactory.

Originally the site just had one CSS file for each page. This means double the http requests though than if all the CSS was in one file

Another way was to create an array or list of style rules in the frontmatter of each page and loop them through from the <head> section and place them there between style tags. The problem with this method was that there is no access to Emmet shortcuts, syntax highlighting, linting and the code was harder to read.

The new way

So the new way is simply this. When creating a page use a temporary CSS file, say temp.css for the page being worked on. Then when the page is complete cut’n’paste the CSS from the file into the frontmatter with a style parameter and a pipe character. The pipe character preserves the formatting of the following style rules and again these can be pulled into the head section of each page.

Here is an example of some frontmatter in YAML format:

style: |
  .card-container {
      width: 100%;
      min-height: 70vh;
      display: grid;
      place-content: center;
  }
  .card {
      position: relative;
      background-color: gold;
      height: 60vh;
      aspect-ratio: 1 / 1.6;
      border-radius: 10px;
  }  

Note that the CSS code has to be indented.

Then in the <head> section use the following Hugo templating code:

{{ with .Params.style }}
    <style>
        {{ . | safeCSS }}
    </style>
{{ else }}
    <link rel="stylesheet" href="path/to/temp.css">
{{ end }}

Pros & cons

This method reduces http requests and keep the CSS on the same page so no searching for another file. When contructing a page you get the advantages of working in a separate CSS file with syntax highlighting, Emmet, etc..

The main con is that if going back to edit the CSS on a page you don’t get the above benefits, well unless you were to put the CSS back in the temp file, though that’d be a hassle.