html – Some way to style "parent" element with CSS

Question:

Hello, is there any way to select the parent element of another element with CSS?

To be more specific, I'm studying on localhost using the phpBB3 forum platform, when a message is thanked it gets the .bg1 class (default is .bg2 ).

Both .bg1 and bg2 are direct children of the .pannels class, as it does not change whether the message is grateful or not.

My goal is to stylize the class .pannels with a background-color:#eaf8e2 only if the child element of it is the .bg1 if the .bg2 would like to keep the color #fff the background.

<div class="pannels">
    <div class="bg1"></div>
</div>

<div class="pannels">
    <div class="bg2"></div>
</div>

Answer:

There is currently no way to select the parent of an element in CSS.

In the CSS, CSS2 and CSS3 specs, there's nothing to that effect, you'll have to resort to JavaScript ( or jQuery, :has() selector ) if you need to select a parent element.


Specification Update

There has been an update to the Level 4 Selectors spec, where the pseudo-class :has() seems to be the syntax of choice for this purpose so far (This is not a final spec and may change, or even be removed altogether. ).

This is not available in any browser so far (10/17/2017):

With this pseudo-class, the solution to the problem proposed in the question would be:

div.pannels:has(> div.bg1) 
{ 
    /* styles serão aplicados ao "div.pannels" elemento que tenham um elemento filho "div.bg1"*/ 
}
Scroll to Top