Should we use CSS child selectors or CSS class based selector?

709 Views Asked by At

Which one is the better way to select the child div in following HTML code in terms of performance and optimizations?

Options 1:

<div class="parent-div">
  <div></div> <!--- child DIV !--->
</div>

// CSS

.parent-div > div {
  // Some CSS for child div
}

'

Options 2: (selecting using a className/id)

<div class="parent-div">
   <div class="child-div"></div>
</div>

// CSS

 .child-div {
    // Some CSS for child div
 }
2

There are 2 best solutions below

2
Peter Van de Laar On

Option 2 is way better for code maintainability.

I recommend reading the BEM naming convention guide.

<div class="block">
   <div class="block__elem"></div>
</div>
0
Akxe On

That depends, if the child is "component" of its own, I would give it a class. but if it is just being a part of some parent component, I would use the .class > element option.

My point of view is based on Angular and its CSS separated on a component level. The benefit of that is, that you will not end up with an overwhelming file.