How to apply formatting to the parent element through the child element class with CSS or SASS?

Asked

Viewed 1,880 times

1

I have the following structure just for example:

<div>
    <div class="filho">teste</div>
</div>

I have the class .filho with a position: absolute; I wonder if through class .filho I can also apply a position: relative; in div parent using css or Sass only?

I know I can create a class for the div father. But I wonder if there is a way to select a parent element through a child element in css. I searched and couldn’t find anything to help me!

1 answer

2


TL;DR: Do not exist Parent selectors in the CSS (yet).

There are several ways to dynamically select the parent of an element, but they all involve a bit of Javascript such as the method parent() jQuery.

Using SASS, you can do something using the operator ampersand:

.filho{
  position: absolute;
  div &{
    position: relative;
  }
}

what generates

.filho {
  position: absolute;
}
div .filho {
  position: relative;
}

But note that you still need to somehow reference the parent selector, no matter how generic it is. Here comes some knowledge about cascading for maybe can simulate dynamic behavior, but this will never be 100% accurate.

This article talks about the problem in question, and emphasizes the fact that, using pure CSS3, it is impossible to make this selection of the parent element. There are even proposals for a new pseudo-element for the new specification (something like .teste:parent), but this is still a distant dream.

  • Very good explanation. Thanks! ;)

  • @Lan, if the answer pleases you, do not forget to mark it as correct, if no other better! =)

  • 1

    Oops! I didn’t know this option! But now it’s checked!

Browser other questions tagged

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