3

This may seem foolish.. I want to give style to a p tag which is after a certain div(the div is not the parent of the p tag).For example

<div>Hai</div>
<p>Hello</p>
<p>How are you?</p>

Here I want to give style to the p tags. I cant put these p tag in another div.I want to give all the p tags followed by the div same style.And also I cant give the style to p tag universally as it will affect other pages. Can anyone help? Hope I am clear with my question...

  • 1
    http://stackoverflow.com/questions/3660046/css-next-element help you how to handle next element vaia css – Shijin TR May 28 '13 at 12:27
  • It will be easier to say if you can show your entire page code – Sowmya May 28 '13 at 12:28
  • The inherent underlying problem is that your HTML isn't structured correctly. If you correctly grouped content using `
    `, `
    ` and `
    ` tags you wouldn't have the problem you're facing now.
    – Niels Keurentjes May 28 '13 at 12:32
  • @NielsKeurentjes How is using article/section/header instead of div/p going to change anything. You don't know what the div actually contains, it could contain an image gallery or used as a hook for multicolumn content for all you know. If the content is dynamically generated, the tags likely cannot be changed. – cimmanon May 28 '13 at 13:01
  • @cinnamon the grouping of related content by semantics is what allows styling rules to be grouped. If you have to select 'all elements following a certain element' you should've put them in their own container to begin with, since they're obviously considered a group for *some* reason. – Niels Keurentjes May 28 '13 at 13:20

3 Answers3

5

To select only the immediate p sibling:

div + p {
    color: peru;
}

http://jsfiddle.net/yvdN6/

Or to select all succeeding p siblings, use the general sibling combinator

div ~ p {
color: peru;
}

http://jsfiddle.net/yvdN6/7/

Adrift
  • 58,167
  • 12
  • 92
  • 90
5

You have to use the general sibling selector :

div ~ p {
    color: red;
}

See this jsFiddle : http://jsfiddle.net/yvdN6/4/.

You can see the doc :

The elements don’t have to be adjacent siblings, but they have to have the same parent, and the div element has to occur before the p element in the document source.

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
-2
<style type="text/css">
div + p{
Styles here
}
</style>
Abdallah Barghouti
  • 85
  • 1
  • 2
  • 12