Explain Codes LogoExplain Codes Logo

Colors in JavaScript console

javascript
console-styling
debugging
customization
Nikita BarsukovbyNikita Barsukov·Aug 7, 2024
TLDR

Easily colorize your JavaScript console by combining console.log() with CSS directives. Use the '%c' directive to initiate style changes:

console.log("%cAwesome Message", "color: red;");

With one simple line, you now have red text in your console. You can chain style changes for more impressive effects:

console.log("%cRed %cBlue", "color: red;", "color: blue;");

In the above case, "Red" is displayed in red, and "Blue" in blue. The magic trick here is %c which activates CSS styling for your console text.

Applying styles

Basic Colors: Jazz up your console logs by adding colors straight from CSS:

console.log('%c Info', 'color: green;'); // Because your info logs are precious emeralds! console.log('%c Debug', 'color: blue;'); // Feeling blue yet?

Error and Warning Highlighting: Make certain messages such as errors and warnings more noticeable with specific color schemes and font styling:

console.log('%c Error', 'color: red; font-weight: bold;'); // When you see red, you know it's bad. console.log('%c Warning', 'color: orange; font-style: italic;'); // Orange you worried about this warning?

Advanced Styles: For some visual flair in your console, experiment with backgrounds, padding, and border parameters:

console.log('%c Success', 'background: #4CAF50; color: white; padding: 4px; border-radius: 2px;'); // Green means go!

Styling Multiple Arguments: Inject different styles for different parts of a single log output:

console.log('%c First Part', 'color: red;', '%c Second Part', 'background: black; color: white;'); // Red Pill or White Rabbit? Choose wisely!

Personalizing the console

Customizing the color scheme

While color-coding console messages is helpful, having custom color palettes adds a personal touch.

  • Leverage Chrome's Custom.css or userContent.css in Firefox to predefine color schemes.
  • Use template-colors-web or a similar library for defining complex color templates.
  • Mix and match different colors, apply shadow effects or even mix in emojis to create more visually striking console logs.

Filtering for efficient debugging

In a heavy debugging session, visual markers can be extremely beneficial. Utilize the console's built-in filters for Errors, Warnings, or Logs. Use Ctrl + F or Cmd + F to quickly find specific log entries.

Getting creative with styles

Ultimately, your console logs should be as unique as you are. Try experimenting with rainbow drop shadows or even gradient text to create visually impressive logs:

console.log('%c Rainbow', 'color: red; text-shadow: 2px 2px orange, 4px 4px yellow, 6px 6px green, 8px 8px blue, 10px 10px indigo, 12px 12px violet;'); // Because everyone needs a little rainbow in their life.