Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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.

like image 272
Jitendra Vyas Avatar asked Nov 19 '25 09:11

Jitendra Vyas


2 Answers

Go here, and try this code out :)

http://www.w3schools.com/css/tryit.asp?filename=trycss_first-child1

p:first-child
{
    color:blue;
} 
p:first-child + p
{
    color: red;
}
like image 115
Timothy Khouri Avatar answered Nov 22 '25 02:11

Timothy Khouri


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 }
like image 42
Brian Campbell Avatar answered Nov 22 '25 01:11

Brian Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!