Sass:可以在声明“ namespace-blockB”时创建类似“ .namespace-blockA + .namespace-blockB”的选择器吗?

时间:2019-10-01 09:11:45

标签: sass

我们需要声明.Article-UnorderedList之后的.Article-Paragraph的最大边距。 我们可以编写选择器.Article-Paragraph+.Article-UnorderedList,但它不适合下面的代码(在注释中,我写了原因)。

.Article

  &-Paragraph
    font-size: 16px
    line-height: 18px
    // In this line, we don't not know about ".Article-UnorderedList" yet.
    // There could be a lot of unknown at advance selectors like ".Article-UnorderedList" below.
    // So, we can't write "&.+Article-UnorderedList" here.

  // Article-UnorderedList declaration begins here. Now we know about it and also about ".Article-Paragraph"
  // So, this selector MUST know how to shift from ".Article-Paragraph"
  &-UnorderedList

    list-style-type: disc
    list-style-position: outside
    padding-left: 20px

    >li
      line-height: 18px
      &:not(:first-child)
        margin-top: 4px

    // We need to declare the margin from .Article-Paragraph
    // Some way to create .Article-Paragraph+.Article-UnorderedList HERE?

  // Works but lame: we need to exit from &-UnorderedList level and re-declare styles
  // for .Article-Paragraph
  &-Paragraph+.Article-UnorderedList
    margin-top: 16px

1 个答案:

答案 0 :(得分:1)

您可以在父选择器中设置一个全局变量,然后在UnorderedList元素中使用它。

.Article
  &-Paragraph
    $parent: & !global
    font-size: 16px
    line-height: 18px

  &-UnorderedList
    list-style-type: disc
    list-style-position: outside
    padding-left: 20px

    >li
      line-height: 18px
      &:not(:first-child)
        margin-top: 4px

    #{$parent} + &
      margin-top: 16px

您的结果:

.Article-Paragraph {
  font-size: 16px;
  line-height: 18px;
}
.Article-UnorderedList {
  list-style-type: disc;
  list-style-position: outside;
  padding-left: 20px;
}
.Article-UnorderedList > li {
  line-height: 18px;
}
.Article-UnorderedList > li:not(:first-child) {
  margin-top: 4px;
}
.Article-Paragraph + .Article-UnorderedList {
  margin-top: 16px;
}