Slide 5.19: CSS border (cont.)
Slide 5.21: CSS pseudo-class
Home

CSS Grouping and Nesting Selectors


Grouping Selector
In style sheets there are often elements with the same style. To minimize the code, you can group selectors. Separate each selector with a comma. The following two examples are the same with or without grouping the selectors:

 h1 {  color:green;  }
 h2 {  color:green;  }
 p  {  color:green;  }
 h1, h2, p {
   color:green;
 }



Nesting Selector
It is possible to apply a style for a selector within a selector. In the example on the right, one style is specified for all p elements, and a separate style is specified for p elements nested within the "marked" class:
 <html>
   <head>
     <style type="text/css">
       p {
         color:blue;
         text-align:center;
       }
       .marked {
         background-color:blue;
       }
       .marked p {
         color:white;
       }
     </style>
   </head>

   <body bgcolor="#EDF3FE">

     <p>This is a blue, center-aligned
       paragraph.
     </p>

     <div class="marked">
       <p>This p element should not be blue.</p>
     </div>

     <p>p elements inside a "marked" classed
       element keeps the alignment style, but
       has a different text color.
     </p>

   </body>
 </html>


Demonstration
The following demonstration shows how the script of HTML and CSS is displayed on the Web: