Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll page specific CSS

Tags:

css

jekyll

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.

like image 921
Matteo Rizzo Avatar asked Aug 02 '18 07:08

Matteo Rizzo


People also ask

Can Jekyll use CSS?

Using CSS, JS, images and other assets is straightforward with Jekyll. Place them in your site folder and they'll copy across to the built site. Jekyll sites often use this structure to keep assets organized: .

What is Jekyll CSS?

Jekyll is an open source static site generator. You can write your content in Markdown, use HTML/CSS for structure and presentation, and Jekyll compiles it all into static HTML.

What is front matter in Jekyll?

Front matter is a snippet of YAML placed between two triple-dashed lines at the start of a file. You can use front matter to set variables for the page: --- my_number: 5 --- You can call front matter variables in Liquid using the page variable.


1 Answers

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; }
...
like image 174
David Jacquel Avatar answered Sep 23 '22 13:09

David Jacquel