DEV Community

Cover image for Style console.log() output with CSS - Part 2
Palash Mondal
Palash Mondal

Posted on • Edited on • Originally published at iampalash.hashnode.dev

Style console.log() output with CSS - Part 2

This video is part 2 of How to style console.log() output with CSS. In this video, I am going to explain about how can we create a generic logic so that we can easily style console log output and do it a bit faster.

Issue Faced

So, right now in order to apply a css styling to multiple console.log() output, we would do something like this:

console.log("%cSome text here 1", "color:green" );
console.log("%cSome text here 2", "color:red" );
console.log("%cSome text here 3", "color:blue" );

console.log("%cSome text here 4", "color:green" );
console.log("%cSome text here 5", "color:red" );
console.log("%cSome text here 6", "color:blue" );
Enter fullscreen mode Exit fullscreen mode

You can see in the above examples, only the console log text is changing and the style is being repeated multiple times. I think we can create a generic logic and just call few functions and pass the text as a parameter to those functions and that would handle the styling for us.

Solution

So first, we will create a main logColor function:

function logColor(color, args) {
  console.log("%c" + args.join(" "), "color:" + color);
}
Enter fullscreen mode Exit fullscreen mode

Then we will create a generic log object:

const log = {
  green: (...args) => logColor("green", args),
  red: (...args) => logColor("red", args),
  blue: (...args) => logColor("blue", args),
};
Enter fullscreen mode Exit fullscreen mode

and then we can call it like:

log.green("Some text here 1");
log.red("Some text here 2");
log.blue("Some text here 3");
Enter fullscreen mode Exit fullscreen mode

As you can see, we can now use these methods anywhere in your project without typing %c (CSS format specifier) and color name part every time. Yay!

Please check out this video where the solution for this issue is explained in full details:

How to style console.log() output with CSS - Part 2

Wrap Up

I hope you will find this video useful and learn something new in the process. If you want to learn more HTML, CSS, JavaScript and web development tips & tricks, please make sure to subscribe on YouTube.

Happy Coding!

Top comments (1)

Collapse
 
palashmon profile image
Palash Mondal

Awesome! 😃