【问题标题】:How to retain advanced SASS nesting option when using correct BEM methodology使用正确的 BEM 方法时如何保留高级 SASS 嵌套选项
【发布时间】:2022-06-28 17:41:59
【问题描述】:

这已经讨论过很多次了,但我还没有看到一个正确的答案。我想在我的代码中使用 BEM 方法,但我想保留高级 SASS 嵌套选项以提高代码可读性。

这是我的代码示例:

<div class="education">
    <h3 class="education__heading">Heading</h3>
    <div class="education__items">
        <div class="education__item">
            <h4 class="education__faculty">Lorem ipsum</h4>
            <span class="education__subject">Dolor sit amet</div>
        </div>
    </div>
</div>

这应该是具有 3 层嵌套的正确 BEM 模型。这个模型的 SASS 代码如下所示:

.education {

    &__heading {

    }

    &__items {

    }

    &__item {

    }

    &__faculty {

    }

    &__subject {
        
    }
}

据我所知,这是正确的方法,但我错过了在我的 SASS 代码中嵌套类的选项(参见下面的简化示例,没有 BEM 类名):

.education {

    .heading {

    }

    .items {

        .item {

            .faculty {

            }

            .subject {

            }
        }
    }
}

这个结构基本上复制了HTML结构,我相信它很容易维护和阅读。 在使用正确的 BEM 方法时,是否可以在 SASS 中保留多级嵌套?

【问题讨论】:

  • 您确定要为您的选择器提供如此多的特异性吗?它将编译为:.education .items . item .faculty {}...如果这确实是您想要的,只需在您的父选择器级别创建一个变量,并使用它而不是与符号&amp;
  • @AmauryHanser 这是一个很好的观点,谢谢。虽然这个简化的例子并不是最好的例子,但我同意在大多数情况下,超过 3 个级别的特异性是多余的。

标签: sass nested bem


【解决方案1】:

我知道的唯一解决方案是三个技巧:

  1. 使用@at-root 规则,无论嵌套多深,它都会将声明移到顶部
  2. 将块选择器保存在一个变量中,使用&amp;作为赋值的值
  3. 使用#{} 在选择器中插入变量

在你的情况下,它看起来像这样:

.education {
    // Save `.education` in the $block variable
    $block: &;

    @at-root #{$block}__heading {
        /* Heading styles */
    }

    @at-root #{$block}__items {
        /* Items styles */

        @at-root #{$block}__item {
            /* Item styles */

            @at-root #{$block}__faculty {
                /* Faculty styles */
            }

            @at-root #{$block}__subject {
                /* Subject styles */
            }
        }
    }
}

并将编译为:

.education__heading {
  /* Heading styles */
}
.education__items {
  /* Items styles */
}
.education__item {
  /* Item styles */
}
.education__faculty {
  /* Faculty styles */
}
.education__subject {
  /* Subject styles */
}

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2021-01-05
    • 2022-01-16
    • 1970-01-01
    • 2017-11-11
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多