Flexbox Fun with Hugo

Flexbox and Hugo both seek to simplify the way we design and develop websites. Flexbox helps make responsive design easy through CSS. Hugo is a static site generator that utilizes templating, shortcodes, and more to power agile development. We’ve used both for our own website. The tutorial below will help you get started using flexbox with custom Hugo shortcodes.

Flexbox

Implementing flexbox requires the creation of a flex container, which at its core simply requires you to use display: flex; to activate flex properties. For this demonstration, all columns generated through the shortcode will be of equal length, which is signified in the example below as flex: 1;.

.flex-container {
  display: flex;
  display: -ms-flex;
  display: -webkit-flex;
}

.flex-container > .flex-column {
  flex: 1;
  padding: 0 30px;
}

While flexbox is now ready to handle resizing based on screensize, columns of content could end up being squashed on tablet and mobile views. The following snippet stacks all flexbox content vertically based on a standard iPad screen view. Alter to fit your particular needs.

@media only screen and (max-width: 768px) {

  .flex-container {
    flex-direction: column;
  }

  .flex-container > .flex-column {
    padding: 0;
}

Hugo shortcodes

Shortcodes can be quickly added to Markdown content via Hugo. They’re called into content using {{< shortcode >}} and depending on how they’re created, can be closed using the backslash. You’ll create two shortcodes: one for the flex container and another for the flex columns.

Be sure to name your shortcode files the way you’d like to call them within your content (see implementation snippet for an example). Lastly, the snippets below use the safeHTML parameter to allow HTML entry in your markdown file - this is optional and dependent on your specific needs.

flex.html

<div class =”flex-container”>
  {{ printf “%s” .Inner | safeHTML }}
</div>

flex-column.html

<div class=”flex-column”>
  {{ printf “%s” .Inner | safeHTML }}
</div>

Implementation

With all components created, now all you need to do is plug them into your Markdown file. Be sure to close each shortcode or your content won’t render properly!

{{< flex >}}

{{< flex-column >}}

  <center>
    <p>this is your first (leftmost) column!</p>
  </center>

{{< /flex-column >}}

{{< flex-column >}}

  <center>
    <p>this is your second (rightmost) column!</p>
  </center>

{{< /flex-column >}}

{{< /flex >}}

The above examples are not the only way to construct flexbox shortcodes. For advanced customization, read CSS-TRICKS’ A Complete Guide to Flexbox and Hugo’s page on creating your own shortcodes. Let us know what you create by tweeting us @forestgiant!

Jessica Elle
Digital Marketing