Computers & ProgrammingCSSWeb Development

CSS Grouping and Nesting Selectors

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 the 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 targeting 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 {

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 {
        This is a <a href="">link</a> within a paragraph element.
        This is a <a href="">link</a> within a span element.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top