Inline CSS from yaml

I was looking for a solution to use variables in scss files and found https://github.com/spf13/hugo/pull/1431, while writing a reply I figured this forum may be better suited.

There are some threads about using variables in scss, less, and css files. Other threads on critical css inlined. This is a method that I just came up with, I haven’t tried it but would like your feedback.

We can put base styles into a data file and format it in yaml then reuse the nodes / styles while setting modified selectors, an example below from bootstraps scss button file defines a base btn style and two additional styles where only the color is set and the btn styles are reused.

A partial or shortcode could add the style=""; attribute so from a global context get the styles $style := $.Site.Data.styles then in a template something like <a {{partial "style" (slice . "btn-primary" "custom-class")}} href="#">Click here</a>

Within the partial it would parse the array with the first member being the dot context then match the array members to classes (keys) and inline the styles.

--- 
btn: &btn
  display: inline-block;
  margin-bottom: 0; // For input.btn
  font-weight: $btn-font-weight;
  text-align: center;
  vertical-align: middle;
  touch-action: manipulation;
  cursor: pointer;
  background-image: none;
  white-space: nowrap;
btn-primary:
    <<: *btn
    color: indigo;
btn-default:
    <<: *btn
    color: blue;

Maybe an improvement on this would be to use a partial for a button, then pass in the classes and have the partial inline the styles

{{partial "button" (dict "dot" . "classes" (slice "btn" "btn-primary" ) "button_text" "Click here" )}}

The rendered html would be a <button> tag with all styles inline.

1 Like

Have you seen

2 Likes