首页 > 解决方案 > 引用 SCSS 中元素的父级

问题描述

我想要这段代码:

ul li {
    ...

    &:first-child a {
        ...
    }

    &:last-child a {
        ...
    }

    &.active a {
        ...
    }

    a {
        ...
    }
}

变成这样:

ul li {
    ...
   
    a {
        ...

        &:first-child a ...
    }
}

有没有办法引用父母(&应该是ul li)?也许甚至是一个mixin来解决它?

标签: sass

解决方案


像这样使用。对类做任何你想做的事情,link 如果你想在锚下锚定它是 html 验证错误。你必须避免这种情况。

ul {
  li {
    &.link {
      &:first-child {
        a {
          color: red;
        }
      }
      &:last-child {
        a {
          color: red;
        }
      }
    }
  }
}

输出

ul li.link:first-child a {
  color: red;
}
ul li.link:last-child a {
  color: red;
}

推荐阅读