Search code examples
htmlcsscolorsbackground-color

How is alpha added in CSS?


Consider the following three divs:

.example-single {
  min-height: 100px;
  min-width: 100px;
  background-color: #04B43188;
}

.example-single:hover {
  background-color: #04B431CC;
}

.example-parent {
  min-height: 100px;
  min-width: 100px;
  background-color: #04B43188;
}

.example-child {
  height: 100px;
  width: 100%;
  background-color: transparent;
}

.example-child:hover {
  background-color: #04B43144;
  /* what alpha is needed here?! */
}

.reference {
  min-height: 100px;
  min-width: 100px;
  background-color: #04B431CC;
}
<div class="example-single">Single
</div>

<div class="reference">Reference
</div>

<div class="example-parent">
  <div class="example-child">Nested
  </div>
</div>

The goal is to have both the single and the nested div to have the same color when hovering (in this case to match the reference div). For the single div this is easy, but for the nested divs the colors of the parent and child are overlayed. How do I calculate the alpha value I need to give the child to achieve this?


Solution

  • Say you have two black elements overlapping, 50% opacity each, the overlapping section would have the alpha of (1-(0.5*0.5))*100, or 75% alpha.

    Example of two opaque, overlapping divs with a background of #000000 and alpha of 50%

    In your case, the added alpha of #XXXXXX88 (decimal value of 136, or 53% of 255) and #XXXXXXCC (decimal value of 204, or 80% of 255) would be (1-(0.53*0.8))*100 = 57.6% (or #XXXXXX93).

    I personally recommend using rgba values instead of hex values for readability where you can define alpha as decimals instead of hexadecimals.