Home > Mobile >  How do I generate a darker color from a css hex color code?
How do I generate a darker color from a css hex color code?

Time:11-22

I don't want to use div:hover { filter: brightness(1.2) } although this would work, it only works on hover.

I'm looking to darken a color for a background-color value.

If I just remove the :hoverthen it darkens the whole element, including the color and background-color which are the same. Unreadlale with (white on white).

I want to darken just the background color and leave the color alone.

CodePudding user response:

Here is a cheap but really flexible and almost supported everywhere solution using background-image: linear-gradient() with a plain white / black :

div{
  height:5em;
  width : 5em ;
  display:inline-block;
}

div.lighter:hover{
 background-image: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)) ;
}

div.darker:hover{
 background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)) ;
}
<div class='lighter' style='background-color:Red;'></div>
<div class='darker' style='background-color:Red;'></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can change the opacity % within the rgba last value, or even use some gray / others colors if needed ! As background-image are display behind background-color without erasing anything, that's the solution I often use for similar case.

CodePudding user response:

I want to darken just the background color and leave the color alone.

If you apply an explicit z-index: 0 to the element, you may then attach to the element a ::before pseudo-element with the following properties:

  • a background-color
  • an opacity, to blend the pseudo-element's background-color with the element's background-color
  • a z-index lower than 0, so the pseudo-element's translucent background-color lies beneath all of the element's content

Working Example:

div {
  position: relative;
  display: inline-block;
  z-index: 0;
  width: 140px;
  height: 140px;
  line-height: 140px;
  margin-right: 12px;
  text-align: center;
  color: rgb(255, 255, 255);
  background-color: rgb(255, 255, 0);
}

.darker::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  z-index: -3;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.25);
}
<div>Normal Background</div>
<div class="darker">Darker Background</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  •  Tags:  
  • css
  • Related