Did you know that you can style console logs ? Using %c
and some CSS so you can make some logs pop out more than others, or highlight specific parts of it:
console.log(
"%c[MyComponent]%c Hello",
"color: oklch(90% 0.15 100)",
"",
)
The snippet above will display a console messages like the one below:
[MyComponent] Hello
The colors that I picked here are working great against a dark background. But here’s what it looks like if my DevTools are using a light theme:
[MyComponent] Hello
The text is barely visible and definitely not accessible.
On top of the custom color we set, we could also set a background color so the text will always be legible:
console.log(
"%c[MyComponent]%c Hello",
`color: oklch(90% 0.15 100);
background-color: #232327;`,
"",
)
This does fix the contrast issue, but that’s not really the look I was looking for
[MyComponent] Hello
This was basically the issue that Tooru Fujisawa (aka Arai), a colleague of mine at Mozilla, asked me about a few days back. They wanted to get some nice looking logs that would adapt to both light and dark background, but couldn’t find a way to do so. I already got the same question in the past, and I used to tell people that such thing was’t possible. But since the last time I had to think about it, something new was added to the platform that is making this an easy fix.
light-dark()
was added at the end of last year in Firefox (120), and a couple months ago in Chrome (123) and Safari (17.5), so it’s now available in the latest version of all major browser engines.
This function takes two color parameters, and return the first one for light color scheme, and the second one for dark color scheme. For example, if we have color: light-dark(blue, red)
, the color will be blue in light mode, and red in dark mode (this is a bit simplified, you can read more about it on MDN).
Back to our styled console messages, we can use light-dark()
as a way to adapt to the console theme:
console.log(
"%c[MyComponent]%c Hello",
`color: light-dark(
/* for light theme */
oklch(50% 0.15 100),
/* for dark theme */
oklch(90% 0.15 100)
)`,
"",
)
Now it looks great in both dark and light theme:
[MyComponent] Hello
[MyComponent] Hello
And this works nicely across all browsers and can even be used in Custom Formatters.
light-dark()
You may have noticed that in my example, only the lightness of the color changes between the light (50%) and the dark one (90%). So it felt like we could do something like this instead: oklch(light-dark(50%, 90%) 0.15 100))
, so we don’t have to repeat all the values.
Unfortunately this doesn’t work, as light-dark()
can only return a color. Bramus wrote a blog post explaning why the function was designed that way and what we coud have in the future.