div {
  width: 150px;
  height: 150px;
  display: inline-block;
  text-align: center;
  line-height: 150px;
}
div p {
  margin: 0px;
  font-size: 2em;
}
function invertColor(hex) {
    //      /-- add the # to the front of the code
    //      |   /-- #ffffff converted to a decimal
    //      |   |                       /-- strip out any # in the input
    //      |   |                       |                   /-- cast the string to an int assuming the string is base16
    //      |   |                       |                   |    /-- convert inverse decimal to base 16 string
    //      |   |                       |                   |    |            /-- pad the front with 0s if the decimal number is small
    //      |   |                       |                   |    |            |
    return '#'+(16777215 - parseInt(hex.replace(/\#/g, ''), 16)).toString(16).padStart(6, '0');
}



// Let's generate a bunch of boxes with random colors and labels that are the inverse of those colors
(function() {
  for (var i = 0; i < 50; i++) {
    color = '#'+(Math.random()*0xFFFFFF<<0).toString(16); // generate random color
    var div = document.createElement('div'); // create div element
    div.style.backgroundColor = color; // set background-color on that div to the color we generated
    var label = document.createElement('p'); // create a p element
    label.textContent = color; // set the text of the p element to the color
    label.style.color = invertColor(color); // set the color of the p element to the inverseColor
    div.appendChild(label); // put the p inside the div
    document.body.appendChild(div); // add the div to the body
  }
}())

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.