简体   繁体   English

修饰组件的子元素样式

[英]Styling children of a modified component

My team and I have started implementing something like BEM-ish (we used this article as our starting point). 我和我的团队已开始实施类似BEM-ish的工具(我们以本文为起点)。 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. 例如,假设我有.avatar.avatar--alternate组件/修饰符。 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? 我应该使用什么CSS选择器来设置替代标题的样式,为什么?

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". 我的直觉告诉我B,因为这是设置标题样式的最不具体的方法,并且似乎是最“可扩展的”或“面向未来的”。 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"> ) 另一方面,A非常引人注目,因为我可能也有.avatar-subHeading ,并且在某些情况下,我可能会开始患有类炎(?)(例如, <h1 class="avatar-heading avatar-heading--dark">

Option C: 选项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. 如果.avatar-heading始终是.avatar--dark的子.avatar--dark在DOM树中为.avatar--dark ,请.avatar--dark

Prefer A when you are sure that the component will never be recursively included inside itself. 当您确定该组件永远不会递归地包含在其内部时,请首选A。

Use B otherwise. 否则使用B。


NB: In the BEM methodology, the second div should have both the component class avatar and the modifier class avatar--dark : 注意:在BEM方法中,第二个div应该同时具有组件类avatar和修饰符类avatar--dark

<div class="avatar avatar--dark">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM