Including CSS stylesheets in Jekyll pages

gabed123 picture gabed123 · Sep 22, 2015 · Viewed 17.2k times · Source

I have been playing around with Jekyll for a couple of weeks now and I am trying to create a default style for each of my blog posts, but I'm not exactly sure where and how it's supposed to be done. My main index page works fine in terms of styling but my posts have no CSS being passed to them whatsoever despite trying various methods.

Is the CSS for blog posts supposed to be written in _layouts/default.html or _layouts/posts.html, and do I have to specify which stylesheets I want to use in the YAML, by using {% include ...%}, or by writing

{% if page.style %}
    <link rel="stylesheet" href="{{ page.style }}">
{% endif %}

I wasn't able to find information that gave a clear cut answer.

Answer

Maximillian Laumeister picture Maximillian Laumeister · Sep 22, 2015

The Jekyll way to do this is to take whichever layout you are going to use for the final page (for example _layouts/posts.html) and create your HTML document skeleton there (i.e. html, head, and body tags). In the head of the layout HTML, put {% include blog-head.html %}. This blog-head.html file is where we are going to include all of the CSS, JS, etc. that is required for every blog page.

Then in your blog-head.html, you can just write the CSS file include for a custom CSS file:

<link rel="stylesheet" href="blogposts.css">

This way, you can easily include the same head section in all of your blog post pages, and you can easily update that head section (adding, removing, or changing CSS/JS) and it will automatically take effect across all of your blog posts.

The following link provides general steps on overriding theme defaults: Jekyll: Overriding Theme Defaults. The page provides instructions for getting a copy of the html base layout file (from your theme) that you will need to modify with the new CSS link.

Please follow up if you would like me to clarify anything!