JavaScript - adding style to the text of console log

JavascriptCssconsole.log

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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;");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRuchir GuptaView Question on Stackoverflow
Solution 1 - Javascriptkhalid13View Answer on Stackoverflow