klick dot dev

higher aspirations, lowered expectations

Featured Images in Jekyll

This may be obvious to more experienced users of Jekyll, but I was recently trying to figure out an efficient way of using featured images with each post. It's a standard feature in WordPress, and seemed like a relatively straightforward task. At the least, it's doable. I just needed to familiarize myself more with Liquid. As I said, this might just be obvious to most people, but I thought it could be useful to others who enjoy using Jekyll.

What I want:

  • A hero-style full-width image at the top of each post
  • Use that same image on the homepage displayed with an excerpt for the most recent post
  • Use Liquid to set it up in a way that I don't have to manually update the homepage


Well I don't want to bore you with a bunch of nonsense right away, we can do that later if you want. Here's my quick solution for displaying featured images automatically.

First, we just need to add some custom front matter to our posts. Let's call it fimg for featured image. Basically we're just assigning the path of the image to this front matter variable, which we'll use later. This is what the front matter for the post you're reading right now looks like.

Now we just need to edit our layout and insert some Liquid tags. We use the post layout for our, well, posts. Let's insert a snippet to pull our featured images from the fimg value we set.

  <sectionclass="hero is-large"
  style="background-image:url( {{ page.fimg | absolute_url }} );
          background-size: cover;
          background-position: center;">

This is our hero section. Specifically, I use Bulma CSS on this website. If you're using a different framework (or no framework at all) then it'll look different. The important part is the inline style for the <section> which holds everything else. This should be possible to achieve without using an inline style, but I ran into issues. We'll save that issue for another day.

The "magic" (I use that term loosely) comes from here.

background-image: url( {{ page.fimg | absolute_url }} );

We entered the path to our featured image into the front matter of each post, now we call for that value and use Liquid to prepend our URL to the beginning of the path, and assign that as the background-image for our hero section. After Jekyll builds, this is what the web browser sees.

background-image: url( http://localhost:4000/assets/images/super-helpful.jpg );