carewithl
carewithl

Reputation: 1153

Understanding more complex examples of descendant selectors

I somewhat understand descendant selectors, but the more complex examples are giving me trouble. For example:

#content .alternative p

Should this rule apply to p elements that are descendants of elements E, where E are :

Or should rule apply to p elements that are:

How about the following rule?

#content .alternative .alternative1 p

Upvotes: 5

Views: 390

Answers (4)

Chuck
Chuck

Reputation: 237060

The first one is the correct description. Your second interpretation would be written in CSS as:

#content p.alternative

Since the .alternative is attached to the p in that version, it's a qualifier rather than specifying a descendent. If you instead write it as

#content p .alternative

it would mean elements of class .alternative that are descendents of p elements that are descendents of the #content element.

Upvotes: 1

Frank Schwieterman
Frank Schwieterman

Reputation: 24480

Each section of the specifier separated by a space refers to a separate node in the document. So its the first one.

Upvotes: 1

Quentin
Quentin

Reputation: 943635

The right most component of the selector is the part that actually picks the element. A space is a descendant selector. If there isn't a space then the selectors all apply to one element.

#content .alternative p

p element contained in an element of class alternative contained in an element of id content.

#content .alternative .alternative1 p

p element contained in an element of class alternative1 contained in an element of class alternative contained in an element of id content.

#content p.alternative.alternative1

p element of class alternative1 and of class alternative contained in an element of id content.

Upvotes: 6

Januz
Januz

Reputation: 527

About the first question: applies to p elements that are: descendants of element #content and also descendants of elements with class .alternative

The second one is the same, just with an extra level of depth.

Check this link for more info on selectors

Upvotes: 7

Related Questions