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.
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
.
* {
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:
* {
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.
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! π