Javascript – How To Add CSS Styles To console.log Messages

In Javascript, console.log() is used to print messages to the developer tools console to help with debugging. The console output can be updated to have CSS styles. This can be helpful when debugging if you have many console messages and you would like a certain message to stand out to be able to quickly find in the console. Adding CSS to console messages works in Google Chrome, Mozilla Firefox, and Microsoft Edge.

CSS styles are added to console.log messages by using string substitution with the %c directive. Lets start with a simple example.

A Simple Example

console.log('%cHello World!', 'color:blue;font-size:20px;');

From the above example, we can see that to add CSS styles to a console message we need to add the %c directive in front of the string to be styled and then follow the string with a comma and then have a string with CSS style rules.

Multiple Styles In A String

The substitution string can be used multiple times in a string to add multiple CSS styles to a string.

console.log('%cHello %cBonjour %cHola %cKonnichiwa', 'color:red;', 'color:blue;', 'color:green', 'color:orange');

In the above example, the %c directive was used four times to update the string with the matching CSS string.

Setting The Style Back To Default

To have part of a console message have CSS style and then go back to the normal console message style you can match the %c directive with an empty string that has no CSS style rules in it.

console.log('normal %cwith style%c back to normal', 'color:blue;background-color:yellow;font-size:25px', '');

In the above example, the ‘%cwith style’ part of the string matches with the string that has CSS styles. The remaining ‘%c back to normal’ part of the string matches with the string that has no CSS rules so the style is the default style for console messages in Chrome.


Here is another article you may be interested in: Javascript – When To Use console.dir()

References:
https://developer.mozilla.org/en-US/docs/Web/API/Console
https://davidjguru.github.io/blog/javascript-fast-tips-stylizing-output-console-log
https://www.bennadel.com/blog/3941-styling-console-log-output-formatting-with-css.htm

Leave a Comment

Your email address will not be published. Required fields are marked *