Random Musings

O for a muse of fire, that would ascend the brightest heaven of invention!


Mixing SimpleCSS with Phoenix

Thursday, 6 Jan 2022 Tags: elixirphoenix

As I’ve done mainly backend development for the last few years, I thought it would be nice to explore and learn a lightweight CSS framework with Phoenix, a powerful modern web framework built on Elixir, and explore a bit the component functionality that it provides.

This assumes you know a bit about Elixir, Phoenix, and LiveView too. I’d refer you to an explanatory post, but I haven’t written it yet.

There are many simple and not-so-simple CSS frameworks out there, but one I really like is SimpleCSS, by Kevin Quirk.

It’s very much in the style direction of justice.gov.uk, which appears to be a follow-on act from the author of Maintainable CSS, Adam Silver. He also wrote a great little book on Form Design Patterns too.

This gives us a delightfully simple introduction to LiveView, a real-time-updates server-side rendering module for Phoenix, and a chance for me to flex some very flabby CSS and HTML muscles.

project initiation

Assuming you have a recent Elixir and Phoenix installed per docs, then create the new project, do the git dance:

$ mix phx.new \
    --no-ecto \
    --binary-id \
    --verbose \
    --install simple
$ cd simple \
    && git init . \
    && git add -A \
    && git commit -am import
$ iex --name simple -S mix phx.server

Then just swap in simplecss.css instead of phoenix.css, and watch the live reloading change the layout.

$ rm assets/css/phoenix.css
$ curl https://cdn.simplecss.org/simple.css -o assets/css/simple.css
$ sed -i '' -e 's/phoenix.css/simplecss.css/' assets/css/app.css
$ git add -A \
    && git commit -am 'switch to simplecss.org'

For bonus points, drop in a favicon.ico of your choice, and switch out the phoenix.png logo too.

phoenix layout

The initial page load is always a plain HTML site, with 3 nested components:

  • root.html.heex which comprises html & head tags, and a minimal body header that wraps the main section
  • app.html.heex which comprises the main section that is nested inside the previous root layout
  • index.html.heex comprising the actual @inner_content we show

JavaScripts to switch to the LiveView mode are also served, along with our CSS and images.

LiveView Layout

Any subsequent rendering is done within the LiveView itself, via websockets, using the live.html.heex template. It’s very similar to the preceding app template, just with a few additional classes to handle updates via liveview flash, instead of traditional views.