Coloured Console Log in Browser DevTools
Displaying colourful console messages may be a child's play to some, but to others, it may still be a mystery yet to be unravelled. I once saw a coloured console message when I popped open the DevTools of a particular website. This sparked my curiosity and my quest to discover how it was achieved began.
In this article, I'll show you how to display colourful console messages. Note that this is mainly for decorative purpose and not to be used when trying to debug production issues.
The common syntax:
\x1b[33m is an escape sequence that will be intercepted by the terminal. When it is encountered, it instructs the terminal to switch to a yellow colour derived from the ANSI escape code.
%s indicates that the next character would be a string. This is where the second argument (the string) gets injected.
\x1b[0m is the code for the non-printable control character escape. It resets the terminal colour.
The syntax for coloured console message formatted using CSS:
console.log('%cstringToStyle', 'color: #f0db4f');
The CSS format specifier %c is used to indicate that the console message (the second parameter) would be styled using CSS.
To format the output further, you can specify a font for the message:
console.log('%cLet\'s build a better web', 'color: #734E73; font: bold 50px Helvetica Neue; text-shadow: 1px 1px 0 #ddd;'); console.log('%cWant to learn more about Software Engineering? Visit https://chiamakaikeanyi.dev', 'font-size: 14px');
Copy the code above and paste in your DevTools console to view the formatting.
You can style your console messages to achieve more. All possibilities are not exhausted in this article.