Бэм-методология: с чего всё начиналось и зачем это всё нужно

Алан-э-Дейл       11.03.2024 г.

Выберите и настройте текстовый редактор

Писать HTML-код можно в любом редакторе кода, даже в блокноте. Да, он будет работать, его можно редактировать и улучшать, но работать в блокноте — долго и неэффективно. Сейчас есть огромное количество различных редакторов и IDE, в которых писать код гораздо удобнее.

Для верстальщика устанавливать полноценную и платную IDE не имеет смысла — код, который он пишет, не настолько сложный. Но подобные редакторы кода отличаются от блокнота массой возможностей: есть встроенный проводник, управление форматированием кода, подсветка синтаксиса, плагины, даже работа с Git. Всё это ускоряет и делает более удобной разработку.

Один из самых популярных редакторов у верстальщиков — VS Code. Это бесплатный продукт от Microsoft, который очень часто обновляется, дорабатывается и улучшается. Есть аналоги: Sublime Text 3, Atom, Brackets. Какой из них выбрать — решать вам.

Why BEM over the others?

I’ve tried a lot of different ways of writing CSS over the years. It went something like this…

  • No structure, everything in one file loaded on every page of a site.
  • Separate files to try and keep page specific content together, but still no real structure.
  • Standard OOCSS (Object-Oriented CSS)
  • SMACSS (Scalable and Modular Architecture for CSS)

…and now BEM.

The reason I choose BEM over other methodologies comes down to this: it’s less confusing than the other methods (i.e. SMACSS) but still provides us the good architecture we want (i.e. OOCSS) and with a recognisable terminology.

For me OOCSS isn’t strict enough. It let’s developers go wild with how they name their objects. But I’ve seen that get really messy on larger projects, or projects with more than one developer and because of the lack of strictness in naming conventions developers become confused on what classes are supposed to be doing.

With regards to SMACSS: it’s almost too strict in the sense that I think it’s over structured. When I first started using it I thought this was the solution I had been searching for but all that ended up happening was that I had so many fragmented areas of CSS that I didn’t know where to go first. It was too over whelming.

This might not be the case for some people, but for me these are all instances of the old adage: “don’t make me think”. If I have to think too hard about how something works, or where I need to find the code for something then (in my opinion) that methodology has failed.

BEM succeeds because it provides a good object oriented structure with a familiar terminology and is simple enough to not get in your way.

But like with any tool, it can be misused. In the end it comes down to the overall skill and understanding of the developer.

Simplicity

As I said before, the reason I find BEM a better option is the simplicity.

Even down to the terminology used is simplified compared to other methodologies. For example, depending on who you talk to about structured CSS you may hear the words:

  • objects
  • modules
  • widgets
  • components

…notice the terminology is different but what they refer to are effectively the same thing. No wonder it can become confusing to some people.

BEM is different in that its terminology is based around the environment it works for: HTML and CSS. We all know when working in CSS what a ‘block’ is, it’s the fundamental building block (no pun intended) of how elements on the page are rendered, but that term can also be understood when used like so…

…you know within the context of that sentence the person speaking is referring to a chunk of code, a grouping of code.

The word ‘Block’ is simple but a very focused term, and more importantly it is a very familiar term.

We also know when working in CSS that ultimately we’re targeting ‘elements’. No other word better fits the description, because that is exactly what we’re doing.

And lastly, the word ‘modifier’ again is a simple but fully understood and familiar term used by developers…

But still structured

But with this simplified terminology/structure it gives us all the tools we need to write maintainable and easily understandable code. BEM easily scales with the size of a project.

Миксы

Позволяют:

  • совмещать поведение и стили нескольких сущностей без дублирования кода;

  • одинаково форматировать разные HTML-элементы.

Внешняя геометрия и позиционирование

В CSS по БЭМ стили, отвечающие за внешнюю геометрию и позиционирование, задаются через родительский блок.

Пример

HTML-реализация:

<header class="header">
    <button class="button header__button">...</button>
</header>

CSS-реализация кнопки:

.button {
    font-family: Arial, sans-serif;
    text-align: center;
    border: 1px solid black;    
}
.header__button {
    margin: 30px;               
    position: relative;
}

В данном примере внешняя геометрия и позиционирование блока задана через элемент . Блок не специфицирует никакие отступы и может быть легко переиспользован в любом месте.

HTML-реализация:

<footer class="footer">
    <button class="button">...</button>
</footer>

Стилизация групп блоков

Иногда необходимо применить одинаковое форматирование сразу к нескольким различным HTML-элементам веб-страницы.
Обычно для решения подобных задач применяют групповые селекторы.

Пример

HTML-реализация:

<article class="article">...</article>

<footer class="footer">
    <div class="copyright">...</div>
</footer>

CSS-реализация:

.article, .footer div {
    font-family: Arial, sans-serif;
    font-size: 14px;
    color: #000;
}

В данном примере текст внутри блоков и имеет один и тот же цвет и шрифт.

Несмотря на то, что групповые селекторы позволяют быстро изменить дизайн страницы, такой подход увеличивает связанность кода.

Поэтому в БЭМ для того, чтобы единообра��но отформатировать целый набор HTML-элементов, используют миксы.

Пример

HTML-реализация:

<article class="article text">...</article>

<footer class="footer">
    <div class="copyright text">...</div>
</footer>

CSS-реализация:

.text {
    font-family: Arial, sans-serif;
    font-size: 14px;
    color: #000;
}

Модификатор

Cущность, определяющая внешний вид, состояние или поведение блока либо элемента.

Особенности:

  • Название модификатора характеризует внешний вид («какой размер?», «какая тема?» и т. п. — «размер»: , «тема»: ), состояние («чем отличается от прочих?» — «отключен»: , «фокусированный»: ) и поведение («как ведет себя?», «как взаимодействует с пользователем?» — «направление»: ).
  • Имя модификатора отделяется от имени блока или элемента одним подчеркиванием ().

Типы модификаторов

Булевый

Используют, когда важно только наличие или отсутствие модификатора, а его значение несущественно. Например, «отключен»: 

Считается, что при наличии булевого модификатора у сущности его значение равно .
Структура полного имени модификатора соответствует схеме:
;

.

Пример

<!-- Блок `search-form` имеет булевый модификатор `focused` -->
<form class="search-form search-form_focused">
    <input class="search-form__input">

    <!-- Элемент `button` имеет булевый модификатор `disabled` -->
    <button class="search-form__button search-form__button_disabled">Найти</button>
</form>

Ключ-значение

Используют, когда важно значение модификатора. Например, «меню с темой оформления »:  .
Структура полного имени модификатора соответствует схеме:
;

.. Пример

Пример

<!-- Блок `search-form` имеет модификатор `theme` со значением `islands` -->
<form class="search-form search-form_theme_islands">
    <input class="search-form__input">

    <!-- Элемент `button` имеет модификатор `size` со значением `m` -->
    <button class="search-form__button search-form__button_size_m">Найти</button>
</form>

<!--
    Невозможно одновременно использовать два одинаковых модификатора
    с разными значениями
-->
<form class="search-form
             search-form_theme_islands
             search-form_theme_lite">

    <input class="search-form__input">

    <button class="search-form__button
                   search-form__button_size_s
                   search-form__button_size_m">
        Найти
    </button>
</form>

Принципы работы с модификаторами

Модификатор нельзя использовать самостоятельно

С точки зрения БЭМ-методологии модификатор не может использоваться в отрыве от модифицируемого блока или элемента. Модификатор должен изменять вид, поведение или состояние сущности, а не заменять ее.

Пример

<!-- Верно. Блок `search-form` имеет модификатор `theme` со значением `islands`-->
<form class="search-form search-form_theme_islands">
    <input class="search-form__input">

    <button class="search-form__button">Найти</button>
</form>

<!-- Неверно. Отсутствует модифицируемый класс `search-form` -->
<form class="search-form_theme_islands">
    <input class="search-form__input">

    <button class="search-form__button">Найти</button>
</form>

Nesting considerations

You’ve probably noticed BEM’s idiosyncratic reliance on the absence (or minimal) of CSS nesting. Nesting is a redundant practice here, as OOCSS decouples styling and html markup, and BEM’s naming convention already lexically represent the component’s structure.

Personally, I’m a big fan of the no-nesting paradigm. It’s more modular and helps to keep the stylesheet clean and simple.

One exception where nesting becomes sensible is within ITCSS’s Themes layer.

Say we’re introducing a seasonal Christmas theme. We could wrap the necessary components with .xmas and easily theme it up, for example:

./themes/_xmas.scss.xmas { .header {   background-image: url(‘../images/xmas/bg-jingle-bells.jpg’); } .footer {   background-image: url(‘../images/xmas/bg-north-pole.jpg’); }}

Putting it all together

Let’s try a more complex example. We’ll build a header with a logo, navigation and search box.

Firstly, we’ll use the Atomic Design system to understand how we should construct our components:

Header: organism

  • Branding: molecule
    • Logo: atom
    • Slogan: atom
  • Search: molecule
    • Text field: atom
    • Button: atom
  • Navigation: molecule
    • Navigation item 1: molecule
      • Link: atom
      • Toggle: atom
      • Menu: molecule
    • Navigation item 2: molecule

    • Navigation item 3: molecule

In the navigation molecule, note that navigation items can still be broken down, so it’s still labeled as a molecule.

Secondly, abiding to the ITCSS structure, we know where to allocate styles that influence the header:

  • Settings: variables like colors and font sizes
  • Generic: reset styling, box-sizing
  • Elements: form elements, list styling
  • Objects: text input field, buttons, navigation items
  • Components: cosmetic treatment specifically for branding, search field and header navigation.

Then in html, code the structure and apply the OOCSS and BEM naming convention:

 <header class=”header”> <!-- Branding --> <a class=”branding” href=”/”>   <img alt=”Doge Inc.” class=”branding__logo”>   <p class=”branding__slogan”>Wow! Such brand, many logo</p> </a> <!-- Site search --> <form action=”/” class=”form site-search” name=”form_siteSearch”>   <input class=”input-text input-text-lg site-search__input-text” name=”text_siteSearch” placeholder=”Wow! Many serach!” type=”search”>   <button class=”btn btn-lg btn-primary site-search__btn” type=”button”>Go!</button> </form> <!-- Top navigation --> <nav class=”top-nav”>   <ul>     <li class=”top-nav-item top-nav-item--first”>...</li>     <li class=”top-nav-item”>       <a href=”top-nav-item__link”>About Us</a>       <button class=”top-nav-item__toggle top-nav-item__toggle--collapsed text-hide” type=”button”>Show</button>       <ul class=”dropdown-menu top-nav-menu”>...</ul>     </li>     ...     <li class=”top-nav-item top-nav-item--last”>...</li>   </ul> </nav></header>

 And lastly, apply your styling to the respective partial SCSS files, and there you have it: scalable and maintainable CSS!

Making it work for everyone

No matter what your approach and toolkits, make sure it’s well shared with developers, designers, and stakeholders if they want to be involved.

Start the conversations and brainstorming sessions early, document your approaches and coding style guide, agree on the use of vocabulary and naming conventions (This is the fun part. Don’t like the atomic analogy? How about soldiers > squads > battalion > templates > pages?). And as always, keep CSS sane, lean and simple.

How do you do yours? Feel free to leave your feedback in the comments below!

Unequivocal Placement of Code

File Naming

When a project is:

Long-lived and under constant development.

If the development team:

  • Consists of several people.
  • Grows and changes.

Then being able to navigate the code base quickly is crucial.

Block code is easiest to find when it’s placed in files using the same naming scheme as the one we use for naming our entities:

Expressing Blocks on a File System

There could be a task:

To reuse some blocks from a previous project for a new one.

We want the procedure of block reuse to be as simple as possible—like simply copying the files, or using partial checkout of a repository from a “donor” project. In both cases, it is useful to have all of the files under the same directory:

File Structure of a Block

When working on a project we might need to change a block at some point.

A manager could ask:

  • To change the color of the or
  • To make the react on hover.

A developer could ask their colleague:

To help with Search Form styling for IE.

To understand where the relevant code is located, follow these (or similar) rules:

  • Block code is placed in a separate directory.
    • Directory name matches block name.
    • Implementation is placed under this directory.
  • Elements are placed in subdirectories under the block directory.
    • Directory name matches element name.
    • Implementation is placed under this directory.
  • Modifiers are placed in subdirectories under the block directory.
    • Directory name matches modifier name.
    • Implementation is placed under this directory.
    • File name includes both key and value of the modifier (again, for programmatic access).

Example

File structure of a block:

Maintaining such file structure manually is, quite obviously, inconvenient. So we’ve developed BEM Tools to handle the burden. These tools help with creating the directory structure, placing files, generating placeholder content, etc.

Grouping Blocks in Directories

Big internet portals often need to reuse the same blocks across different websites.

There could be a task:

  • To create the same on all the portals’ websites, or
  • To create a new project using blocks from the existing websites.

Working for a Web design agency often means that one has to use typical solutions for typical Web pages.

A project manager could ask you:

To create an order page with a Web form as on the previous project.

We have to do these tasks while preferably avoiding copying blocks around manually. So it’s nice to have a repository of shared blocks that can be linked to a project. Blocks should then be united under a single directory for that.

Such a directory is usually called .

E.g.

That directory can be linked to another project straight from the version control system, so that we can make changes to shared blocks in a single location.

Starting Your BEM Project

As explained in the official BEM documentation, the easiest way to start you own new BEM project is to use existing GIT repository. Simply use Git clone command:

Next, go to a newly created directory and install all dependencies:

All required dependencies will be installed:

Build the project using ENB:

Run a server mode for development:

As a result, the following message appears:

Now, this means that the server is up and running. You can now check the results on this address:

As you can see, there are a lot of elements already created which are defined inside file which is located here:

You can see and explore the current structure of the file that is generating all that HTML, which you see at your localhost file. We are going to alter this file to get our “Person” BEM project which we explained in a previous chapter. You can remove (or comment) the whole code from file, and replace it with this one:

Now, the following HTML will be generated:

As you can see from the code above, the default BEM coding scheme was used in this scenario since we are just using default settings which BEM provided to us.
There are a lot more commands and options which you can explore and use, such as creating new pages, blocks, or modifying BEM HTML. I will not go too deep into this, and it can all be found in the official BEM documentation.

Организация CSS по BEM (БЭМ — блок, элемент, модификатор)

61667

1472

117

01:37:28

10.05.2017

ВАЖНОЕ УТОЧНЕНИЕ: в видео периодически звучит утверждение, что блок не может быть внутри другого блока. Имеется ввиду, что мы не создаём селекторов вида блокблокэлемент-модификатор

Когда во время вебинара задавали вопросы относительно вложенности блока в блок и т.п., я считал, что спрашивают именно про иерархию в селекторах. Потому что очевидно, что в HTML эта вложенность 100% будет.

Содержание. Подходы к организации CSS-кода. Вложенные селекторы vs БЭМ. Блокэлемент-модификатор. Плюсы и минусы БЭМ. БЭМ и препроцессоры. Ужасы БЭМ на примере лендинга. Выгода БЭМ на примере небольшого сайта.

Ссылка из конца видео: ? Скоро новый поток!

Как писать классы по БЭМ?

БЭМ расшифровывается как «Блок Элемент Модификатор». На самом деле, это целый стэк технологий, из которого мы воспользуемся только соглашением по именованию классов.

Почему БЭМ?

  • БЭМ позволяет создавать абсолютно независимые блоки. Блоки и элементы получают уникальные имена, так что стили для одного элемента ничего не поломают в другом.
  • БЭМ помогает легко придумывать любое количество классов, не повторяющихся между собой.
  • БЭМ помогает писать самодокументирующийся код, в классе любого элемента содержится информация о нём.

Подробнее можно почитать в разделах Быстрый старт и
Часто задаваемые вопросы на сайте bem.info.

Ниже показаны примеры кода.

  1. Простой пример: Блок + Элемент

    Допустим, у вас есть блок с заголовком, текстом и кнопкой внутри, например, это всплывающее окно — попап. Разметка:

    Добавляем класс содержащий назначение элемента: :

    Теперь попробуем добавить классы вложенным элементам:

    Классы удобные, но не уникальные. Если на странице будут ещё элементы с классами и , их стили могут затронуть элементы в попапе. Селектор типа может в будущем создать проблемы со специфичностью. Можно придумать другие классы, но чем больше похожих по смыслу элементов, тем сложнее придумывать новые классы.

    А теперь применим БЭМ-нотацию: каждому элементу внутри блока добавим префикс с классом родителя, например, для заголовка это будет :

    Теперь эти классы легко решают сразу две задачи: во-первых, благодаря уникальным классам стили для них никогда не пересекутся с другими подобными элементами на странице, а во-вторых, по таким классам сразу видно, что это элементы блока .

  2. Пример посложнее: Блок + Элемент + Модификатор

    Для примера возьмём сервисное сообщение на сайте. Обычно такие сообщения бывают разных видов, например, сообщение об успешном завершении действия или об ошибке.

    Логично использовать одну и ту же разметку, но с разными цветовыми темами. Именно здесь очень пригодятся модификаторы.

    Обоим элементам можно добавить одинаковые стили используя общий класс и так же легко можно добавить отдельные стили для каждого из них, используя уникальный класс с модификатором:

    Оба сообщения будут иметь рамку толщиной один пиксель, но для сообщения об успешной операции она будет зелёной, а для сообщения об ошибке — красной.

  3. Ещё сложнее: что делать, если хочется сделать элемент элемента?

    Например, на странице есть блок новостей:

    Заголовок блока логично получает класс , список — , а отдельная новость — :

    Тут никаких проблем возникнуть не должно. Теперь добавим разметку отдельной новости:

    Нам нужно добавить класс заголовку новости. Первым делом приходит в голову , но такой класс уже занят. Предположим, что второй элемент будет не , а , тогда в CSS получается такое:

    Без дополнительных комментариев будет совершенно невозможно понять какой из них является заголовком всего блока, а какой — отдельной новости. Не пойдёт.

    Следующий вариант — , но в БЭМ нельзя создавать элемент элемента, и это понятно, потому что получается каша. Ещё вариант: — тоже не годится, потому что может быть неочевидным как соотносится с . Как же быть?

    Решение простое: на уровне элемента можно объявить новый блок (например, ), и строить вложенные классы уже от него. Да, это не самостоятельный переиспользуемый блок, здесь объявление блока нужно только для того, чтобы разгрузить селекторы. Что получается:

    Проблема решена: нам больше не нужно использовать монструозные классы, при этом класс точно описывает элемент, и в CSS будет сразу понятно какой класс за что отвечает:

    Простой и удобный выход из неудобной ситуации.

Больше примеров разметки можно увидеть здесь.

Ещё одно хорошее руководство по использованию БЭМ есть здесь.

Block Element Modifier

BEM encourages developers to divide layouts into blocks and nested elements. Variations from the average appearance of a block or element should also be identified and applied using modifiers.

CSS declarations are applied using a single class name of format block-name for blocks and block-name__element-name for elements, with two underscores in between. Modifier names are appended to classes, prefixed with an underscore or two hyphens for better clarity, for example block-name__element-name_modifer-name or block-name__element-name—modifer-name. An object is a block if it can exist without ancestors, otherwise it’s an element. 

Blocks can have nested blocks and elements, but elements cannot. Modifiers must be used alongside block and element classes, not instead of them.

BEM can be applied to a list, where list-block—inline and list-block__item—active display lists horizontally and highlight items respectively:

BEM is a highly effective naming convention that creates predictably behaving CSS that is easy to manage, maintain and scale. BEM does have downsides, however, including the difficulty in inventing class names for deeply nested objects, the ridiculously long class names and bloated HTML that may sometimes result, and also the lack of consistency that is caused by the inability to share CSS between objects.

Селекторы

В БЭМ не используют селекторы тегов и идентификаторов. Стили блоков и элементов описываются через селекторы классов.

Селекторы классов

Позволяют указать конкретный HTML-элемент страницы, независимо от тега. Обращение к селектору класса происходит через атрибут , который должен иметь каждый HTML-элемент.

Значением атрибута может быть разделенный пробелами список слов. Это позволяет использовать разные БЭМ-сущности на одном DOM-узле.

Пример

HTML-реализация:

<header class="header">
    
    <button class="header__button button button_theme_islands">...</button>
</header>

Совмещение тега и класса в селекторе

Методология БЭМ не рекомендует совмещать теги и классы в селекторе. Объединение тега и класса (например, ) повышает специфичность CSS-правил, что усложняет задачу их переопределения. Это приводит к войнам значимости, при которых таблицы стилей загружаются излишне сложными селекторами.

Пример

HTML-реализация:

<button class="button">...</button>

CSS-правила заданы в селекторе .

Допустим, блоку добавили модификатор со значением :

<button class="button button_active">...</button>

Селектор не переопределит свойства блока, записанные как , так как специфичность выше чем у . Для успешного переопределения селектор модификатора блока также должен быть скомбинирован с тегом .

В результате развития проекта могут, например, появиться блоки с селекторами , и . В таком случае все модификаторы блока и вложенные в него элементы потребуют четыре разные декларации для каждого случая.

Нужно стараться использовать простые селекторы классов:

.button {}
.button_active {}

Вложенные селекторы

Методология БЭМ допускает использование вложенных селекторов, но рекомендует свести их применение к минимуму. Вложенные селекторы увеличивают связность кода и делают его повторное использование невозможным.

При использовании вложенных селекторов важно соблюдать принцип инкапсуляции: правила одного блока не должны влиять на внутренний мир другого блока. Элементы — это внутренняя реализация блока

Таким образом, блок влияет только на свои элементы и не может воздействовать на элементы другого блока.

Вложенность уместна, если необходимо изменить стили элементов в зависимости от модификатора (например, состояния блока или заданной темы):

Пример

CSS-реализация:

.button_hovered .button__text
{
    text-decoration: underline;
}

.button_theme_islands .button__text
{
    line-height: 1.5;
}

Комбинированные селекторы

Методология БЭМ не рекомендует использовать комбинированные селекторы. Комбинированные селекторы (например, ) имеют более высокую специфичность, чем одиночные селекторы, что усложняет задачу их переопределения.

Пример

HTML-реализация:

<button class="button button_theme_islands">...</button>

CSS-правила заданы в селекторе .

Допустим, блоку добавили модификатор с значением :

<button class="button button_theme_islands button_active">...</button>

Селектор не переопределит свойства блока, записанные как , так как специфичность выше, чем у . Для успешного переопределения селектор модификатора блока также должен быть скомбинирован с селектором и объявлен ниже , так как специфичность обоих селекторов одинакова:

CSS-реализация:

.button.button_theme_islands {}
.button.button_active {}

Нужно стараться использовать простые селекторы классов:

.button_theme_islands {}
.button_active {}

Именование

Имя селектора должно полно и точно описывать представляемую им БЭМ-сущность.

В качестве примера рассмотрим следующие четыре строки CSS-кода:

.button {}
.button__icon {}
.button__text {}
.button_theme_islands {}

С определенной долей вероятности можно предположить, что мы имеем дело с одним блоком и его HTML-реализация выглядит следующим образом:

<button class="button button_theme_islands">
    <span class="button__icon"></span>

    <span class="button__text">...</span>
</button>

Сложнее сделать подобное предположение с такой группой селекторов:

.button {}
.icon {}
.text {}
.theme_islands {}

Имена , , не так информативны.

Общие правила именования блоков, элементов и модификаторов позволяют:

  • сделать имена CSS-селекторов максимально информативными и понятными;

  • решить проблему коллизии имен;

  • независимо описывать стили блоков и их опциональных элементов.

Пример

HTML-реализация:

<div class="logo logo_theme_islands">
    <img src="URL" alt="logo" class="logo__img">
</div>


<div class="user user_theme_islands">
    <img src="URL" alt="user-logo" class="user__img">
    ...
</div>

Именование CSS-классов:

.logo {}                  

.logo__img {}             

.logo_theme_islands {}    

.user {}                  

.user__img {}             

.user_theme_islands {}    

Block

A block is a component. It’s a little abstract, so let’s use examples instead.

Let’s say you’re building a contact form. In this case, the form can be a block. In BEM, blocks are written as class names, like this:

The reason BEM uses a class instead of the element is because classes allow for infinite reusability, even if the fundamental element should change in style.

Buttons are good examples of blocks that can contain different possible styles. If you set the background color of a element to be red, all are forced to inherit the red background. Following which, you have to fix your code by overwriting your elements (and probably end up with broken limbs in the process ).

If styled a button with a class instead, you can choose whether to use the class on any elements. Then, if you need a different background color, all you do is to change to a new class, say , and you’re good to go!

This brings us to the next part of BEM — modifiers.

Intersection of Particles

In past BEM projects I’ve felt uneasy about the parent/child component relationship. There are sometimes points where I feel a parent/child relationship of two components is preferred, but that’s not what BEM is good for.

When I do create a parent/child relationship, often one component’s styles will need to be higher in the cascade than the other, which means more code documentation to make sure that that ‘gotcha’ is understood, and it introduces a little fragility.

This architecture handles that issue very well.

Let’s take a look at a ‘teaser list’, it contains a title for the listing and then a list of ‘teaser’ components.

In this example the wrapper of the ‘teaser’ component has two jobs:

  • define how the ‘teaser’ is laid out in the ‘teaser list’ component
  • define any backgrounds, borders, padding, or other interior effects that the teaser has

With the naming convention we’ve gone with, that wrapper has two classes that cover each function:

  • makes sure the component is flowing correctly inside of its parent
  • class is responsible for the aesthetic and how the wrapper affects the contents

Using two classes will make sure the styles needed for the teaser’s layout in its parent won’t affect teasers that are in different contexts. The single letter prefix makes it even easier to to tell which class comes from the parent, and which defines the child component.

The partials are loaded in ‘particle size’, smallest to largest. I know if there’s any overlap in the styles for those two classes, the parent component’s class will win. No cascade guesswork, and no fragility introduced by the parent/child relationship.

As I mentioned before, I tried to make sure that parent components were always a larger ‘particle size’ than their children. There are a few instances where organisms were parents to other organisms, and, looking back, I wish I’d separated those organisms by adding a new particle size to the mix. Pattern Lab would have allowed me to add onto to it’s naming conventions, or even completely replace them.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.