组织较少:第 n 个子活动状态

Less organize :nth-child active states

我在这个项目中使用的较少,目前正在设计一个导航栏并使用 :nth-child 以 3 的倍数设置 li 元素的样式。我也在尝试管理 active 状态(如下所示 //li active states for nav 评论)。

我正在尝试让任何活动的 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;
    }
}