CSS Grouping and Nesting Selectors

Tuesday, March 6, 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.

<style type="text/css">
p a {color:red;}
<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>

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

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