A Sass Mixin for CSS Triangles

There is a very popular CSS trick consisting on using a mix of solid and transparent borders on a 0 width, 0 height element in order to fake a triangle. If you don’t know technique yet, you can find more information about it in the following articles:

While it comes with some quirks, it actually does the job well and has the benefit of being very compatible across the wide range of browsers we have to support.

Now the thing is, I never completely remember how to use this little piece of code. Which borders need to be transparent? Which one should be solid? I just can’t figure this out and I bet it’s the same for many of you as well. So this is typically the kind of thing you would like to automate using Sass.

There are probably as many CSS triangle Sass mixins as there are Sass developers. What if I showed you my own mixin to deal with CSS triangles/arrows in CSS?

What Do We Need?

Before digging into the code, it would be a good idea to check what we need in order to make a triangle out of CSS. First: a direction. We need to define a direction for our arrow, either top, right, bottom, or left. Also, what about a position? Like at 1.5em from the top, 100% from the left, for instance. Also we could define a color, and perhaps a size as well, although those 2 arguments could have defaults.

So in the end, our mixin is a short way for us to say Generate a triangle pointing to this direction, at this spot, in this color, and in the following dimensions. Sounds good, right?

Note that in order to avoid using extra markup, I like to use pseudo-elements for triangles. For instance:

.element {
  /* Container of some kind */

  &::before {
    /* Including triangle mixin */
  }
}

Using Our Toolbox

Last week, I wrote about some functions and mixins to kickstart your project. In case you haven’t read that article yet, go ahead. I’ll wait.

Okay, done? What if we reused some of our mixins in order to make this triangle mixin as sharp and clean as possible? For instance, we could use the size() mixin so we don’t have to define both the width and the height. We could also keep a consistent API for positioning stuff and make use of the absolute() mixin (more about that mixin here).

Continue reading %A Sass Mixin for CSS Triangles%

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s