Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lighten parent's (unknown) background-color in child

Tags:

css

less

Is there a way in less or (css3 in general) to access parent's background-color without knowing it?

Something like:

.child-class {
    background-color: lighten(parent-background-color, 30%);
}

A less variable would be the obvious approach but in this case I simply don't know the parent's background-color as it can be dynamically styled.

Anybody got something in her trick box to help out?

like image 594
Harald Avatar asked Feb 06 '14 00:02

Harald


3 Answers

You Can Achieve the Effect

Technically the answer "no" is correct. However, because we are talking about "lightening" (or "darkening"), that is, adding white or black, then the effect can be achieved still through either css3 rgba() colors or opacity on a pseudo element. Consider these (each would be used on the child element):

Opt #1: CSS3 rgba

.lighten {
    background-color: rgba(255, 255, 255, 0.3);
}

Opt #2: CSS2 Pseudo-element with opacity

.lighten{
    position: relative;
    z-index: 0;
}

.lighten:before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: -1;
    background-color: #fff;
    opacity: 0.3;
}

See an example fiddle showing both options

like image 119
ScottS Avatar answered Oct 27 '22 18:10

ScottS


EDIT: Have a look at ScottS's answer for a clever solution that is probably what you need.

That cannot be done in pure css. The reason is that these types of references could lead to 'circular' situations. Or situations where the DOM has to be looped over multiple times to determine the final value. Both these situations are something css always avoids.

Now, if your main goal is to define a 'pallette' of sorts and have all your colors work together, you should look into CSS expansion tools like "SASS" or "LESS". They could let you define colors and change them and do other useful comparison things. Have a look at those tools if you want such flexibility. They cannot however, do direct comparison like you ask, since they just reduce to css in the end.

This can easily be done using JavaScript, and even more easily using jQuery. I wont clutter this answer with JavaScript/jQuery code when it probably isn't what you need.

like image 4
Damien Black Avatar answered Oct 27 '22 20:10

Damien Black


It's actually possible with the new backdrop-filter property but the browser support isn't very good at the moment.

.child {
  backdrop-filter: brightness(1.5);
}

For now, I would still stick with a white/black alpha background color, which works well for grayscale backgrounds.

like image 2
janispritzkau Avatar answered Oct 27 '22 19:10

janispritzkau