Categories
JavaScript Answers

How to Add Colors in JavaScript Console Log Output?

Spread the love

To make console long output easier to see, we can add colors to JavaScript’s console log.

In this article, we’ll look at how to add colors to console log output in the browser dev console.

Add CSS Styles to Console Log Output

We can add CSS styles to console log output with the %c tag.

For instance, we can write:

console.log('%c hello world ', 'background: #222; color: #bada55');

We add the %c tag so that we can apply the CSS styles in the 2nd argument to the hello world text.

We set the background property to set the background color.

And we set the color property to change the text color.

The console.error Method

The console.error method lets us log things with a red background.

This lets us show data in more obvious ways.

For instance, we can write:

console.error("hello world");

to use the method.

The console.warn Method

The console.warn method lets us log things on a yellow background.

To use it, we write:

console.warn("hello world");

Bash Color Flags

Also, console.log lets us add Bash color flags to set the color of the text.

For instance, we can write:

console.log('x1B[31mhellox1B[34m world');

x1B[31 means red.

And x1B[34m is blue.

Also, we can set the background color of text by writing:

console.log('x1b[43mhighlighted');

x1b[43m sets the background color to yellow.

Conclusion

We can log colored text to the browser development console with various tricks.

Some console methods lets us change colors in various ways.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *