Tuesday, April 13

CSS specificity - What if "id" and "class" with same name applied to a div element??

A CSS quick question. If you have a id and a class with same name applied to a division tag, then what rule will be applied.
Now a common and most logical answer would be whichever rule is defined later in the stylesheet, will be applied to the division tag. Sounds good, but this is not the correct answer or explanation. In such situation, CSS specificity is what comes into the picture.

The correct answer is the CSS rule defined by id is more specific and gets applied to the html document.
Let us demonstrate through an example.

Case 1: CSS class defined first and then id defined later.
<html>
<head>
<title>CSS specificity</title>
</head>
<style type="text/css">
          .simple p{
               font-size:20px;
              color:red;
          }
         #simple p{
              font-size:20px;
              color:blue;
         }

</style>
<body>

<div class="simple" id="simple">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</body>
</html>

 Output : The browser assigns the paragraph a color blue.

Case 2: id defined first and then class.

<html>
<head>
<title>CSS specificity</title>
</head>
        <style type="text/css">
               #simple p{
                   font-size:20px;
                   color:blue;
               }
              .simple p{
                   font-size:20px;
                   color:red;
              }
</style>
<body>
<div class="simple" id="simple">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</body>
</html>

Output : The paragraph is still in blue.

Conclusion : id's are more specific than class.