It took me a little longer than others to start using Sass. I just felt like it would add to my time and that I was good enough at CSS to not need any help. Then a little over a year ago I was tasked with picking up where another developer had left off, and I was quickly convinced. It is now an indispensable tool in my kit.

One of the things I’ve been doing lately is using a couple of mixins to easily manage the background size and position of an image sprite. I use fonts and SVG for most things, but a couple of recent projects have warranted the need for good ol’ background images. This means setting background sizes for icons that get bigger on responsive or┬ábeing retina ready and with those challenges comes using the property background-size. I was working steadily on a project manually doing the math and setting the size in CSS. Then I would need to adjust my sprite and I had to go back and change the sizes on everything. I also had to do the math to figure out what position each image was at. It didn’t take me very many times of doing that before the programmer in me kicked in a developed the following mixins:

The first one takes one value. Since I’m only working with one sprite, I set the variables for the width and height of my sprite here. Then it takes the divisor and creates the new width and height. If my image is 64 x 64 pixels for retina and I want it to display as 32 x 32 pixels, I simply include the mixin as is to get half the size of the image. If it needs to be 16 x 16 pixels in smaller viewports, I can include it with a divisor of 4 and get a quarter of the size.

The next mixin does more math for me. I just give it the actual x and y coordinates, and it creates the correct placement for me with a simple math problem.

My final tip is to create your sprites and coordinates in numbers that are easily divisible by 2, 3, and 4. Those are the most common reductions you’ll make in your background sizes and the more even the math, the better results you’ll get.

Stay Sassy!

Leave a Reply

Your email address will not be published. Required fields are marked *