My team and I have started implementing something like BEM-ish (we used this article as our starting point). What I've read so far seems to make sense. One big problem I'm wrapping my head around is how to style children of modified components.
For example, say I have .avatar
and .avatar--alternate
components/modifiers. Perhaps the background on alternate is black instead of white. What's CSS selectors should I use to style the headings in the alternate and why?
I've laid out the scenarios here:
<div class="avatar">
<h2 class="avatar-heading">Lorem ipsum...</h2>
</div>
<div class="avatar avatar--dark">
<h2 class="avatar-heading">Lorem ipsum...</h2>
</div>
// _typography.scss
h1 {
color: #000;
}
// _avatar.scss
.avatar {
background: #fff;
}
.avatar--dark {
background: #000;
}
.avatar-heading {
color: #222;
}
// option A
.avatar--dark {
.avatar-heading {
color: #fff;
}
}
// option B
.avatar-heading--dark {
color: #fff;
}
// option C?
My gut is telling me B because I this is the least specific way to style the heading and seems to be the most "scalable" or "future-proof". On the other hand, A is pretty compelling because I might potentially have .avatar-subHeading
as well, and maybe some paragraphs in which case I might start suffering from classitis (?) (eg <h1 class="avatar-heading avatar-heading--dark">
)
Option C:
.avatar--dark > .avatar-heading {
color: #fff;
}
All these options are correct.
Prefer C if .avatar-heading
is always a child of .avatar--dark
in the DOM tree.
Prefer A when you are sure that the component will never be recursively included inside itself.
Use B otherwise.
NB: In the BEM methodology, the second div
should have both the component class avatar
and the modifier class avatar--dark
:
<div class="avatar avatar--dark">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.