ExampleSelect and style every Show
element where the parent is a element: div > p { Definition and UsageThe element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected. Browser SupportThe numbers in the table specifies the first browser version that fully supports the selector. Selectorelement>elementYes7.0YesYesYes CSS Syntaxelement > element { Having a “parent selector” in CSS is mentioned regularly as something CSS could really use. I feel like I’ve had that thought plenty of times myself, but then when I ask my brain for a use case, I find it hard to think of one. Well, I just had one so I thought I’d document it here. A classic parent/child:
Say it makes a lot of sense for this parent to have hidden overflow and also for the child to use absolute positioning.
Now let’s say there’s one special circumstance where the child needs to be positioned outside the parent and still be visible. Hidden overflow is still a good default for the vast majority of situations, so it’s best to leave that rule in place, but in this very specific situation, we need to override that overflow.
That selector above is fake but it’s saying, “Select the parent of
…which is selecting the element on the left rather than the right. Who knows? Probably both of those are problematic somehow and the final syntax would be something else. Or maybe we’ll never get it. I have no idea. Just documenting a real use case I had. You might be thinking, “Why not just use another special class on the parent?” I would have, but the parent was being injected by a third-party library through an API that did not offer to add a class of my choosing on it. Ultimately, I did have to add the class to the parent by writing some custom JavaScript that queried the DOM to find the Do y’all have some other use-cases for a parent selector? Here’s one from Uzair Hayat:
|