Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jekyll baseurl in css files

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.

like image 656
Scott Decker Avatar asked Nov 17 '13 22:11

Scott Decker


People also ask

What is the URL of Jekyll?

When you run jekyll serve locally, it starts a web server, usually at http://localhost:4000 , that you use to preview your site during development.

What is a site Baseurl?

Base URL: The consistent part or the root of your website's address. For example, http://www.YourDomain.com. Relative URL: The remaining path given after the base URL. For example, /contact_us, /seo/blog/new_post.

What is GitHub base URL?

When you deploy to GitHub Pages, the base URL of your website has the following structure: https://{org}.github.io/{repo} . A subdomain is created for your GitHub organization and your repository's name is appended as a fixed path.


2 Answers

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".
like image 166
Raphael Avatar answered Oct 02 '22 18:10

Raphael


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
---
like image 20
Brian Willis Avatar answered Oct 02 '22 17:10

Brian Willis