ialhamad
ialhamad

Reputation: 48

confusion with Nested Bem classes

I have a header with nested classes. How can I write classes name?

Is the following correct?

<header class="header">
    <nav class="header__navbar"></nav>
    <div class="header__search__btn">
        <a href="#" class="header__search__btn__link"></a>
    </div>
    <div class="header__search__wrapper">
        <form class="header__search__wrapper__form"></form>
    </div>
    <div class="header__logo"></div>
</header>

Upvotes: 0

Views: 228

Answers (1)

Toni Leigh
Toni Leigh

Reputation: 4971

Not really.

You are right that you should separate out your blocks from your elements with a __ but once you've done that you shouldn't then be using __ again in the same class. If you need to use more than one word then use a single hyphen, for example header__affiliate-logos.

Let's look at the example cleaned up a bit:

<header class="header">
    <nav class="header__navbar"></nav>
    <div class="header__search search">
        <form class="search__form"></form>
        <a href="#" class="search__link"></a>
    </div>
    <div class="header__logo"></div>
</header>

What's happened here is that the header block has been reduced somewhat to include classes that only logically belong to the header, whereas the search block has been separated out into it's own BEM module.

The result is that the classes are much more concise and meaningful and you actually have a full re-usable search module that is not tied to the header of the site.

To style the search you'd put your generic search styles into the module, perhaps including the colour of the link or the size of the search input. Then you'd give it header related context in your more specific header__search, perhaps positioning it the correct place as per the designs.

It's generally best to avoid all context if possible in BEM modules, particularly in any general block, so the search block could just be small-form.

Some more resources here:

Smashing Magazine - A New Front End Methodology

CSS Wizardry - MindBEMding

CSS Wizardry - an article with more about context and examples

Note that it isn't technically necessary to include all the search elements within their parent, but it does make more sense to do so.

Upvotes: 2

Related Questions