
How to Style Console Logs in JavaScript
If you use a special character in front of your console messages β called a directive β you can specify CSS styles as a second parameter to enhance the look of your messages.
// Notice the "%c" at the beginning of the string.
console.log('%cAn error has occured', `
text-transform: uppercase;
background: #000;
color: #FFF;
font-weight: bold;
padding: 5px 20px;
text-shadow: -1px -1px 0 rgba(251, 1, 252, 0.5),
1px 1px 0 rgba(4, 251, 246, 0.5);
`);
This will produce the following formatted message:
An error has occured
Other Directives
So what other directives can you use for console
? For example, you can use %o
and %O
to format string as expandable DOM or JavaScript objects:
// Outputs an expandable JavaScript object
console.log('Person: %O', { icon: 'π' });
// Outputs an expandable DOM element
console.log('Navigation: %o', document.getElementById('nav'));
If you would like to learn more about the console
in JavaScript, make sure to check out the tutorial below.


Resources:

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: