CSS Grouping and Nesting Selectors

You can group and nest items to minimise the amount of code you write, which will decrease your style-sheet size and allow pages to load faster. When grouping you separate each selector by a comma.

Grouping

Sponsored Links

Example

In the following example we want all paragraphs and heading tags to be coloured sky blue:

p, h1, h2, h3, h4, h5, h6
{
color:#94C8F2;
}

Example 2 - Id and Class

Here we group an ID and class:

#myDiv, .mySecondDiv
{
width:90%
}

If we give an element the ID myDiv or class mySecondDiv it would have a width of 90%.

!Important

The important keyword will override a previous style.

Example - Important Keyword

h1, h2, h3{

color:#333;

}

When we apply an h1-h3 tag to some text it will have a light black colour. Browsers go down the style sheet and apply each style in order. If a style was given twice, one above and one below, the first one would apply. You can override this by using the important keyword.

h3{
color:blue !important;
}

Nesting

You can nest selectors, for example a <ul> tag has <ul> and also a <li> tag; you can apply style to the <li> by nesting.

Example

ul li

{
padding:10px;
}

This would give all <li> tags in an unordered list a padding of 10px.

Example 2

table tr th
{
background-color:#000;
}

This would style a <th> element with a black background, providing it’s in a <table> tag and then a <tr> tag.

Summary

This tutorial covered how to group CSS selectors and addressed the important keyword, and also showed how to nest selectors.