Skip to content

Instantly share code, notes, and snippets.

@elstgav
Last active June 28, 2022 00:36
Show Gist options
  • Save elstgav/47ac8c505757bf89a85a to your computer and use it in GitHub Desktop.
Save elstgav/47ac8c505757bf89a85a to your computer and use it in GitHub Desktop.
CSS Generated Error Messages

CSS-Generated Error Messages

Writing a UI library is hard: coming up with components, figuring out naming schemes, finding the right granularity for your UI components so they can be composed together easily. As an author of the library, you'll be intimately aware of how things work and how components should go together. But the users of your library won’t. In other programming languages, this is where error messages can step in, providing guidance when using deprecated methods or incorrect arguments. So how can we produce error messages in CSS? Simple: with pseudo elements.

First let’s start with our error message mixin:

// Prints out error messages
// $location defaults to 'before'. 'after' is recommended for inline elements
@mixin error($message, $location: 'before') {
  &::#{$location} {
    content: '\26A0 ERROR: ' $message; // \26A0 => ⚠
    display: inline-block;

    background: red;
    padding: .5em;
    margin: .5em;
    border:  1px solid darkred;

    color:   white;
    font-size: 1.4rem;
  }
}

With that one simple mixin, we can easily produce error messages for our users. Let’s walk thorugh some helpful examples:

We can call out when a component should have appropriate aria attributes:

.alert:not([role*="alert"]) {
  @include error('`.alert` requires a `role="alert"` attribute');
}

or inform users of deprecated classes

// Deprecated selectors
// ------------------------------------

$deprecated: (
  // selector          // alternative
  '.page-row':         '`.row`',
  '.page':             '`.container`',
  'i.icon':            'span.icon'
);

@each $selector, $alternative in $deprecated {
  #{$selector} {
    @include error('`#{$selector}` is deprecated. Use #{$alternative} instead.');
  }
}

I used this technique extensively at a previous company, and it was a big help in preventing errors and catching common mistakes right as they happen. I knew it was working when shortly after setting up the debugger stylesheet, I saw a commit in our repo that removed a deprecated class, with the message “fair enough, weirdly intrusive css style warning” 😆.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment