Junior
How is isolation achieved when using the BEM methodology?
sobes.tech AI
Answer from AI
Isolation is achieved through unique classes for blocks, elements, and their modifiers.
- Block: Has a unique class name, for example,
button. Styles applied to the block class only affect elements within that block. - Element: Has a class name consisting of the block name, two underscores, and the element name, for example,
button__text. Element styles are tied to a specific block and do not affect elements with the same name in another block. - Modifier: Has a class name consisting of the block or element name, two hyphens (or one underscore, depending on the convention), and the modifier name, for example,
button--disabledorbutton__text_bold. The modifier adds or changes properties of the existing block or element without affecting others.
Example of HTML structure:
<button class="button button--primary">
<span class="button__icon"></span>
<span class="button__text">Click</span>
</button>
<div class="card">
<h2 class="card__title">Title</h2>
<p class="card__text">Card text</p>
</div>
CSS example:
.button {
/* Styles only for the button */
}
.button--primary {
/* Styles for the modifier only for this button */
}
.button__icon {
/* Styles for the icon only inside .button */
}
.button__text {
/* Styles for the text only inside .button */
}
.card {
/* Styles only for the card */
}
.card__title {
/* Styles for the title only inside .card */
}
.card__text {
/* Styles for the text only inside .card */
}
Thanks to this nomenclature and style structure, CSS rules for one block do not conflict with rules for another, even if they contain elements with similar names. This facilitates development, maintenance, and reuse of components.