Compass is a beautiful, beautiful thing and its image helpers make working with visuals just that much more beautiful. Here are two methods to let compass do all of the work for you. Just hit ⌘s!
Image-Url
Image-url is FANTASTIC. Basically, you must first set up your compass.rb or config.rb (whatever your compass configuration file is) and update the images path to its correct directory in relation to this file (like, “public/images” or just “images” if they’re on the same level). Here’s a great link with more detail on relative paths and how to set them up.
Config.rb :
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "stylesheets"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "js"
Then, all you have to do is link to the specific image you’re looking for in the sass file:
SCSS:
.my-little-pony {
background: image-url("rainbow_unicorn.jpg");
}
CSS output:
.my-little-pony {
background: url("/images/rainbow_unicorn.jpg?1375810680");
}
Compass does all of the work for you! It links to your images directory, and pulls the file (no more searching confusingly through directories: ../../images), AND it does a clever little thing called cache-busting. You may be wondering what all of the numbers after the “?” in that CSS are. Well, what Compass did was added these numbers so that if I changed that image, the numbers would change and a user’s cache wouldn’t be loading the old image anymore. It’s called “cache-busting.” Pretty clever, Compass.
The only downside is that image-url doesn’t support .svg’s yet. It can’t read the file’s image size properly (well, neither can your computer). A good rule of thumb is: if your system can return information on a file’s dimensions, you can use that file format for image-url.
Image-Height & Image-Width
Compass can also read the width and height of your image, so you don’t have to!
SCSS:
.my-little-pony {$image: "rainbow_unicorn.jpg"; // note: no svgs here either :(
background: image-url($image); // see! image-url rocks
height: image-height($image);
width: image-width($image);
CSS output:
.my-little-pony {
background: url("/images/rainbow_unicorn.jpg");
height: 204px;
width: 163px;
}
Now isn’t that nice? :)
TL;DR: Use image-url as much as possible, & know about other Compass image helpers :)