What is syntax for selector in CSS for next element?

HtmlCssCss SelectorsSiblings

Html Problem Overview


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.

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

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.

Solution 3 - Html

no > is a child selector.

the one you want is +

so try h1.hc-reform + p

browser support isn't great

Solution 4 - Html

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;
}

Solution 5 - Html

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontony noriegaView Question on Stackoverflow
Solution 1 - HtmlJosh StodolaView Answer on Stackoverflow
Solution 2 - HtmlStephan MullerView Answer on Stackoverflow
Solution 3 - HtmlMoin ZamanView Answer on Stackoverflow
Solution 4 - HtmlRichard JP Le GuenView Answer on Stackoverflow
Solution 5 - HtmlJustin RussellView Answer on Stackoverflow