Skip to content

Latest commit

 

History

History
74 lines (44 loc) · 3.43 KB

console-style-console-log-output-css.md

File metadata and controls

74 lines (44 loc) · 3.43 KB

[Console] - Style console.log() output with CSS

The humble console.log() method can do a LOT more than just output plain text to the console, even though that's all it's used for most of the time.

You can add CSS to style the text using the %c directive. I summarized a bit of the possibilities below but as always, the MDN Docs have a wealth of knowledge.

But why?

Styled output in the console is much easier to see. It's especially useful if there are other unformatted logs in the console. Stylish output jumps out at you.

Another excellent use case - which I'll try to address soon - is when outputting colors. What would you prefer? Reading color RGB or hex values, or looking at an actual sample of that color right in the console?

The basics

The syntax for the basic case is simple:

console.log( " %c The string you want to format " , " CSS Styles " )

// instead of
console.log("Hello World");

// be stylish
console.log("%cHello World", "color:red");

image

Moving %c around

As shown, the %c directive doesn't need to be at the beginning of the string.

The style argument is applied immediately after the %c directive until the end of the string or the next %c directive.

console.log("Hello %cWorld", "color:red");

image

Using %c multiple times

There can be multiple %c directives in one string. The style arguments are applied in order.

  • The 1st style argument is applied from the 1st %c directive until the 2nd %c
  • The 2nd style argument is applied from the 2nd %c directive to the 3rd %c and so on, until the end of the string.
console.log("Hello %cWorld%c!!", "color:red", "color: green");

image

Leave parts of the string unstyled

To leave parts of the string unstyled, just add a %c with an empty string as its style.

console.log("Hello %cWorl%cd", "color:red", "");

image

Add all of the styles*

* Not really. There are some limitations. See MDN Docs for a list of supported CSS properties (at least in Firefox).

Better yet, open the console and try it yourself right now!

What I showed is just the tip of the iceberg. I would highly recommend checking out the excellent examples in this article.

Another good place to see these stylish console logs is in the console of tech companies like Facebook or Discord. Here's an example from the latter.

image