Style your JS console logs

  26 May 2019       Javascript

Article featured image

But why?

Why might you want to style your logs? Well it could be an innocent reason like Facebook (go have a look) or many companies who put a message there to try to drum up some recruitment leads for their development team...

It could also be cos you're a dick that wants some extra developer points. Like me 👀.

How?

When writing your console log, your first argument (which is usually just the text/variable you want to output) needs to contain "%c". For example: console.log("%c Hello world!").

The second argument, must be the CSS you want to use to stye your log. For example: console.log("%c Hello world!", "color: red;")

Full example:

console.log("%cHello world!", "background-color:#137886; color: white; padding: 5px; border-radius: 3px; font-family:verdana; font-weight:bold; margin: 20px;")
Your styled console.log() should now look like this:
Styled console.log

You can keep adding to that so that different parts of your log have different styling but using more than one %c and more than one styling parameter.

For example:
console.log("%cText1 %cText2", "styles for text1", "styles for text2")

Full example:

console.log(
  "%c( ͡° ͜ʖ ͡°) %c¯\\_(ツ)_/¯",
  "background-color:#137886; color: white; padding: 5px; border-radius: 3px; margin: 5px;",
  "background-color:#861340; color: white; padding: 5px; border-radius: 3px; margin: 5px;"
)
Result:
Another styled console.log

Have fun!

Tags:

Javascript, Code, Console logs, Styling

Share this post