Coder Perfect

What is the CSS syntax for a selector for the next element?

Problem

If I use the h1 class=”hc-reform”> header tag, title

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

After that, I have a paragraph titled “stuff here” (p>stuff here/p>).

How can I ensure that every p> element that follows the h1.hc-reform uses the following CSS: clear:both;

would that be:

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

That isn’t functioning for some reason.

Asked by tony noriega

Solution #1

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

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

This feature is not available in Internet Explorer 6 or earlier.

Answered by Josh Stodola

Solution #2

The sibling selector can be used as follows:

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

This chooses all of the p elements following. Not just the first one, but all of them.

Answered by Stephan Muller

Solution #3

A child selector is no >.

+ is the one you’re looking for.

as a result, try h1.hc-reform + p

There isn’t a lot of browser support.

Answered by Moin Zaman

Solution #4

A child selector is indicated by the > symbol. If your HTML looks something like this:

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

…then you’ve got yourself a ticket.

If, on the other hand, your HTML looks like this:

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

Then you’ll need the selector next to it:

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

Answered by Richard JP Le Guen

Solution #5

No, not at all. “Any p precisely one level beneath h1.hc-reform” implies “any p exactly one level beneath h1.hc-reform.”

h1.hc-reform + p is what you’re looking for. Of course, this may cause issues in previous versions of Internet Explorer; if you want to make the page compatible with older IEs, you’ll have to either manually add a class to the paragraphs or use JavaScript (for example, in jQuery, you could write $(‘h1.hc-reform’). next(‘p’). addClass(‘first-paragraph’)).

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

Answered by Justin Russell

Post is based on https://stackoverflow.com/questions/3660046/what-is-syntax-for-selector-in-css-for-next-element