akai
akai

Reputation: 2052

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.

Upvotes: 1

Views: 66

Answers (3)

Gyanendra Singh
Gyanendra Singh

Reputation: 9

.foo {font-size: 2em;} is correct

Upvotes: 0

Jameson the dog
Jameson the dog

Reputation: 1806

you should use minimum depth where possible, this will render your site faster by minimizing the 'reflow' time and CPU usage

Avoid unnecessary complex CSS selectors - descendant selectors in particular - which require more CPU power to do selector matching.

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

so as to your example - .foo {font-size: 2em;} is preferable.

Upvotes: 1

Chen
Chen

Reputation: 3060

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). If you prefer to use the more explicit approach- the maintenance of the css can become a nightmare.

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.

So try just to use it as the author wish it to be- Cascade.

Upvotes: 1

Related Questions