How to Add Colorful Styles to console.log Messages in JavaScript

This article explains how to use the %c placeholder and CSS strings with console.log to create colorful, formatted debug messages that stand out in large JavaScript log outputs, boosting development efficiency.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Add Colorful Styles to console.log Messages in JavaScript

When developing JavaScript you often use console to output debug information. The console API also allows you to apply CSS styles to the printed text, making logs easier to spot among many messages.

Why use styled console output? In applications with large amounts of logs, colored or formatted messages help you quickly identify the information you care about.

Example of a simple styled log:

console.log('%cHello', 'color: green; background: yellow; font-size: 30px');

The %c placeholder tells the console to apply the following CSS string to the preceding text.

You can also define a list of style strings and join them:

const styles = [
  'color: green',
  'background: yellow',
  'font-size: 30px',
  'border: 1px solid red',
  'text-shadow: 2px 2px black',
  'padding: 10px'
].join(';');

console.log('%cHello There', styles);

Another placeholder, %s, works as a string substitution:

const styles = ['color: green', 'background: yellow'].join(';');
const message = 'Some Important Message Here';
console.log('%c%s', styles, message);

A small amount of styling can greatly improve debugging efficiency.

Source: translated from Medium article .

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

debuggingfrontendJavaScriptconsole.logCSS styling
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.