简体   繁体   中英

sass - grouping selectors

I have this sass code:

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-brand {
    &:hover {
    color: #fff;
    }
}

This output:

.navbar-default .navbar-nav > li > a:hover:hover,
.navbar-default .navbar-brand:hover {
  color: #fff;
}

But I want to be:

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-brand,
.navbar-default .navbar-brand:hover {
    color: #fff;
}

How can I use the same property in the parent and the child without repeating the parent with sass?

Try this:

 $white: #fff; .navbar-default { .navbar-brand { color: $white; &:hover { color: $white; } } .navbar-nav > li > a:hover { color: $white; } } 

Unfortunately, it's not really possible to exactly do what you're asking only with the ampersand. The ampersand (&) always gets replaced with the parent selector. In your case, parent selectorS. But what you could do is remove the :hover from the first selector and toss in an @extend . I created a new selector called ".primary-color" which will hold the color.

.primary-color {
  color: white;
}
.navbar-default .navbar-brand {
    @extend .primary-color;
}
.navbar-default .navbar-nav > li > a,
.navbar-default .navbar-brand {
    &:hover {
        @extend .primary-color;
    }
}

This compiles to this CSS:

.primary-color, .navbar-default .navbar-brand, .navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-brand:hover {
  color: white;
}

@extend is a little different than a mixin in how it compiles the CSS. I'm not in love with how it gives you the extra '.primary-color' class that I created, but other than that you sort of get what you want.

Probably a little more complicated of a setup than it needs to be though. I would just add the extra parent selector like you mentioned in your question to get the results your looking for.

This is an article I wrote on the sass ampersand that might be helpful. https://css-tricks.com/the-sass-ampersand/

If you don't mind the redundant :hover:hover you can simplify it to:

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-brand {
    &, &:hover {
        color: #fff;
    }
}

output:

.navbar-default .navbar-nav > li > a:hover, 
.navbar-default .navbar-nav > li > a:hover:hover,
.navbar-default .navbar-brand, 
.navbar-default .navbar-brand:hover {
    color: #fff;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM