Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do people mean when they say theres no parent selector in css?

For example lets say I have an HTML looking like the one below. Am I not selecting the parent element which is ul?

ul
  margin: 50px

ul.test
  li hello
  li how are u
like image 342
EEE Avatar asked Mar 10 '23 20:03

EEE


1 Answers

In order to understand what they mean you need to understand what selecting means in CSS (parent is easy :).

By selector they mean the element to which CSS applies. So, using CSS, if you have a selector (any selector), you cannot apply changes to any of the parent parts. You can only apply them to its last part. To the child (or, in some cases, to an immediate or distant following sibling).
(The simple rule here is that the part determining which element the styling will apply to is always the last part of the selector).

Let's take this simple selector:

ul { 
  /* rules apply to all ul */
}

I can make a rule to style up all it's children:

ul > * { 
    /* rules apply to * (all children of ul) */
}

But I cannot make a rule to style up its parent:

* < ul { 
  /* rules don't apply. this is invalid */ 
}

Whenever I make a rule, like...

* > ul {
  /* rules apply to any ul that is a child of * (any element) */
}

the style always applies to the last item in the selector, never to one of the parents.

That's why there's no parent selector in CSS. You can't style a parent based on selecting one of its children. You need to select it. Got it?


Heck, I'll give you an example.

Consider this markup, but imagine it 10 times more complex (let's assume there's a bunch of guys adding/removing parts from it so it can have huge depth):

<div>
  <whatever></whatever>
</div>
<span>
  <whatever></whatever>
</span>
<ul>
   <li>
     <whatever></whatever>
   </li>
   <li></li>
   <li>
     <whatever></whatever>
   </li>
 </ul>

Now, please create a CSS that would make all parents (one single level ancestors) of <whatever> have a red background, no matter where they are in DOM. Can you?
Here's some news: you can't.

The closest they got to making this happen was when :has() selector has been proposed, but it's been rejected. This selector would need the CSS parser to go back, and it always goes forward. That's why it's fast, no matter the device/browser/system. CSS is always fast.

Because it has no :has() selector (or < combinator).

Additional note: As @Maximus has noted in comments, shadow DOM elements provide a method to select the top level element of the current shadow DOM instance by using :host. It's not a proper parent selector, as it doesn't provide means to select parent elements inside the shadow DOM, but only the entry point (the contact point with the normal DOM), giving you the option to apply rules to the current shadow DOM instance and not to others.

like image 51
tao Avatar answered Apr 24 '23 22:04

tao