Search code examples
csscolorsbackground-color

Change the shade of the color, with the reference to the original one


<style>
    div.red {
        border-left: 5px solid rgb(255, 96, 92);
        margin: auto;
        padding: 0.5em 1em;
        width: 95%;
    }
</style>

<div class="red">
    <p>Aaa aaa aaa aaa aaa</p>

    <div class="red">
        <p>Aaa aaa aaa aaa aaa</p>
    </div>
</div>

I have a base color (rgb(255, 96, 92)) and I need to incorporate it into the styling of divs, as a background.

The background of the divs should be something lighter then the base color, similar to

div.red {
    rgba(255, 96, 92, 0.25);
}

However, I cannot use

background: {rgba(255, 96, 92, 0.25);}

directly, because it changes the background color of the nested div.

Opacity is not suitable as well, because it changes the color of the text.

div.red {
    background: rgb(255, 96, 92);
    opacity: 0.25;
}

Filters are not suitable for the same reason as the opacity: they affects the text.

Another option I'm aware of is the HUE color model. It is not suitable because I need to keep the reference to the base color.

rgb(255, 96, 92) is the same as hsl(1, 100%, 68%). I can change 68 to 93 and it will give the desired visual effect. But now I cannot say, looking into my code, which color was the base one.

div.red {
    background: hsl(1, 100%, 93%);
}

The best way I am searching for is something like

div.red {
    background: rgba(255, 96, 92, 0.25);
    background-alpha-channel: separate; /* separate or merge,
                                           depending of what you need. */
}

Solution

  • Use pseudo element as a background layer and apply the filter there:

    div.red {
      border-left: 5px solid rgb(255, 96, 92);
      margin: auto;
      padding: 0.5em 1em;
      width: 95%;
      position: relative;
      z-index: 0;
    }
    
    .red:before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: -1;
      background: rgba(255, 96, 92);
      filter: brightness(2);
    }
    <div class="red">
      <p>Aaa aaa aaa aaa aaa</p>
    
      <div class="red">
        <p>Aaa aaa aaa aaa aaa</p>
      </div>
    </div>

    Another idea is to consider two background layer where the top one is a white color having alpha. Add more white will make the color more bright.

    div.red {
      border-left: 5px solid rgb(255, 96, 92);
      margin: auto;
      padding: 0.5em 1em;
      width: 95%;
      background: 
        linear-gradient(rgba(255,255,255,0.5),rgba(255,255,255,0.5)),
        rgba(255, 96, 92)
    }
    <div class="red">
      <p>Aaa aaa aaa aaa aaa</p>
    
      <div class="red">
        <p>Aaa aaa aaa aaa aaa</p>
      </div>
    </div>