Monday 15 July 2019

Latest on CSS parent selector



The most recent information I can find regarding this is the W3C Selectors Level 4 Editor’s Draft, but, as far as I can see, it doesn't mention the parent selector anymore.



I know there was a Google survey about this, but that's over now.



What happened to the parent selector? Will it ever be introduced, or has it been removed?



Answer



The survey culminated in the subject selector (the proper name for the so-fabled "parent selector") being replaced with the far more versatile :has() pseudo-class, which is documented here (with an interesting anchor name, #relational, I wonder if that will stick).



Implementations will probably only arrive when the specification for this feature is more stable. Currently, with such disruptive changes as completely replacing the subject selector with a pseudo-class, I'm not banking on it happening anytime soon. That said, it is likely that the :has() pseudo-class will stick, but whether it can be implemented in CSS remains to be seen due to its very nature. See this section of the same draft to learn about implementation profiles.






The reason :has() is more versatile is because, with the subject selector, it was never made clear in any draft if a single complex selector could have more than one subject selector (since a single complex selector can only ever have one subject) and/or if functional pseudo-classes such as :matches() accepted the subject selector. But because a pseudo-class is a simple selector, you know that :has() can be accepted anywhere a pseudo-class is accepted.



As an example, this makes such selectors as the following quite theoretically possible:




/* 
* Select any p
* that is a sibling of a ul
* that has more than one li child.
*/
ul:has(> li:nth-of-type(2)) ~ p, /* p follows ul */
p:has(~ ul:has(> li:nth-of-type(2))) /* p precedes ul */



Whereas, using the subject selector, this would only be possible if :matches() accepted the subject selector, which was never stated directly in the spec:



ul:matches(! > li:nth-of-type(2)) ~ p, /* p follows ul */
!p ~ ul:matches(! > li:nth-of-type(2)) /* p precedes ul */


You can also see here why I dislike the name "parent selector" for either form of the selector — it can be used for so much more.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...