简体   繁体   中英

CSS selectors Descendant selectors

I couldnt understand the below from W3C spec.

div * p

matches a P element that is a grandchild or later descendant of a DIV element. Note the white space on either side of the "*" is not part of the universal selector; the white space is a combinator indicating that the DIV must be the ancestor of some element , and that that element must be an ancestor of the P.

How the white space is a combinator indicating that the DIV must be the ancestor of some element?

Please help to clarify

To answer your question, you need to first understand how CSS rules are interpreted by the browser.

Whenever you write a CSS selector, you can use one or many elements in the selector. For instance, the selector div has one element, both div p and div > p have two.

Think of a CSS selector as several stages of filtering. CSS selectors are actually interpreted by the browser reading them from right to left. When multiple elements are specified in a selector, you first find the set all the elements for the right-most piece, then filter that set by the next piece, and so on.

In the case of the div rule, we are saying "find me all 'div' elements on the page". Simple enough.

In the case of the div p rule, we first "find all the 'p' elements on the page". But then, for each of those 'p' elements, we then ask "give me just the 'p' elements that have a 'div' as an ancestor".

Using the same logic, let's describe div * p : we first "find all the 'p' elements on the page". Next, we ask "give me just the 'p' elements that have a parent element of any kind". From that set, we then ask 'give me just the elements out of this set that have a 'div' as an ancestor".

The selector div * p would be almost the same as div p , but with one key difference: the <div> would have to be at least a grandparent of the <p> for the selector to match. See http://jsfiddle.net/cDTGY/ for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM