W3cubDocs

/Jekyll 4

Step by Step Tutorial

7. Assets

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:

.
├── assets
│   ├── css
│   ├── images
│   └── js
...

So, from your assets folder, create folders called css, images and js. Additionally, directly under the root create another folder called ‘_sass’, which you will need shortly.

Sass

Inlining the styles used in _includes/navigation.html(adding or configuring within the same file) is not a best practice. Instead, let’s style the current page by defining our first class in a new css file instead.

To do this, refer to the class (that you will configure in the next parts of this step) from within the navigation.html file by removing the code you added earlier (to color the current link red) and inserting the following code:

<nav>
  {% for item in site.data.navigation %}
    <a href="{{ item.link }}" {% if page.url == item.link %}class="current"{% endif %}>{{ item.name }}</a>
  {% endfor %}
</nav>

You could use a standard CSS file for styling, we’re going to take it a step further by using Sass. Sass is a fantastic extension to CSS baked right into Jekyll.

First create a Sass file at assets/css/styles.scss with the following content:

---
---
@import "main";

The empty front matter at the top tells Jekyll it needs to process the file. The @import "main" tells Sass to look for a file called main.scss in the sass directory (_sass/) by default which you already created directly under the root folder of your website).

At this stage you’ll just have a main css file. For larger projects, this is a great way to keep your CSS organized.

Create the current class mentioned above in order to color the current link green. Create a Sass file at _sass/main.scss with the following content:

.current {
  color: green;
}

You’ll need to reference the stylesheet in your layout.

Open _layouts/default.html and add the stylesheet to the <head>:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{ page.title }}</title>
    <link rel="stylesheet" href="/assets/css/styles.css">
  </head>
  <body>
    {% include navigation.html %}
    {{ content }}
  </body>
</html>

The styles.css referenced here is generated by Jekyll from the styles.scss you created earlier in assets/css/.

Load up http://localhost:4000 and check that the active link in the navigation is green.

Next we’re looking at one of Jekyll’s most popular features, blogging.

  1. Setup
  2. Liquid
  3. Front Matter
  4. Layouts
  5. Includes
  6. Data Files
  7. Assets
  8. Blogging
  9. Collections
  10. Deployment

© 2020 Jekyll Core Team and contributors
Licensed under the MIT license.
https://jekyllrb.com/docs/step-by-step/07-assets/