Deniz R. - 2 months ago 7

HTML Question

This question is for learning purposes only. I understand the logic behind math operations in SASS when calculating hex colors, i.e.:

`<div>Style me</div>`

div {

color: #010203 + #010203;

}

I know it will be calculated in this way:

`01 + 01 = 02`

02 + 02 = 04

03 + 03 = 06

which will compile to:

`color #020406;`

More precisely:

`div {`

color: #020406;

}

How are hex colors calculated when you have letters in them? For example:

`div {`

color: #a1b1c1 + a2b2c2;

}

Are they calculated like this:

`a1 + a2 = a3`

b1 + b2 = b3

c1 + c2 = c3

which would compile to

`color: #a3b3c3;`

If so, how would then

`div {`

color: #a1a2a3 + #b1b2b3;

}

calculate?

Would

`a1 + b1`

`c2`

If it would, what would happen with:

- multiplication
`*`

- division
`/`

- modulo
`%`

I know this is a very long question and I apologize for that.

Thank you.

Answer

In the example of `#010203 + #010203`

you should first split the string to retrieve RGB channels, so than you can do RED+RED

```
var R1 = parseInt("01", 16); // 1
var R2 = parseInt("01", 16); // 1
var R1R2 = Math.min(R1 + R2, 255); // 2
console.log( R1R2.toString(16) ); // "2"
```

add a leading zero and here you go with `02`

, repeat for all other channels and you got your `#020406`

Let's see another example with letters:

```
var R1 = parseInt("9f", 16); // 195
var R2 = parseInt("ae", 16); // 174
var R1R2 = Math.min(R1 + R2, 255); // 255 <<< !!!!!
console.log( R1R2.toString(16) ); // "ff"
```

so since R1 + R2 are exceeding 255 max value for RED channel, 255 will be used,

convert it back to HEX and you have `ff`

.

**To conclude:**

`#ff0000 + #00ffff = #ffffff`

which makes quite sense but let's see further:

`#eeeeee + #eeeeee = #ffffff`

which could make you conclude every HEX+HEX (R,G or B) channel that sums over 255 stays at 255. (pseudo-code:) `Min( R1_16 + R2_16, 255)`

Source (Stackoverflow)

Comments