Search code examples
cssbem

How to avoid conflict of same class names in BEM?


I'm working on a website using BEM methodology for maintaining my CSS code. Here is some HTML code:

<div>
    <form class="sc-campaign-form__test-wrapper" id="test-wrapper-1">
        <input type="text" class="sc-campaign-form__test-input" />
        <input type="submit" class="sc-campaign-form__test-submit" />
    </form>
    <form class="sc-campaign-form__test-wrapper" id="test-wrapper-2">
        <input type="text" class="test-wrapper__test-input" />
        <input type="submit" class="test-wrapper__test-submit" />
    </form>
</div>

I think that from BEM point test-wrapper-2 is more right but I'm afraid to make conflict if I bundle everything into one big CSS file because test-wrapper__test-input looks very common. Though I want to have different styling for different test-wrappers. Which way would be more appropriate?


Solution

  • It's a bit hard to guess the right way without seeing the layout. But I'll try.

    1. Try to avoid such entities as wrappers (see https://en.bem.info/methodology/css/#how-do-i-make-an-html-wrapper).
    2. Please give a try to mixes (https://en.bem.info/methodology/css/#mixes)
    3. Don't be afraid to have long classnames, actually it's better than abbreviations like sc. It's much harder to remember what does it mean.

    So a result I'd suggest something like this:

    <div class="campaign-form">
        <form class="form campaign-form__form">
            <input type="text" class="form__input" />
            <input type="submit" class="form__submit" />
        </form>
    </div>
    

    So here you have campaign-form block with abstract universal form block inside mixed with an element form of campaign-form (that's the selector you'd use to provide specific for campaign-form styling).

    If you also need to tune styling of form elements you can add mixes to the elements as well:

    <div class="campaign-form">
        <form class="form campaign-form__form">
            <input type="text" class="form__input campaign-form__input" />
            <input type="submit" class="form__submit campaign-form__submit" />
        </form>
    </div>
    

    As a result all the universal styles will be kept in reusable form + form__input + form__submit and everything specific to campaign-form in it's own elements. So you can easily reuse basic form styling wherever you like.