Difference between p.div, div p and div > p

Friday, December 28, 2012 · Posted in ,

Here the div can be interchangeably used for both class and id, but of course you have to use p#div instead of p.div. I am giving the example with <p> element, but it is true for any other element as well.

p.div:

Let's say our html file is like this:


 <head>
  <title>CSS Selector</title>
   <style type="text/css">
    p.para2 { color:green; }
   </style>
 </head>
 
 <body>
   <p>First Paragraph under class1.</p>
   <p class="para2">Second paragraph under class1 with class para2.</p>
 </body>
</html>

The output of this will be like this:

First Paragraph under class1.
Second paragraph under class1 with class para2.

So it only selects those <p> elements with class name "para2"



div p:

HTML File-

<html>
 <head>
  <title>CSS Selector</title>
   <style type="text/css">
    .class1 p { color:green; }
   </style>
 </head>
 
 <body>
  <div class="class1">
   <p>First Paragraph under class1.</p>
   <p>Second paragraph under class1.</p>
  </div>
 </body>
</html>

The output of this will be-

First Paragraph under class1.
Second paragraph under class1.

It selects every <p> element under "class1".


div > p:

HTML file -

<head>
  <title>CSS Selector</title>
   <style type="text/css">
    .class1 > p { color:green; }
   </style>
 </head>
 
 <body>
  <div class="class1">
   <p>First Paragraph under class1.</p>
   <p>Second paragraph under class1 with class para2.</p>
    <div class="class2">
        <p>First paragraph under class2.</p>
        <p>Second paragraph under class2.</p>
    </div>
  </div>
 </body>
</html>

The output of this will be-

First Paragraph under class1. Second paragraph under class1 with class para2.
First paragraph under class2.
Second paragraph under class2.

So div > p selects only the child of that div. Here it selects the child <p> of "class1", but doesn't select the <p> under the nested "class2" as those are not the child of "class1".



WHO OVERRIDES WHOM

Now the question is if you use all of them in the same document and there is conflict which one will be used. Here all of these have same precedence. So, the one defined later will be used as per the rules of css precedence.

So, that's it for now. I will talk more about how precedence is calculated in the next post. Cheers.

Leave a Reply

Powered by Blogger.