Matteo Rizzo
Matteo Rizzo

Reputation: 167

Jekyll page specific CSS

I'm building a website using Jekyll for the first time, and so far it's truly amazing.

My problem is: I want to be able to add specific CSS to specific pages of the website.

The question is: is there a clever way to add some lines of code to a specific page, maybe using YAML front matter?

Before using Jekyll, I used to link a separate .css file in the <head>, like that:

<link rel="stylesheet" href="/style.css">       # main stylesheet
<link rel="stylesheet" href="/page/style.css">  # secondary stylesheet


Update #1

I found this document https://jekyllrb.com/docs/includes/#using-variables-names-for-the-include-file.
It seems to accomplish something similar to what I'm looking for.
The only issue is that (due to the way I set up my template) the CSS ends up being included in the <body> tag. Everything seems to work fine tho.


Solution

I solved the problem by including the following lines in the <head>:

<style>
{% if page.style %} {% include css/{{ page.style }}.css %} {% endif %}
</style>

That way I'm able to include a whole stylesheet from _includes.

So far it works without issues and I'm very happy with it.

Upvotes: 10

Views: 1975

Answers (1)

David Jacquel
David Jacquel

Reputation: 52809

The clever answer is in your question : use a front matter variable to define which style is applied for a specific page.

---
title:  any page
style:  one         # defines body main class
layout: default
---

layouts/default.html

<body class="{% if page.style %}{{ page.style }} {% endif %}">
...

your css

one: { background: #f00; }
two: { background: #0f0; }
...

Upvotes: 10

Related Questions