Last Updated: February 25, 2016
·
653
· shlidor

Compass size() mixin

This is a small and useful mixin to easily set width and height to your elements.
It can be used with any kind of unit or even with an image name so it gets the dimensions from the image.

The simplest usage would be something like:

@include size(40px);

This will compile to:

width: 40px;
height: 40px;

Another example usage would be with two parameters (<width>, <height>) :

@include size(70%, 200px);

The great part of this mixin is the ability to pass in an image and set width and height based on the image dimensions; Let's say I have a background image named bg.png, it is 300px high and 200px wide. Now I want to create a form that will have this image as a background and have the same dimensions it has.
To accomplish that, I would usually go and check my image dimensions and set the form's width and height manually. Using this mixin, all I have to do is:

form {
  @include size('bg.png');
}

And compass would do the rest!

Edit: I wanted to paste the mixin right here but it seams that @else turns into a coderwall user referencing link, so until that is fixed, I've added it as a Gist

and finally, here it is:

The size() mixin on github