16

I'm using Jekyll to host a site on Github pages. The problem lies in referencing file paths within css files.

I'd like to do something like this:

body { {background: #FFF url('{{ site.baseurl}}/images/page_bg.JPG') center 0 no-repeat; background-attachment: fixed; color: #4b595f; }

But it doesn't seem that Jekyll process the css files, so site.baseurl never gets swapped out.

There are other situations where I can't just change it to an inline style, so assume that's not a possibility.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Scott Decker
  • 4,229
  • 7
  • 24
  • 39

2 Answers2

17

Using the trick from Brian Willis' answer won't work with SASS in @import-ed files.

Instead, you can do this:

main.scss

---
---
$baseurl: "{{ site.baseurl }}";
@import "myfile";

_sass/_myfile.scss

myclass {
  background: url($baseurl + "/my/image.svg");
}

Don't forget

  • the quotes around "{{ site.baseurl }}" (important in case of empty site.baseurl, and probably more robust) and
  • the plus sign with $baseurl + "/my/image.svg".
Raphael
  • 9,779
  • 5
  • 63
  • 94
  • 1
    Same issue will pop up with SASS. Same fix except put the value of the `$baseurl` variable into quotes and remove the semicolon. The quotes had me messed up for a bit. – William Park Oct 27 '16 at 06:43
  • 1
    Found a relevant article about some [weirdness with SASS strings](http://vanseodesign.com/css/sass-strings/). I think this answer will work perfectly without further reading. But if anyone is curious.... – Keen Oct 18 '17 at 19:33
  • I would improve the `main.scss` a bit, use `$baseurl: "{% if site.baseurl != '/' %}{{ site.baseurl }}{% endif %}";` so you are even save when the baseurl is just a single slash. Otherwise you have // slashes in CSS-pathes – KargWare Sep 18 '21 at 16:59
4

Jekyll processes all files that have YAML front matter. Stick a front matter section (even if it's empty) at the beginning of your file, and Jekyll will transform it correctly. Try using this at the start of the file:

---
title: CSS stylesheet
---
Brian Willis
  • 22,768
  • 9
  • 46
  • 50
  • 3
    FWIW, you can so leave out any content and do just 2 lines `---\n---` (sorry I can't make it look right in this comment field...). – BigBlueHat Oct 03 '14 at 15:00