HTML5 Zone is brought to you in partnership with:

Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 167 posts at DZone. You can read more from them at their website. View Full User Profile

Sass Snippets: Using the Parent Selector

02.19.2013
| 1901 views |
  • submit to reddit

 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



Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)