简体   繁体   English

直接在父元素(和继承)或子元素上使用CSS样式?

[英]css style on parent (and inheritance) or child elements directly?

Generally speaking, when we have some child elements that should be styled together, should we put that style to the parent and let the inheritance work, or to the children themselves? 一般而言,当我们有一些应该一起设置样式的子元素时,我们应该将该样式放到父级并让继承起作用,还是子元素本身呢? For example, if we have a structure as below: 例如,如果我们具有以下结构:

<div class="foo">
  <p>should be 2em</p>    
  <ul>
    <li>should be 2em</li>
    <li>should be 2em</li>
  </ul>
</div>

then should I make it as this: 那么我应该这样做吗:

.foo {font-size: 2em;}

or something like this?: 或类似的东西?

.foo p, .foo li {font-size: 2em;}

I think this question is very basic, but sorry I couldn't find any good google result. 我认为这个问题是非常基本的,但是对不起,我找不到任何好的google结果。

It is a good question. 这是一个好问题。 I believe you should let the cascading work as it should- this is what css is all about ( cascading style sheets ). 我相信您应该让层叠工作正常进行-这就是CSS的全部意义( 层叠样式表 )。 If you prefer to use the more explicit approach- the maintenance of the css can become a nightmare. 如果您喜欢使用更明确的方法-维护CSS可能会成为噩梦。

If for example I give my parent div a bg-color of yellow, and there are another 100 divs nested inside it, with their classes/ids, we won't want to explicitly give them the background-color: yellow property over and over again. 例如,如果我给我的父div一种黄色的bg颜色,并且在其中嵌套了另外100个div,以及它们的类/ id,我们就不想一遍又一遍地明确为他们提供background-color:yellow属性再次。

So try just to use it as the author wish it to be- Cascade. 因此,请尝试按作者希望的那样使用它-级联。

you should use minimum depth where possible, this will render your site faster by minimizing the 'reflow' time and CPU usage 您应尽可能使用最小深度,这将通过最大程度地减少“重排”时间和CPU使用量来使您的网站更快

Avoid unnecessary complex CSS selectors - descendant selectors in particular - which require more CPU power to do selector matching. 避免使用不必要的复杂CSS选择器-特别是后代选择器-这些选择器需要更多的CPU能力来进行选择器匹配。

src: https://developers.google.com/speed/articles/reflow src: https//developers.google.com/speed/articles/reflow

so as to your example - .foo {font-size: 2em;} is preferable. 因此,以您的示例.foo {font-size: 2em;}

.foo {font-size:2em;}是正确的

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

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