Background/Foreground Color Contrast

In this example below you will see how to do a Background/Foreground Color Contrast with some HTML / CSS and Javascript

Base on the background color input the foreground text color will change to black or white for a better contrast ratio.

Thumbnail
This awesome code was written by Giovanni, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Giovanni ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Background/Foreground Color Contrast</title>
  <meta name="viewport" content="width=device-width, initial-scale=1"><link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container app" id="app">
  <div class="app--container">

    <h1><strong>BG/FG Color</strong> Contrast Tool</h1>
    <p>As you enter a background color the foreground text changes to <strong>black</strong> or <strong>white</strong> for a better contrast, give it a try! <strong>Note</strong>: currently 4-hex and 8-hex notation is not supported, these new notations support
      alpha and transparency.</p>
    <div class="app--controls">
      <div class="app--controls-half">
        <label for="hexcolor">Enter hex notation color</label>
        <input title="Enter Hex notation color code" type="text" name="hex" id="hexcolor" maxlength="6" placeholder="#" autofocus value>
      </div>
    </div>
    <div class="app--result">
      <p><strong>Results:</strong></p>
      <div id="result"></div>
    </div>
    <footer>
      <p>Made with &#10084; by <a href="giovannilara.com">Giovanni Lara.</a> All Rights Reserved. MIT Licensed.</p>
    </footer>
  </div>
</div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Giovanni/backgroundforeground-color-contrast-EQLjvO */
*,
*:before,
*:after {
  box-sizing: border-box;
}

.group:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

* html .group {
  zoom: 1;
}

*:first-child + html .group {
  zoom: 1;
}

html {
  font-size: 1em;
}

body {
  background-color: #bad;
  color: #000;
  font: 16px/1.5 "Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  font-weight: 300;
}

a {
  color: inherit;
}
a:hover {
  color: slateblue;
}

code {
  font-family: monospace;
  font-size: 1em;
  font-weight: normal;
  background: mediumspringgreen;
  padding: 1px 3px 1px;
  border-radius: 4px;
}

footer {
  padding: 6em 0 2em;
  clear: both;
}

strong {
  font-weight: 900;
}

h1,
h2,
h3,
h4 {
  line-height: 1.2;
  margin: 1.618em 0 1.618em;
}

h1 {
  margin-top: 0;
  font-size: 2.618em;
}

p {
  margin-bottom: 1.45em;
}
p:last-of-type {
  margin-bottom: 0;
}

input, button {
  font-size: 1.222em;
  padding: .5em;
}

label {
  padding: 1em 0 1em;
  font-weight: 700;
  font-size: 1.222em;
}

input[type="number"], input[type="text"] {
  width: 70%;
  margin-top: 0.5em;
  display: block;
  color: #000;
  font-weight: 900;
  border: 4px solid transparent;
  border-radius: 4px;
  outline: none;
  transition: all 0.45s ease-in;
  box-shadow: -5px -5px 25px -4px rgba(0, 0, 0, 0.25), 5px 5px 25px -4px rgba(0, 0, 0, 0.25);
}
input[type="number"]::-webkit-input-placeholder, input[type="text"]::-webkit-input-placeholder {
  color: #b3b3b3;
}
input[type="number"]:-ms-input-placeholder, input[type="text"]:-ms-input-placeholder {
  color: #b3b3b3;
}
input[type="number"]::-ms-input-placeholder, input[type="text"]::-ms-input-placeholder {
  color: #b3b3b3;
}
input[type="number"]::placeholder, input[type="text"]::placeholder {
  color: #b3b3b3;
}
input[type="number"]:focus, input[type="text"]:focus {
  border-width: 4px;
  border-color: #000;
  color: #000;
  box-shadow: -1px -1px 25px 1px rgba(0, 0, 0, 0.35), 1px 1px 25px 1px rgba(0, 0, 0, 0.35);
}

/* Remove controls from Firefox */
input[type="number"] {
  -moz-appearance: textfield;
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

button, input[type="button"] {
  width: 50%;
  margin-top: 1.45em;
  background-color: #000;
  color: #fff;
  border: 4px solid transparent;
  border-radius: 4px;
  font-weight: bold;
}

.container {
  max-width: 700px;
  width: 98%;
  margin: 0 auto;
}

.app--container {
  padding: 3em 1em 3em;
}
.app--controls {
  padding-top: 2em;
}
.app--controls-half {
  float: left;
  width: 50%;
}
.app--controls-half:last-of-type {
  margin-bottom: 0;
}
@media (max-width: 26.563em) {
  .app--controls-half {
    width: 100%;
    margin-bottom: 2em;
  }
}
.app--controls-third {
  float: left;
  width: 33.333%;
}
@media (max-width: 26.563em) {
  .app--controls-third {
    width: 100%;
    margin-bottom: 2em;
  }
}
.app--result {
  padding-top: 2em;
  margin-top: 2em;
  clear: both;
}
.app--result span {
  font-weight: bold;
}

#result {
  overflow-wrap: break-word;
}


/*Downloaded from https://www.codeseek.co/Giovanni/backgroundforeground-color-contrast-EQLjvO */
const black = "#000",
  white = "#fff";
let hex = document.getElementById("hexcolor"),
  body = document.querySelector("body"),
  app = document.getElementById("app"),
  result = document.getElementById("result");

hex.addEventListener("keyup", themeBody);

function themeBody() {
  let hexlen = hex.value.length,
    sR = R(hex.value[0] + hex.value[1]) * 1,
    sG = G(hex.value[2] + hex.value[3]) * 1,
    sB = B(hex.value[4] + hex.value[5]) * 1,
    r0 = R(hex.value[0] + hex.value[0]) * 1,
    g1 = G(hex.value[1] + hex.value[1]) * 1,
    b2 = B(hex.value[2] + hex.value[2]) * 1,
    isHex = /^[0-9a-f]|[A-F]{3}(?:[0-9a-f]|[A-F]{3})?$/i,
    brightnessValue = null;
  // hex short
  if (hexlen === 3) {
    if (isHex.test(`${r0 + g1 + b2}`)) {
      brightnessValue = brightness(r0, g1, b2);
      contentColor(brightnessValue);
    } // hex long
  } else if (hexlen === 6) {
    // hex pair
    if (isHex.test(`${sR + sG + sB}`)) {
      brightnessValue = brightness(sR, sG, sB);
      contentColor(brightnessValue);
    }
  }
  let color =
    hexlen <= 6
      ? (body.style.backgroundColor = `#${hex.value}`)
      : (body.style.backgroundColor = "initial");
}
function R(r) {
  return `0x${r}`;
}
function G(g) {
  return `0x${g}`;
}
function B(b) {
  return `0x${b}`;
}
function brightness(r, g, b) {
  let light = Math.sqrt(0.241 * r * r + 0.691 * g * g + 0.068 * b * b);
  return light;
}
function contentColor(b) {
  if (b < 130) {
    app.style.color = white;
    result.innerHTML = `<p><strong>background-color : </strong>#${
      hex.value
    } <br><strong>color : </strong> ${white}</p>`;
  } else {
    app.style.color = black;
    result.innerHTML = `<p><strong>background-color : </strong>#${
      hex.value
    } <br><strong>color : </strong>${black}</p>`;
  }
}

Comments