The JavaScript console is a powerful tool for debugging and logging information in web applications. By default, the console displays messages in a plain text format, but it is possible to customize the output with colors and styles. In this tutorial, we will explore how to add colors and styles to console output using CSS.
To add colors and styles to console output, you can use the %c
directive in your console.log
statements. The %c
directive allows you to specify a CSS style string that will be applied to the corresponding argument. For example:
console.log('%c Oh my heavens! ', 'background: #222; color: #bada55');
This code will output the string "Oh my heavens!" with a black background and green text color.
You can also apply multiple styles to the same command by using multiple %c
directives. For example:
console.log('%c Error: %c something went wrong ', 'color: red', 'color: blue');
This code will output the string "Error: something went wrong" with the word "Error:" in red and the rest of the message in blue.
It’s also possible to use this technique to display errors, warnings, and logs in different colors. For example:
console.error('%c Error: %c something went wrong ', 'color: red', 'color: black');
console.warn('%c Warning: %c something might go wrong ', 'color: orange', 'color: black');
console.log('%c Log: %c something happened ', 'color: green', 'color: black');
This code will output error messages in red, warning messages in orange, and log messages in green.
The CSS styles that can be used with the %c
directive are limited to those that are supported by the browser’s console. However, most modern browsers support a wide range of styles, including colors, backgrounds, fonts, and more.
For more information on styling console output, you can refer to the following resources:
- MDN: Styling console output
- Chrome: Console API Reference
- WebKit: Console Object API
By using the %c
directive and CSS styles, you can customize your JavaScript console output to make it more readable and visually appealing.