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.
Copied to clipboard! Playground
// 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:
Copied to clipboard! Playground
// 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:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews