Search code examples
javascriptcssconsolestylingconsole.log

Multiple Color Styles in a single console.log()?


I have an array of hex values,

"colors": ["#d5dd90","#e6bb45","#ef9770"]

I can log these out like this:

colors.forEach((value)=>{
  console.log('%cABC', `background: ${value};`);
})

which results in 3 separate console.log() entries:

ABC

______________

ABC

______________

ABC

______________

Each 'ABC' being a different color, one log() called for each item in the array.

What I'd like to do write each item in one line, like so:

ABC ABC ABC

______________

So basically have one log() call for each array, each styled with its respective color.

I can do that here: let colors= ["#d5dd90","#e6bb45","#ef9770"] console.log('%cABC %cABC %cABC', color:${colors[0]}, color:${colors[1]}, color:${colors[2]});

I have multiple arrays, so I'd need to do this within a for() loop, which is the part I'm having trouble with


Solution

  • %c can be used multiple times in the string to log.

    const colors = ["#d5dd90","#e6bb45","#ef9770"];
    console.log(colors.map(c => `%c${c}`).join(''), ...colors.map(c => `background: ${c};`));
    Open the browser console to see the result