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.