CSS Sass 和组合子选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7345763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:33:23  来源:igfitidea点击:

Sass and combined child selector

csscss-selectorssass

提问by frarees

I've just discovered Sass, and I've been so excited about it.

我刚刚发现了 Sass,对此我感到非常兴奋。

In my website I implement a tree-like navigation menu, styled using the child combinator(E > F).

在我的网站中,我实现了一个树状导航菜单,使用子组合器( E > F) 设置样式。

Is there any way to rewritethis code with a simpler (or better) syntax in Sass?

有没有办法在 Sass 中用更简单(或更好)的语法重写这段代码?

#foo > ul > li > ul > li > a {
  color: red;
}

回答by Arnaud Le Blanc

Without the combined child selector you would probably do something similar to this:

如果没有组合子选择器,您可能会做类似的事情:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

如果你想用 重现相同的语法>,你可以这样做:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

这编译为:

foo > bar > baz {
  color: red;
}


Or in sass:

或者在 sass 中:

foo
  > bar
    > baz
      color: red

回答by BoltClock

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

对于您拥有的单一规则,没有任何更短的方法可以做到。子组合器在 CSS 和 Sass/SCSS 中是相同的,没有替代品。

However, if you had multiple rules like this:

但是,如果您有多个这样的规则:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

您可以将它们浓缩为以下之一:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}