I have script that set cell background dependent on selected item from dropdown. There are a lot of colors to choose from. Some of them are dark, so the dark text is invisible. Is there any way to automatically set the text color to contrast with the background?
2 Answers
If you are setting the background color then you can set the font color at the same time. I think your question is "how do I automatically find a font color that will contrast with the background color".
This has a very long answer with lots of code here.
There are various ways of finding a color that will compliment a specified color using the hexadecimal representation of the rgb values.
The simplest is to just take a logical compliment of the RGB values - it won't necessarily be pleasing but it should contrast enough to be legible:
function getOppositeColor(color) {
// color comes in as #AAAAAA
// step one - convert to a number - 0xAAAAAA
var hex = '0x' + color.split("#")[1];
var backgroundColor = parseInt(hex, 16);
// take the logical compliment of it 0x000000 -> 0xffffff
var complement = 0xffffff ^ backgroundColor;
// convert compliment to hex
var complementHex = complement.toString(16);
// complement Hex needs to be padded to 6 hex digits
var padding = "";
if (complementHex.length < 6) {
padding = Array(6 - complementHex.length + 1).join("0");
}
var opposite = "#" + padding + complementHex;
return opposite;
}
This simple test will set a contrasting font color for the current cell:
function setComplimentaryColor() {
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var background = cell.getBackground();
var opposite = getOppositeColor(background);
cell.setFontColor(opposite);
}

- 1,550
- 1
- 13
- 20
-
It almost works... not entirely, but thank you for coming up with an idea! when set background #8E7CC3 it set font color rgb(113,131,60) - no contrast – Peter222 May 15 '18 at 19:34
If you are using conditional formatting then you can configure both the foreground and background colors for whatever you choose from the drop down.
If you are not using conditional formatting, you should check and see if it will meet your requirements as it is a very useful feature and generally better than rolling your own in a script.

- 1,550
- 1
- 13
- 20
-
I can't use conditional formatting in this case... Even if I could, I would still have to manually specify the colour of the text to contrast with the background. The point is that when the background colour is indicated, the text colour is automatically adjusted to contrast. – Peter222 May 15 '18 at 11:38
-
@Peter222 no, it shouldn't automatically be done. Yes, when you manually specify the background color, you should manually specify the text color. – tehhowch May 15 '18 at 12:29