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

前端 未结 3 1301
终归单人心
终归单人心 2020-12-04 03:15

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

Something like:

.child-class {
             


        
相关标签:
3条回答
  • 2020-12-04 03:59

    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.

    0 讨论(0)
  • 2020-12-04 04:01

    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.

    0 讨论(0)
  • 2020-12-04 04:04

    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

    0 讨论(0)
提交回复
热议问题