How to Style Console Messages using CSS in JavaScript

Updated onbyAlan Morel
How to Style Console Messages using CSS in JavaScript

Console messages in JavaScript are very useful for displaying information to yourself, whether that be for debugging purposes or just to see what's going on.

By default, these messages are bland and boring, but you can spice them up with some CSS.

In this post, we'll learn how to style JavaScript console messages with CSS.

How to style console messages

To begin, let's start with a string that we want to later console log:

JAVASCRIPT
const message = "Hello, world!";

Now we can log this message to the console:

JAVASCRIPT
const message = "Hello, world!"; console.log(message);

This will, of course, produce a normal console message.

When you want to style this, you can pre-pend the string with a %c.

Doing this allows you to pass in CSS as the second argument and it will apply it to your message.

JAVASCRIPT
const message = "Hello, world!"; console.log(`%c${message}`, "color: red");

This will produce a console message with the text "Hello, world!" in red.

How to Style all Console Methods

Keep in mind that this works for all console methods, not just console.log.

For example here is a console.warn with the same styling:

JAVASCRIPT
const message = "Hello, world!"; console.warn(`%c${message}`, "color: red");

Here are all the console methods that you can style:

  • console.log
  • console.warn
  • console.error
  • console.info
  • console.debug

How to Style with Multiple CSS Properties

You can also pass in multiple CSS properties to the second argument, however that might be hard to read considering it has to be in one line.

A cool pattern you can use is to define each CSS property on a new line and then join them together with a semicolon.

JAVASCRIPT
const message = "Hello, world!"; const css = [ "color: red", "font-size: 20px", "font-weight: bold", ].join(";"); console.log(`%c${message}`, css);

That way, it is almost like writing normal CSS, except each property will get applied to the message.

Conclusion

In this post, we learned how to style console messages with CSS.

Simply pre-pend your message with %c and then pass in your CSS as the second argument and the styles will be applied to your message.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.