Some way to style "parent" element with CSS

Asked

Viewed 14,336 times

26

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 thankful it wins the class .bg1 (where the standard is .bg2).

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

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

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

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

    Why don’t you do it using jquery?

  • 5

    I’ll be using friend.. I just wondered if there was any way to do this in CSS before using jQuery...

2 answers

26


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

In the CSS specifications, CSS2 and CSS3, there is nothing in that sense, you will have to resort to Javascript (or jQuery, :has() selector) if you need to select a parent element.


Update in the Specification

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

This is not available in any browser so far (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"*/ 
}

12

That’s what they call selector, whereas cannot do this using CSS3.

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

* according to the reference, CSS4 does not exist, but yes, level 4 selectors.

EDIT: Correction

Checking by draft of W3C specification, it is possible to verify that the currently proposed symbol is the ! after the selector to be stylized.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.