Martin
Martin

Reputation: 24318

Confusion with selectors, div ~ h1 vs div > h1

I am having a problem understanding the div ~ h1, it appears it selects all h1 tags that directly follow a div.

But isn't this what div > h1 actually does ?

It selects all h1 that is a direct child of the div ?

I also came across div + h1 and at first i was confused, but this appears to select only a single element i.e 1 H1 tag that follows a div.

Upvotes: 1

Views: 916

Answers (2)

Mike H.
Mike H.

Reputation: 1751

p ~ ul

The ~ selects every UL element that are preceded by a P element

body > P

Sets the style of all P elements that are children of BODY.

http://www.w3.org/TR/CSS2/selector.html

In other words

The ~ selector uses an immediate predecessor clause whereas the > is more general, targeting all children no matter how far from their parent.

Upvotes: 1

avrahamcool
avrahamcool

Reputation: 14094

div ~ h1 will select all the h1 following siblings [brothers] (not just the immediate one).

div + h1 will select only the immediate brother h1 following the div.

div > h1 will select all the h1 that are direct children of the div.

div h1 will select all the h1 that are nested in the div (not just direct children).

all of that, and more can be found here

Upvotes: 5

Related Questions