Shape: A Sass Mixin

November 4, 2013

CSS shapes are really fun, and making images out of them is awesome! We see shapes being used everywhere on the web these days, from icons to navigation to tooltips. And its great! I mean, doesn’t typing a bit of code and getting a cool image out of it without touching Illustrator make you feel like a badass?

Well, it definitely makes me feel like one. Which is why I made this (based on this dribbble shot):

Screen Shot 2013-10-28 at 8.13.17 PM.png

Click on that image to open the code pen for it!

And most of the markup looks like some variation of this:

.neck {
  @include shape(circle, 180px, $tan);
  margin: 200px 210px;
}

What? That’s like … two lines. Yep, its pretty easy to make shapes without much effort when you use Sass and a really simple little mixin I wrote called “Shape”

The CSS that the above code compiles to looks like this:

.neck {
  width: 180px;
  height: 180px;
  background-color: #f4e5be;
  border-radius: 50%;
  margin: 200px 210px;
}

But we don’t need all of that! All you need to do in order to instantiate the shape is state what shape it is (options include circle, triangle, right-triangle, square, pentagon, hexagon, and octagon), it’s size, and the color you want it to be. It’s super easy (which makes more complex shapes easier to make)!.

For instance, the way I made freckles was like this:

%freckles {
  @include shape(circle, 15px, $darkbrown);
  margin-top: 285px;
  &:before {
    @include shape(circle, 15px, $darkbrown);
    content: "";
    margin: -20px 15px;
  }
  &:after{
    @include shape(circle, 15px, $darkbrown);
    content: "";
    margin: -20px -15px;
  }
}
.freckles--left {
  @extend %freckles;
  margin-left: 220px;
}

Instead of all of this:

.freckles--left, .freckles--right {
  width: 15px;
  height: 15px;
  background-color: #523026;
  border-radius: 50%;
  margin-top: 285px;
}
.freckles--left:before, .freckles--right:before {
  width: 15px;
  height: 15px;
  background-color: #523026;
  border-radius: 50%;
  content: "";
  margin: -20px 15px;
}
.freckles--left:after, .freckles--right:after {
  width: 15px;
  height: 15px;
  background-color: #523026;
  border-radius: 50%;
  content: "";
  margin: -20px -15px;
}
.freckles--left {
  margin-left: 220px;
}

Not only does it simply look neater, but it makes more semantic sense to anyone reading your code. Here is a shape: the shape is a circle, the circle is this big and this color. You don’t have to worry about borders and transparency etc., and can always edit the shape right below the @include.

Grab the mixin right here: https://gist.github.com/una/7198256#file-shape-mixin

And see it in action here: http://codepen.io/unax3/pen/BhCLi