Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Sass Snippets: Using the Parent Selector

DZone's Guide to

Sass Snippets: Using the Parent Selector

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

 The Sass syntax has several useful extensions to CSS. One of them is the parent selector shortcut: &. We can use & in our style definition of a selector and Sass will replace it with the parent selector of the rules when the code is converted to CSS. If we use the parent selector (&) in nested rules the complete parent selector is first resolved and then used to replace &.

h1 {
    padding: 20px 0 10px 0;

    // & will be replaced with parent selector h1.
    &.pageHeader {
        color: #f7f7f7;
    }

    // & will be replaced with parent selector h1.
    body.main & {
        color: #ccc;
    }
}

// Parent selector can have a class or id.
a.first {
    text-decoration: none;

    // Parent selector works on pseudo-classes as well.
    &:hover {
        text-decoration: underline;
    }
}

body {
    .article {
        h1 {
            color: #7f7f7f;

            // In nested rules the parent selector is 
            // completely resolved before being used.
            // The complete parent selector here is
            // body .article h1.
            &.blog {
                font-weight: bold;
            }
        }

    }
}

The resulting CSS is in the following sample:

h1 {
  padding: 20px 0 10px 0;
}
h1.pageHeader {
  color: #f7f7f7;
}
body.main h1 {
  color: #ccc;
}

a.first {
  text-decoration: none;
}
a.first:hover {
  text-decoration: underline;
}

body .article h1 {
  color: #7f7f7f;
}
body .article h1.blog {
  font-weight: bold;
}

Written with Sass 3.2.5



Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}