首页 > 解决方案 > HTML BEM 命名约定

问题描述

我正在学习 HTML BEM (CSS) 架构,即使在观看了一些 youtube 视频后也不太了解。你们中的任何人都可以查看我的代码以查看我的类命名是否正确吗?

<div class="chat-offer">

  <div class="img chat-offer__img">
    <picture class="chat-box-b default-box-b">
      <img src="${properties.chatMobileImageBoxA}" alt="${properties.chatBackgroundImageAltText}"              class="offers-img-responsive">
    </picture>
    <picture class="chat-logout default-logout">
      <source media="(min-width: 320px) and (max-width: 767px)"               srcset="${properties.chatMobileImageBoxA}">
      <source media="(min-width: 768px) and (max-width: 1023px)" srcset="${properties.chatMobileImageBoxA}">
      <img src="${properties.chatDesktopImageBoxA}" alt="${properties.chatBackgroundImageAltText}" class="offers-img-responsive">
    </picture>
  </div>

  <div class="chat-offer__txt">
    <h1 class="chat-offer__txt--heading">${properties.offerTitle}</h1>
    <p class="chat-offer__txt--subheading">${properties.offerSubTitle}</p>
    <div class="chat-offer__btn">
      <a href="${chatOfferModel.loginCTALink}" target="${chatOfferModel.loginNewWindow}" class="chat-offer--cta">${properties.loginCTAText}</a>
    </div>
  </div>

</div>

标签: htmlcssbem

解决方案


命名看起来大部分是正确的。我会提出以下建议:

  1. 我会chat-offer__txt改为chat-offer__txt-wrapper. 您将其附加到的元素与您添加该规则的修改版本的两个元素(h1 和 p)实际上没有任何共同之处。
  2. 就个人而言,每当我在元素上看到修饰符类时,我也希望在同一元素上看到未修改的(元素或块)类。未修改的类设置了修饰符覆盖的默认值。举个h1.chat-offer__txt.chat-offer__txt--heading例子。
  3. img例如,您在 BEM 中混入了很多不相关的“通用”类chat-box-bdefault-box-b这使得推理样式以及所有这些规则如何交互变得更加困难。如果您使用的是 SASS,则可能值得设置 mixin 以包含可跨多个组件重用的样式,这将使您的 BEM 更简单、更易于推理。

推荐阅读