Did you find this useful?
Socialize it today.


CSS Grouping and Nesting Selectors

Tuesday, March 06, 2012

tags CSS

As you develop your CSS structure, you may realize that in many cases, you need to apply the same styles to different elements in your HTML pages. Also, it is fairly common that you will need to apply unique styles to specific elements. In some cases, these elements may be elements that are within parent elements you are trying to target. This is where you can leverage the ability to combine and/or nest selectors.

Combining Selectors

This example shows how you can group all the heading elements and apply the same property and values. Each selector is separated by a comma. In the case of the font-family property, you will notice three values. If the user's browser does not support the first value, it will try to apply the second. If the second is not supported, it will continue through the list of values specified.



h1, h2, h3, h4, h5, h6
{
color: #blue;
font-family: Arial, Verdana, sans-serif;
}


Nesting Selectors

It is possible to apply a style for a selector within a selector. For example, say you wanted to style only the hyperlinks within paragraph elements, you can do so by targetting those specific selectors. In the example below, we are applying a style to hyperlinks within a paragraph parent element. In your HTML file, when you add hyperlinks within a paragraph element, those hyperlinks will be styled.



p a {color:red;}


In your HTML file, create a paragraph element, then add your hyperlinks. Only those hyperlinks will have this style applied. Notice that the hyperlink outside of the paragraph element will not be styled.  Copy and paste the following code into our HTML Editor so that you can try it yourself.



<html>
<head>
<style type="text/css">
p a {color:red;}
</style>
</head>
<body>
<p>This is a <a href="http://www.itgeared.com">link</a> within a paragraph element.</p>
<span>This is a <a href="http://www.itgeared.com">link</a> within a span element.</span>
</body>
</html>

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Editor CSS: The Missing Manual HTML CSS: The Complete Reference