Make your console.log() beautiful: Unleash the magic of console.log() with CSS
For a long time, I've been using plain old boring console.log() and so far, it's been a very good friend. However, I feel betrayed because I just discovered that console.log() output can be styled with CSS. It's like finding out your dog can sing after you've sold him to a pirate.
In this blog post, I'll show you how to bring beauty back into your console.
Start Here
It's pretty simple:
- add %c before the block you want to style (Don't press enter yet!)
console.log("%cMy name is Saviour");
- Add a comma and write the styles like CSS
console.log("%cMy name is Saviour", "background-color: yellow; color: red;font-size: 30px; padding: 50px")
Result:
It's as simple as that.
Of course, you could go a step further and style different blocks, different words etc. You could even add background images, margins and other cool stuff.
Let's do one more example. You can write the following code in the console.
const name = prompt("Hello friend. What is your name?");
console.log(`%cWelcome👋 %c${name}`, "display: inline-block; margin-right: 10px; background-color: green; color: white;font-size: 30px; padding: 10px; border: 2px solid white; border-radius: 10px", "color: black; background-color:white; font-size: 30px; padding: 10px; border: 2px solid green; border-radius: 10px")
What😮?????
Ok, a few things are going on but I promise you, it's really simple.
- I added two %c to style different parts of the text. The %c applies the styles until you override it with another %c, as in:
- Then, the styles are separated by a comma, like this:
Final RESULT
This is just the beginning of what is possible with console.log magic. I hope you found this post enlightening. If you liked this, make sure to bookmark this blog for more awesome web stuff. Till next time.
To find out more about console.log() styling, visit MDN Docs.