Handling pseudo selectors like :hover in SASS

SASS is an amazing CSS preprocessor that allows you to rapidly code websites using nested rules and variables and a lot more.

However, one thing the basic SASS instructions won’t tell you about is how to handle pseudo selectors when you’re nesting your rules. I’m talking about :hover, :before, :after and :visited states. Do you create a whole new CSS rule for a pseudo selector, or is there a way to nest them?

Well, you’ll be pleased to know that it’s actually quite easy to nest pseudo selectors in SASS – with the help of our friend, the ampersand: &

Ordinarily, your code for a hover effect would look like this:

.box {
    border: 1px solid #000;
    background: #f5f5f5;
}
.box:hover {
    background: #f5f5f5;
}

But with SASS, you simply use the ampersand (&) to reference the parent selector. Like this:

.box {
    border: 1px solid #000;
    background: #f5f5f5;
    &:hover {
        background: #f3f3f3;
    }
}

From there, you can chain and nest other rules. It’s easy. Do you have any other SASS tips that you want to share with the class? Let me know in the comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s