I've Tweet this a few days ago and it got a little attention from the community.
While you're here you might want to follow me on Twitter
Liquid error: internal
The main reason for writing this post is to explain why to use 16777215, looks kind of a random number and can be a little misleading.
Why 16777215?
If you're familiar with RGB (Red, Green, Blue), you know it's represented by a number from 0 to 255, an example of a colour using RGB would look like:
/* Same as #ffffff */
color: rgb(255, 255, 255);
Now, if we do 256 * 256 * 256 we end up with 16,777,216, now why do we remove 1 from this value?
We want to convert into a hexadecimal format and 16777216 converts to 1000000, while 16777215 converts to ffffff.
I did a little research but mainly this came from here, thanks Jacob:
@ajaykarwal @telmo Red, green, and Blue are each represented by a number from 0 to 255
256 * 256 * 256 = 1677721602:57 AM - 15 Mar 2020
There are other explanations, based directly on the hexadecimal code, but I felt this one made more sense and it was simpler.
Happy to discuss this further and give me a shout if you think something's not right. I'm always open to learning something new. Connect on Twitter if you want to discuss.
Hope this makes sense to you 🔥
Top comments (8)
Great explanation, but that method can generate hexadecimal numbers with less than six digits, so you might want to pad the start with zeroes.
You could also use
(16777216 * (1 + Math.random()) | 0).toString(16).slice(1).Thanks for that 🙏
lets test this trick, in this page open chrome console and paste this code, and see the title change color:
Awesome 😆
parseInt('ffffff', 16)would be more straightforward and easy to refractor.BTW,
parseInt('ffffffff', 16)if you need alpha channel (opacity).It seems that
0xFFFFFFalso works.Thanks 🙏
Nice article, Thanks @telmo