248

If I have a header tag <h1 class="hc-reform">title</h1>

h1.hc-reform{
    float:left;
    font-size:30px;
    color:#0e73bb;
    font-weight:bold;
    margin:10px 0px;
}

and after that I have a paragraph <p>stuff here</p>.

How can I ensure using CSS that every <p> tag that follows the h1.hc-reform to use: clear:both;

would that be:

h1.hc-reform > p{
     clear:both;
}

for some reason that's not working.

Ramratan Gupta
  • 1,056
  • 3
  • 17
  • 39
tony noriega
  • 7,523
  • 17
  • 53
  • 72

5 Answers5

464

This is called the adjacent sibling selector, and it is represented by a plus sign...

h1.hc-reform + p {
  clear:both;
}

Note: this is not supported in IE6 or older.

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
83

You can use the sibling selector ~:

h1.hc-reform ~ p{
     clear:both;
}

This selects all the p elements that come after .hc-reform, not just the first one.

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
  • The IE bugs in the first link are obscure edge case stuff, which is probably why quirksmode overlooks them. – Ax. Sep 07 '10 at 16:25
16

no > is a child selector.

the one you want is +

so try h1.hc-reform + p

browser support isn't great

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
9

The > is a child selector. So if your HTML looks like this:

<h1 class="hc-reform">
    title
    <p>stuff here</p>
</h1>

... then that's your ticket.

But if your HTML looks like this:

<h1 class="hc-reform">
    title
</h1>
<p>stuff here</p>

Then you want the adjacent selector:

h1.hc-reform + p{
     clear:both;
}
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
2

Not exactly. The h1.hc-reform > p means "any p exactly one level underneath h1.hc-reform".

What you want is h1.hc-reform + p. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')).

More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/

Justin Russell
  • 1,009
  • 1
  • 9
  • 15