htmlcss

How can I inherit color from currentColor when setting opacity?


Is there a method in which I can change the opacity of a border which is being set to inherit its color from currentColor? I.e. inherit currentColor in #inner2 and set its opacity to 0.25.

Searching for a pure CSS solution please.

For example, something which resembles the following:

#outer{
  color: rgba(255,0,0,1);
}

.inner{
  display: block;
  width: 100%;
  height: 10px;
  margin-bottom: 5px;
  border: 2px solid currentColor;
}

#inner2{
  /* This is where I want to inherit current color */
  /* ... but still set it to 0.25 opacity */
  border-color: rgba(255,0,0,0.25);
}
<div id='outer'>
  <div id='inner1' class='inner'></div>
  <div id='inner2' class='inner'></div>
</div>


Solution

  • You can now achieve this in a more direct way, at least in modern browsers ("baseline" since May 2023), using the color-mix function.

    Example:

    #outer {
      color: rgba(255,0,0,1);
    }
    
    .inner {
      display: block;
      width: 100%;
      height: 10px;
      margin-bottom: 5px;
      border: 2px solid currentColor;
    }
    
    #inner2 {
      border-color: color-mix(in srgb, currentColor 25%, transparent);
    }
    <div id='outer'>
      <div id='inner1' class='inner'></div>
      <div id='inner2' class='inner'></div>
    </div>

    You can choose a colour space (I chose SRGB for you here), and the proportion for the mixture. If you leave out the proportion, it defaults to 50%.

    Note, however, that if the current colour is already partially transparent, this will make it more transparent; this does not replace the alpha channel. For that we need to wait for relative colors (another part of CSS Color Level 5).