JavaScript - adding style to the text of console log

Ruchir Gupta picture Ruchir Gupta · Jul 18, 2014 · Viewed 31k times · Source

Recently I logged into my FB account on Chrome Browser. When I opened the developer tools, I saw something like this:

enter image description here

Now I know that it is possible to add anything to console using the javascript console.log function. But my question is -- how did they add style to the text? E.g. "Stop!" is written in red tahoma font with black border and larger size. How did they do it?

Answer

khalid13 picture khalid13 · Jul 18, 2014

Addy Osmani has a good explanation:

https://plus.google.com/+AddyOsmani/posts/TanDFKEN9Kn (archive.org)

Styled console logging in the Chrome DevTools (Canary)

Thanks to Mr. +Mike West, you can now add style to your console log via %c, just like you can in Firebug. e.g

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

Blocks such as console.log('%cBlue! %cRed!', 'color: blue;', 'color: red;'); are also now supported :)

Whilst most people will probably use this for practical purposes, it's also possible to have a little fun with it :) (see below)

Not to be outdone, here's what +Mike West came up with a few days ago

;)

Relevant change: http://trac.webkit.org/changeset/130941


Basically, you can use the %c paramater to pass in CSS styling. For an example, try the following in your chrome console:

console.log("%cBlue! %cGreen", "color: blue; font-size:15px;", "color: green; font-size:12px;");