How to Style Console Logs in JavaScript

How to Style Console Logs in JavaScript

Ferenc Almasi β€’ 2020 September 13 β€’ Read time 1 min read
  • twitter
  • facebook
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);
`);
console.js

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'));
directives.js

If you would like to learn more about the console in JavaScript, make sure to check out the tutorial below.

9 Different Use Cases of console.log
How to Style Console Logs in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.