CSS 减:如何写 :hover 和 :focus

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17356049/
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-29 23:20:25  来源:igfitidea点击:

Less: how to write :hover and :focus

cssless

提问by Pelangi

I just started learning Less and would like to have an outcome like this:

我刚开始学习 Less 并希望得到这样的结果:

.navbar .nav > li > a {
   /* some rules */
} 

.navbar .nav > li > a:hover {
   /* some rules */
} 

.navbar .nav > li > a:focus {
   /* some rules */
}

I can't figure out how to write that in Less. I tried

我不知道如何在 Less 中编写它。我试过

.navbar .nav > li > a {
    /* some rules */
    &:hover {

    }
    &:focus {

    }
}

but that doesn't work. Please help. Thank you.

但这不起作用。请帮忙。谢谢你。

回答by ScottS

That is the essentially the correct format for nesting, but it is a little unclear what you are expecting. Perhaps you are expecting duplicationof the /* some rules */into the :hoverand :focus(just based on what you show above for input and output--if that is not a correct understanding of your issue, please clarify). However, that is not how nesting works. Nesting only picks up the selector string to attach the pseudo class to, it does not populate the rules defined outsideof it automatically intoit. You need to be more explicit like one of these options:

这本质上是嵌套的正确格式,但有点不清楚您的期望。也许你期待复制/* some rules */进入:hover:focus(只是根据你上面显示输入和output--什么,如果这是不是你的问题有正确的认识,请说明)。然而,这不是嵌套的工作方式。嵌套只选取选择器字符串来附加伪类,它不会自动将外部定义的规则填充其中。您需要更加明确,例如以下选项之一:

Option 1 (using nesting)

选项 1(使用嵌套)

.navbar .nav > li > a {
    /* some rules */
    &:hover {
      /* some rules */
    }
    &:focus {
      /* some rules */
    }
}

Option 2 (just like CSS)

选项 2(就像 CSS)

.navbar .nav > li > a,
.navbar .nav > li > a:hover,
.navbar .nav > li > a:focus {
    /* some rules */
}

Option 3 (using nesting with a mixin)

选项 3(使用带有 mixin 的嵌套)

.setRules() {
    /* some rules you type once */
}

.navbar .nav > li > a {
    .setRules();
    &:hover {
      .setRules();
    }
    &:focus {
      .setRules();
    }
}