Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to select elements that do not have a child of a certain type?

I'm trying to select <a> elements that are not the parents of <img> elements. (Note: if it's relevant some of the anchors I want to select are childless.) I tried this:

a > :not(img) {}

and this:

a:not(> img) {}

but neither of them seem to work. How would I accomplish this in CSS?

like image 609
James Ko Avatar asked Apr 06 '18 20:04

James Ko


People also ask

What is the class used to select an element which has no child?

The :empty CSS pseudo-class represents any element that has no children.

Which is the correct way to select child element?

The element > element selector selects those elements which are the children of the specific parent. The operand on the left side of > is the parent and the operand on the right is the children element. Example: Match all <p> element that are child of only <div> element.


1 Answers

There is a spec, currently in draft, for a :has() pseudo-class. No browser supports it yet. If the spec is someday approved and implemented, you'd be able to do this:

a:not(:has(img)) {
    // Styles
}

The MDN page says that :has would never work in stylesheets, only in JavaScript; but in saying that, it links to a section of the spec about a "dynamic selector profile" that apparently no longer exists.

I think the browser vendors typically have a problem with implementing CSS features that require knowledge of the DOM that only exists after the selected element is created, so I don't know if we should get our hopes up for this. Someone who follows the mailing lists or is generally smarter than me might offer a better prognosis.

like image 128
75th Trombone Avatar answered Sep 23 '22 20:09

75th Trombone