两个 Sass `@extend` 的冲突

Two Sass `@extend`s Conflict

我将这些行作为导航的一部分 sass,在此处进行了简化:

// These lines (66-72) should generate what I want.

.top-nav .nav {
  & > ul {
    a {
      @extend %section-button;
    }
  }
}

// These lines (76-82) prevent the previous code from generating what I want. 
// Delete it to see things work.

.nav {
  & > ul {
    a {
      @extend %section-button;
    }
  }
}

删除第 76-82 行后,第 66-72 行会生成 .top-nav .nav > ul a:hover,将深灰色应用于悬停时的文本。但是,当允许保留第 76-82 行时,不会生成 .top-nav .nav > ul a:hover 选择器。这是为什么?

更改选择器块的顺序没有帮助。

我需要两个块,因为在 .nav 选择器块中我覆盖了 %section-button 中的内容,而我不想在 .top-nav .nav.

中覆盖这些内容

Here's the code in a pen, simplified as much as possible while still demonstrating the problem.

完整代码:

HTML:

<div class="top-nav">
  <nav id="nav" class="nav">
    <ul>
      <li class="page-link"> <a href="/live">Live</a></li>
    </ul>
  </nav>
</div>

SCSS:

// Colors
$grey-color-dark:  #3f3f3d;
$grey-color-light: lighten($grey-color-dark, 65%);
$blue: #23527c;
$green: #2d5a3a;

// Section Colors

%section-background-color {
  background: $grey-color-dark;
}

%section-text-color {
  color: $grey-color-dark;
}

// Buttons

%button {
  cursor:pointer;
  padding:0 1rem;
  line-height: 2rem;
  height: 2rem;
  display:inline-block;
}

%section-button {
  @extend %button;
  @extend %section-background-color;
  color:$grey-color-light;

  &:hover, &:focus {
    background: $grey-color-light;
    @extend %section-text-color;
  }
}

// navigation

// These lines (66-72) should generate what I want.

.top-nav .nav {
  & > ul {
    a {
      @extend %section-button;
    }
  }
}

// These lines (76-82) prevent the previous code from generating what I want. Delete it to see things work.

.nav {
  & > ul {
    a {
      @extend %section-button;
    }
  }
}

当你想使用 mixin 时,你正在使用 @extends@extends 旨在创建一组 classes(并且它将编译成一个实例),因此在 .top-nav .nav.nav 上调用它会创建一个 CSS 组合 classes 并导致其他笨拙。而使用 mixin 将在 navtop-nav.

中定义 section-button 的两个不同实例

如果您将 %section-button 更改为 @mixin section-button 并且 @extend %section-button 调用 @include section-button,一切都应该有效。

如果您打算使用占位符,则需要创建多个占位符。但我认为这种做法违背了使用占位符的意义。或者,如果您不担心重复代码,您可以使用嵌套的 :hover, &:focus 伪选择器在 .top-nav class 中定义您想要的 CSS,然后定义您想要的任何颜色。