13

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
  • 889,049
  • 245
  • 3,507
  • 2,997
Scott Decker
  • 3,659
  • 5
  • 21
  • 36

2 Answers2

16

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
  • 6,604
  • 2
  • 48
  • 77
  • 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
3

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
  • 19,334
  • 9
  • 43
  • 48
  • 2
    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