tags:

views:

63

answers:

3

How to give same style to first 2 paragraphs differently in css.

<html>
<head>
<style type="text/css" media="screen">
p+p {color:red}
</style>
</head>
<body>
  <p>first paragraph</p>
  <p>second paragraph</p>
  <p>third paragraph</p>
  <p>fourth paragraph</p>
 </body>
</html>

I've tried this but it's leaving first paragraph and styling all other.

and this only style first paragraph not others

<html>
<head>
<style type="text/css" media="screen">
p:first-child { color: blue; }
</style>
</head>
<body>
  <p>first paragraph</p>
  <p>second paragraph</p>
  <p>third paragraph</p>
  <p>fourth paragraph</p>
 </body>
</html>

remember I want to give same style on first 2 paragraph.

+3  A: 

Go here, and try this code out :)

http://www.w3schools.com/css/tryit.asp?filename=trycss%5Ffirst-child1

p:first-child
{
    color:blue;
} 
p:first-child + p
{
    color: red;
}
Timothy Khouri
+1 for beating me and the tryit link.
Moshe
no it's not styling first 2 paragraph same
metal-gear-solid
I hope your kidding ... I intentionally made the second one red and the first one blue to show you which of the above CSS selectors was affecting which paragraph tag.Make the second one say "blue" instead of "red".
Timothy Khouri
oh, sorry yes u are right. it's working . thanks. can u tell what is the solution if i want to style like first 3 <p> or first 4 <p>.
metal-gear-solid
@Jitendra - try adding + p to the *p:first-child + p* for each additional p you want to style. (You also need a new set of curly braces and rules.)
Moshe
@Moshe - Thnaks. it's working - p:first-child, p:first-child + p, p:first-child + p + p{color:blue;}
metal-gear-solid
+2  A: 

first of all, ID's need to be unique on a page. You can't use id="hello" twice. You need to use class for that. Try:

<html>
<head>
<style type="text/css" media="screen">
.hello { color: blue; }
</style>
</head>
<body>
  <p class="hello">first paragraph</p>
  <p class="hello">second paragraph</p>
  <p>third paragraph</p>
 </body>
</html>
Moshe
id removed it was added mistakenly
metal-gear-solid
+2  A: 

It depends on what browsers you want to be compatible with. The latest versions of Firefox, Safari, Chrome, and Opera all support the nth-of-type pseudo-element, but IE does not yet (it is a CSS 3 feature, which IE does not support much of). If you can limit yourself to these browsers, the following should work, otherwise, you'll need to use one of the solutions from one of the other answers.

p:nth-of-type(1), p:nth-of-type(2) { color: red }
Brian Campbell
Nice tut, but CSS3 is not widely supported enough. Ah well, +1 anyways for the interesting lesson ni CSS3
Moshe
Yes, I'm aware that CSS3 isn't widely supported enough. I wanted to document this solution for the future, or for people who are targeting only a dingle platform, even though it's impractical for the web as a whole right now.
Brian Campbell