CSS concatenation

Learn how to automatically combine many CSS files together into a single CSS file for better performance.

Goal

We’re going to use Jekyll to combine many CSS files into a single file automatically to improve our website loading time.

After you’ve followed along with this tutorial apply the same technique to your own portfolio website.

  1. Type it, type it real good

    Remember the purpose of this lesson is to type the code out yourself—build up that muscle memory in your fingers!

Fork & clone

Start the lesson by forking and cloning the css-concatenation repository.

Fork & clone the “css-concatenation” repo.

The repository will have some starter files to get you on your way.

  1. Fork & clone

    This includes some starter code that you can get by forking and cloning the repository.

1 Set up the project

The basic starter repo you just forked and cloned has the CSS files we need inside it—we’re going to work from that.

  1. css-concatenation
  2. _layouts
  3. default.html
  4. css
  5. grid.css
  6. main.css
  7. modules.css
  8. type.css
  9. _config.yml
  10. index.html

Start Jekyll in this folder. Open the css-concatenation into your code editor.

  1. Naming conventions

    Don’t forget to follow the naming conventions.

2 Create new primary CSS

We need to make a new CSS file that Jekyll is going parse. Generally Jekyll ignores CSS files because they don’t have the --- at the top.

So, let’s make a new file named site.css:

  1. css-concatenation
  2. _layouts
  3. default.html
  4. css
  5. grid.css
  6. main.css
  7. modules.css
  8. site.css
  9. type.css
  10. _config.yml
  11. index.html

In the CSS file we’re going to write this code:

---
---

{% include_relative modules.css %}
{% include_relative grid.css %}
{% include_relative type.css %}
{% include_relative main.css %}

The really important thing is that these files are in exactly the same order as inside default.html

3 Link layout to single CSS

The final step in this process is to link to the single, concatenated CSS file from our default.html file.

⋮
  <title>{{page.title | escape}}</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="css/site.css" rel="stylesheet">
</head>
<body>
⋮

Now our default.html only links to a single CSS file. That single CSS file (site.css) represents a combined (concatenated) version of all our CSS together.

Refresh your browser to make sure everything still works…

And you’re now ready to get much better results on the performance tests.

  1. Line D

    There’s only one CSS file linked from our layout now.

4 Apply to your portfolio

Now that you understand the technique and done it once, apply the same thing to your own portfolio to make it harder, better, faster & stronger.