How to make console.log() output colorful and stylish in browser 🌈

Hello there! Somebody wants their website to look cool, don’t you? 😎

Spoiler alert: You can do some crazy styling in browser console, open it up right now and check it out! πŸ˜‰

Table of contents:

  1. How does it work
  2. What are my options
  3. How to do it <<<<—– here’s the actual guide!
Styling console output of Facebook.com

How does it work

First of all, it is not complicated at all. It is just a bit of css code applied to a console.log call. That’s it.

What are my options

You can not use obviously all of the CSS properties, but with the ones you can use, you can accomplish a lot.

You can style your console outputs with:

  • background*
  • border*
  • border-radius
  • box-shadow
  • float + clear
  • color
  • cursor
  • display
  • font*
  • line-height
  • margin (must use also display: inline-block)
  • outline
  • padding (must use also display: inline-block)
  • text* (text-transform for example)
  • white-space
  • word-spacing
  • writing-mode

In the end, you can accomplish a lot, can’t you? πŸ˜‰

How to do it

It works with any of the console.* calls (console.log, console.warn…etc).

It works based on %c directive.

So you put %c into your text and for every %c you need to put another string parameter that contains style into console.*() call.

Style format

The styles have the format exactly as if you were to write styles in your *.css files, you put a casual “kebab case” properties (font-family: Roboto; color: #ccaa44, …) separated by a semicolon.

Here’s an example: (try it now!)

console.log("And %cthis%c is %chow%c %cyou%c can style your console logs", "color: red; font-family: monospace", "" ,"background-color: orange", "", "font-weight: 900", "");

A simple example: (try it now!)

console.log("%cThis will be styled%c and this won't", "color: blue; background-color: orange; font-weight: 900", "");

Here’s the catch!

Once you use %c directive, every character that follows will be styled.

Therefore don’t forget to put a closing %c character into your text and also another argument to the console log as empty string as within the example above – so as “empty style object” can be applied.

That’s it!

Yeah guys, it was this easy. Also, one more important note, if you have implemented some funny console message that shows up when a visitor loads your website, just make sure the console.log call will not get removed by babel or any other code preprocessor or minifier πŸ˜‚ .

If you want to study this in a more detail, checkout an official Console API documentation on MDN explaining a bit more.

Yours in coding,

Ivan