Even though I’m a back end and iOS kind of guy, I do enjoy working with CSS and Sass (with moderation).

This post is about a handy technique to debug positions and sizes of DOM elements.
Since it’s based on Sass mixins, we can imaginatively call it Sassy Debug.

There is no shortage of front end debug tools, and all modern web browsers will feature a more or less advanced development panel. These are useful, but at times I don’t really need all their power, as all I want is just to see the shapes the web layout is made of.

In those cases, my preferred way to highlight an element is to use an inset box-shadow, as it won’t affect the element’s size.

This can be easily done, and the simplest way would be to add (and then remove) the debug style rules directly. It would work, but it would also be a repetitive process with a lot of duplicated code, and it would lack any form of centralized control.

Sass mixins to the rescue.

The code

The Sass (SCSS) code is quite simple:

1
2
3
4
5
6
7
8
9
10
11
12
$debug: 1;

@mixin debug_with_color($color: #f00) {
  @if $debug == 1 {
    box-shadow: inset 0 0 5px $color;
  }
  @else if $debug == 2 {
    &:hover {
      box-shadow: inset 0 0 5px $color;
    }
  }
}

And the code to include the mixin into concrete selectors is even simpler:

1
2
3
.a_selector {
  @include debug_with_color(#0f0);
}

Let’s see what we have, here.

The mixin is controlled through $debug, a Sass variable.

Also, the mixin accepts a CSS color as an optional argument (with a default value).

Inside its body, the mixin will check the value of $debug to decide which, of two different style rules, should be applied when the Sass code is preprocessed to generate the CSS output.

The result

Once the mixin has been included where I need it, it all comes to changing the value of the $debug variable.

A value of 1 will add a colored internal shadow to all affected elements. A value of 2 will make the shadow appear only on the hovered elements – and all their ancestors that also include the mixin.

More importantly, when $debug has a value different from 1 and 2 (let’s say 0) the mixin will not generate any CSS rule.
This means that switching off the mixin will completely remove the debugging markers, and the Sass files will be ready to be preprocessed for production.