Menu Developer Moovweb University

Develop Locally: Images

Images should be placed in the assets/images directory of your project.

There are two ways you can add an image to your site — in the stylesheets or in JavaScript.

Furthermore, in SCSS, you can use sprites (the recommended method) or you may directly use individual images.


Add Images via JS

To include an image in your site, use the fns.asset() function. For example:

let $img = $(tag("img", {src: fns.asset("/images/icon.png")}));
$body.find("#item").append($img);

Add Images via Stylesheets

Spriting

Create a sprites folder in assets/images. Inside this folder, place all images you want to sprite.

The gulpfile.js in the root of your project takes care of producing your sprites.

The _sprites.scss stylesheet defines a series of classes, one for each image, in the format:

sprites-filename

The stylesheet also contains mixins and variables with the same name assigned. Remember to use @import to import your sprite stylesheet into _main.scss!

To use the sprite, either:

  1. add the class to your HTML element, e.g., addClass("sprites-filename")
  2. insert a new HTML element, e.g., append("<div class='sprites-filename'></div>")
  3. extend the class or include the mixin to a pre-existing class or ID with Sass, e.g., @include sprites-filename or @extend .sprites-filename

Since a sprite is a collection of images put into a single image, they often get rather large. This can impact website performance, especially first page loads. As a rule of thumb, once a sprite image file gets larger than 100KB, break it into multiple sprites.

For more information, check out the GitHub page for gulp.spritesmith.

Directly Use Individual Images

You can also directly use images in the asset/images folder using the Sass function image-url().

Do not reference images by their paths relative to the stylesheet you are in. Depending on the Moovweb project you are running, the relative path will be different for different compiled stylesheets.

The following is the correct way to reference the image asset/images/icon.png:

background: image-url("icon.png")