我在这个元素中使用了 less,目前正在设计一个导航栏并使用 :nth-child
将 li
元素设置为 3 的倍数。我是还尝试管理 active
状态(如下所示 //li active states for nav
comment)。
我正在尝试使任何事件的 li
项都具有 background-color: white
。下面的解决方案添加了:
&:nth-child(3n + 1):hover {
background-color: white;
}
到 每个 事件 :nth-child
声明。当然,有一种方法可以执行类似 &:nth-child(all):hover
之类的操作,或者比我下面的方法更干的操作。看看我的 LESS:
li {
color: white;
padding: 0.9em;
// nav item 1 and multiple
&:nth-child(3n + 1) {
border-top: 2px solid @blue;
&:nth-child(3n + 1):hover {
background-color: @blue;
}
}
// nav item 2 and multiple
&:nth-child(3n + 2) {
border-top: 2px solid @red;
&:nth-child(3n + 2):hover {
background-color: @red;
}
}
// nav item 3 and multiple
&:nth-child(3n + 3) {
border-top: 2px solid @green;
&:nth-child(3n + 3):hover {
background-color: @green;
}
}
}
// li active states for Nav
.active {
background-color: white;
&:nth-child(3n + 1) {
color: @blue;
&:nth-child(3n + 1):hover {
background-color: white;
}
}
&:nth-child(3n + 2) {
color: @red;
&:nth-child(3n + 2):hover {
background-color: white;
}
}
&:nth-child(3n + 3) {
color: @green;
&:nth-child(3n + 3):hover {
background-color: white;
}
}
}
最佳答案
你应该改变这个......
&:nth-child(3n + 1) {
border-top: 2px solid @blue;
&:nth-child(3n + 1):hover {
background-color: @blue;
}
}
...到这个...
&:nth-child(3n + 1) {
border-top: 2px solid @blue;
&:hover {
background-color: @blue;
}
}
你的 LESS 会输出 ...
li:nth-child(3n + 1):nth-child(3n + 1):hover
...但是你想要...
li:nth-child(3n + 1):hover
在你剩下的所有 LESS 中都遵循这个模式。
至于 .active
状态 - li.active
将具有与 li:nth-child(3n + 1)
相同的特异性等等,所以只需在 :nth 选择器之后包含 li.active
。
//编辑 - 最终解决方案
li {
color: white;
padding: 0.9em;
// nav item 1 and multiple
&:nth-child(3n + 1) {
border-top: 2px solid @blue;
&:hover {
background-color: @blue;
}
&.active{
color: @blue;
}
}
// nav item 2 and multiple
&:nth-child(3n + 2) {
border-top: 2px solid @red;
&:hover {
background-color: @red;
}
&.active{
color: @red;
}
}
// nav item 3 and multiple
&:nth-child(3n + 3) {
border-top: 2px solid @green;
&:hover {
background-color: @green;
}
&.active{
color: @green;
}
}
// li active states for Nav
&.active{
background-color: white;
}
}
关于css - 少组织 :nth-child active states,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28862542/