【问题标题】:Sass "semantically" nesting tags and classesSass“语义”嵌套标签和类
【发布时间】:2017-10-11 20:24:08
【问题描述】:

我正在尝试在 Sass 中强制执行某种 语义 css 类嵌套。我想强制节的 css 代码只能在节中使用,以确保在语义上应该使用 <section /> 标记。

但是在我的 Sass 文件中使用 & 时遇到了麻烦。考虑以下 html:

<section class="section-home">
  <h1 class="section-home__heading">Section heading</h1>
  <p class="section-home__intro">This is some random text</p>
</section>

我假设我可以在 Sass 中使用以下代码,但不行:

section {
  &.section-home {
    background-color: white;
    &__heading {
      font-size: 5rem;
    }
    &__intro {
      color: grey;
    } 
  }  
}

Sass 将其呈现为以下 CSS:

section.section-home{background-color:#fff}
section.section-home__heading{font-size:5rem}
section.section-home__intro{color:grey}

这不是我期望或需要的,我想要的:

section.section-home{background-color:#fff} 
section.section-home .section-home__heading{font-size:5rem} 
section.section-home .section-home__intro{color:grey}

这是一个错误吗?我在这里做错了吗?

【问题讨论】:

  • 不,这不是错误;这就是你应该预料到的。为什么&amp; 的内部和外部使用会表现不同?
  • 是的,好的。但是如何使用&amp;?这就是使用 BEM 时 Sass 的意义所在,不是吗?
  • 我想要section.section-home{background-color:#fff} section.section-home .section-home__heading{font-size:5rem} section.section-home .section-home__intro{color:grey}。请参阅 html。
  • 您需要添加另一层.section-home,因为您的预期输出中有两次(例如section.section-home .section-home__heading )。
  • 我建议不要使用嵌套,尤其是在使用 BEM 时。主要是因为它使查找课程变得更加困难。如果您将类名分开,那么试图找到类“section-home__heading”是不可能的。您将不得不搜索 __heading 并且如果您的拆分类名称向上,它将出现在多个地方

标签: css html sass


【解决方案1】:

只需将 CSS 更改为:

section {
  &.section-home {
    background-color: white;

    .section-home {
      &__heading {
        font-size: 5rem;
      }
      &__intro {
        color: grey;
      } 
    }  
  }
}

这样 Sass 会将其解释为:

section.section-home

section.section-home .section-home__heading

section.section-home .section-home__intro

【讨论】:

  • 但这不会正确创建section.section-home{background-color:#fff}
  • 已更改,之前无法正确解释 OP 的需求 :)
【解决方案2】:

这会解决你的问题,但是既然已经被html标签限制了,为什么你可以简单地称之为“.home”时称之为“.section-”。

section {
  &.section-home {
    background-color: white;

    .section-home__heading {
      font-size: 5rem;
    }

    .section-home__intro {
      color: grey;
    }
  }
}

【讨论】:

  • 你没有解决问题,你没有理解它。我们的想法是不要在所有子分支中复制section-home 部分。这就是为什么你需要使用&amp;
  • 完全做到了,就像在你的例子中一样;-) 但我不能这样使用&amp;
  • @AndrévanToly 可以,只是不要使用根标签选择器。
  • @dfsq 你是对的 :) 我认为首先不要使用标签选择器。
猜你喜欢
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
相关资源
最近更新 更多