How to Style Console Messages using CSS in JavaScript
Table of Contents
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:
JAVASCRIPTconst message = "Hello, world!";
Now we can log this message to the console:
JAVASCRIPTconst 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.
JAVASCRIPTconst 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:
JAVASCRIPTconst 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.
JAVASCRIPTconst 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!
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Getting Started with React