Any way to style "parent" element with CSS

26

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

To be more specific, I am studying in localhost using the phpBB3 forums platform, when a message is grateful it gains the .bg1 class (the default being .bg2 ).

Both .bg1 and bg2 are direct children of class .pannels , since this does not change if the message is grateful or not.

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

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

<div class="pannels">
    <div class="bg2"></div>
</div>
    
asked by anonymous 24.04.2014 / 19:03

2 answers

24

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

In CSS specifications, CSS2 and #, there's nothing like that, you'll have to turn to JavaScript ( or jQuery,% with selector%) if you need to select a parent element.

Specification Update

There has been an upgrade to Level 4 Selector specs, where pseudo-class :has() looks like be the syntax chosen for this purpose so far (This is not a final specification and may undergo changes, or even be completely removed).

This is not available in any browser yet (17/10/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"*/ 
}
    
24.04.2014 / 19:12
12

This is called parent-selector , can not do this using CSS3 .

This has already been proposed, and something similar is to be implemented by CSS4 * level 4 selectors , using the $ tag before the hierarchy selector to which the style will be applied.

* According to the reference, CSS4 does not exist, but rather, Level 4 selectors .

EDIT: Fix

By checking the W3C specification stub , you can check that the currently proposed symbol is ! after the selector to be stylized.

    
24.04.2014 / 19:10