How do I apply formatting on the parent element through the child element class with CSS or SASS?

1

I have the following structure just for example:

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

I have class .filho with position: absolute ; I would like to know if using .filho I can also apply a position: relative; to div parent using css or sass only?

I know I can create a class for div parent. But I would like to know if there is a way to select a parent element through a child element in css. I researched and could not find anything to help me!

    
asked by anonymous 15.08.2016 / 15:53

1 answer

2

TL; DR : There are no parent selectors in 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 %

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

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

What it generates

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

But note that you still need to somehow reference the parent selector, however generic it may be. Here comes a bit of cascading knowledge to maybe be able to simulate dynamic behavior, but it will never be 100% accurate.

This article talks about the problem in question, and emphasizes the fact that using CSS3 pure, 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 parent() ), but that's still a distant dream.

    
15.08.2016 / 16:16