BEM规范与SASS - 理解上的问题

3

我是一个前端新手,正在尝试理解SASS和BEM的概念。

我非常困难地理解命名约定以及如何与SASS组织它。

我编写了一个产品部分,其中包含三个div(列),它们本身包含子元素。

我不知道如何很好地组织这些名称。例如,img是product__preview的子元素,但我倾向于将类命名为product__img....但这似乎不正确?如果在产品部分中有多个图像,但其中一些必须不同,我们如何处理名称?(product__img似乎太模糊了) 对于特殊情况,我需要添加product__preview__img class吗

你能帮我纠正这个块,以便我正确理解命名吗?

提前感谢您!

 <section class="product">
    <img class="product__cover product__item" src="./images/nintendo/marioodyssey/marioodyssey-1.jpg" alt=""
        srcset="">
    <div class="product__preview product__item">
        <img class="product__img" src="./images/nintendo/marioodyssey/marioodyssey-2.jpg" alt="" srcset="">
        <img class="product__img" src="./images/nintendo/marioodyssey/marioodyssey-3.jpg" alt="" srcset="">
        <img class="product__img" src="./images/nintendo/marioodyssey/marioodyssey-3.jpg" alt="" srcset="">
    </div>

    <div class="product__content product__item">
        <h4 class="product__title">Super Mario Odyssey</h4>
        <p><span> Date: </span> 2017</p>
        <p><span> Story: </span> Super Mario Odyssey[b] is a platform game developed and published by Nintendo for
            the Nintendo Switch on October 27, 2017. An entry in the Super Mario series, it follows Mario and Cappy,
            a sentient hat that allows Mario to control other characters and objects, as they journey across various
            worlds to save Princess Peach from his nemesis Bowser, who plans to forcibly marry her. In contrast to
            the linear gameplay of prior entries, the game returns to the primarily open-ended, 3D platform gameplay
            featured in Super Mario 64 and Super Mario Sunshine.[1] </p>
        <p><span> Review: </span></p>
        <button class="product__btn btn-orange-tiger">Add to cart</button>
        <button class="product__btn btn-orange-tiger">Go to cart</button>
        <button class="product__btn btn-orange-tiger">Keep buying</button>
    </div>
</section>
1个回答

2
您现在的结构非常好和有效。因此,您不需要使用product__preview__img。如果您创建这些类型的选择器,那么您将破坏BEM的目的,因为您将会创建复杂/无组织的代码。如果您觉得名称模糊不清,您可以尝试product__img-preview,因为它仍然与块元素选择器相关联,而不是堆叠的块元素选择器。
另外一个建议是,由于您正在使用BEM并且要充分利用它,请将您的按钮修改器类名称更改为product__btnproduct__btn--orange,因为这将有助于保持您的代码可维护性,因为您在此处同时具有块元素选择器和修改器,即橙色按钮。
.product {
  ...
  &__features {
    ...
  }
  &__btn {
     ...
     &--orange {
       ... 
    }
  }
}

正如您所见,最深层的嵌套级别是块元素的修饰符。


你好,感谢您的反馈!比如说,如果我需要在product__content中添加一个div(其中包含一组特性),那么理想的命名是什么?product__features可以吗?当有“很多”嵌套时,我很难理解命名约定。最终,您应该只使用与该部分最高父级相对应的前缀? - chris
嗨,没问题。product__features 就可以了。就像我说的,你不想创建超过一个块元素的选择器,例如 block__element__element。这违背了命名约定的目的。因此,创建不必要的复杂嵌套选择器会变得混乱和难以维护。你需要坚持使用 一个 块元素选择器。你的 SCSS 代码看起来会像我更新后的原始帖子一样干净整洁。 - Jamie Reardon
谢谢,你的解释清晰简单!如果您不介意,我会再问一个问题。我在这个主题上创建了另一个话题!https://stackoverflow.com/questions/63764373/html-scss-flex-class-directly-in-html-like-bootstrap-or-mixin-in-scss-element - chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接