Wednesday, September 28, 2011

14 - Grouping and Nesting in CSS


Grouping is very good approach to define more than one style Tags or Selectors if they have common elements and values. This also help us to minimize our code. For example.


Here I have three selectors which has same elements and values.

h2{         
   color: red;
   Font-size:24px
}
p{            
   color: red;
   Font-size:24px
}
#myStyle{           
   color: red;
   Font-size:24px
}

By Grouping I can define all these Tags or selectors in single line separated by commas.

h2, p, #myStyle{              
color: red; Font-size:24px
}


Nesting is another very useful approach to access child tags and styling them. For Example In  below example I have two DIV’s with a class applied on it called “leftContent” and “rightContent” respectively. In both DIV’s we have a heading tag and a paragraph tag.



<div class="leftContent">
    <h1> This is my Left Content</h1>
    <p>Hii Friends, Welcome to this Fast Food Corner. 
       We have vast and delicious varieties of Fast Food.
    </P>
</div>

<div class="RightContent">
    <h1> This is my RightContent</h1>

    <p>Hii Friends, Welcome to this Electronics Corner. 
       We have latest and vast varieties of Electronics.
    </P>

</div>


Now suppose I have to Style heading and paragraph of each DIV differently, like I love to have heading of DIV containing class “leftContent” in Blue color and paragraph in red and heading and paragraph of DIV containing class “RigthContent” in Red color and paragraph in Blue.


Than our approach of styling these h1 and p tags will be like this:

div.leftContent h1{
                color:blue
}
div.leftContent p{
                color:red
}

Here browser look h1 and p tags in those div's only which have content “leftContent” class. 

div.RightContent  h1{
                color:red
}
div.RightContent  p{
                color:blue
}

Here browser look h1 and p tags in those div's only which have content “leftContent” class.

Output in Browser:

 
powered by multimediagyan ©

No comments:

Post a Comment