Search code examples
cssbem

How to avoid redundant for something like BEM modifiers


Recently when I started to use my own implementation of methodology based on BEM I stuck on modifiers for nested elements.

I want to change link color to red when product-desc-name has class mark.
The following example presents the problem.

What should I do to keep the final style the same but without duplicating class names?

.product-desc {		
  &-name {
    &.mark {
      /* this section is ugly */
      .product-desc-link {
        color: red;
      }
    }
  }
}
<ul class="product-desc">
  <li class="product-desc-name">
    <a class="product-desc-link">Param1</a>
  </li>
  <li class="product-desc-name mark"> <!--add class .mark-->
    <a class="product-desc-link">Param1</a>
  </li>
</ul>


Solution

  • This is a typical weakness of BEM. I have search for long, but do not seen any good solution for this so I make my own.

    At first I would change the class name. Because UL element should be call 'product-desc-list'. The LI element 'product-desc', as this is in fact exactly a product description for a product.

    The more important is the condition of the product. Therefore the selection of the element should be mentioned first. This allows several blocks to be used for one component.

    The first is the component definition. The next define possible states like selected, in progress etc.

    Here is an example for illustration

    // your product in default definition. 
    .product-desc {		
      &--link {
        text-decoration: underline;
      }
    }
    
    // your product in mark state definition
    .mark {
        .product-description {
            &.--link{
                font-weight: bold;
            }
        }
    }
    <ul class="product-desc-list">
      <li class="product-desc">
        <a class="product-desc--link">Param1</a>
      </li>
      <li class="product-desc mark"> <!--add class .mark-->
        <a class="product-desc--link">Param1</a>
      </li>
    </ul>