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.
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.
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: .
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.
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.
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; }
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With