Simple Trick To Debug Your CSS

Published Oct 2, 2021

Table of Contents

The Outline Trick

The fastest way to find misbehaving elements on the page is using the outline trick in CSS. This helps you find issues such as overflowing elements quickly, but more importantly it gives you a visual of the entire page.

Debugging CSS

You can use outline to set an outline on every element, which isn’t going to affect the layout compared to using border β€” unless you specify box-sizing: border-box.

css
* {
  outline: 1px solid tomato;
}

You can also add a background property, or use different outline colors for nested elements, if you want to make things more readable:

css
* {
  outline: 1px solid tomato;
}

* * {
  outline: 1px solid black;
}

* * * {
  outline: 1px solid white;
}

Creating A Bookmarklet

You can turn this helper into a JavaScript bookmarklet, and use it when you need it. The only thing you have to do is create a regular bookmark in your browser, and include this code.

Bookmarklet

bookmarklet
javascript: (function () {
  const headElement = document.head;
  const styleElement = document.createElement('style');
  styleElement.setAttribute('debug-css', '');
  styleElement.innerText = '* { outline: 1px solid tomato; }';

  const debugElement = headElement.querySelector('[debug-css]');
  if (debugElement) return debugElement.remove();

  headElement.append(styleElement);
})();

The code uses an IIFE to create a <style> tag, append it to the <head> element, and checks if the element exists to toggle it.

That’s it! πŸ˜„

Support

If you want to support the content you're reading or watching on YouTube consider becoming a patreon starting low as 1$ per month.

Become a patreon
Subscribe For Updates
Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub