1

Consider the following HTML snippet

<div class="my-cool-section">
  <div>
    <div>
      <ul>
        <li>List</li>
        <li>Of some</li>
        <li>Stuffs</li>
      </ul>
    </div>
  </div>
</div>

Is it a bad CSS if I define the style for the li items like this?

 .my-cool-section ul li {
     //Styles for the items
 }

According to my code reviewer the BEST solution is to attach a class directly to the ul IF NOT li. The super ideal case would be to attach a class with the li itself.

<li class="my-cool-list-item">Stuffs</li>

Like that. So is this true? If yes is it related to performance etc? Also please consider that this code would be part of a bigger compiled CSS file containing thousands of lines of code. Thanks.

Souvik Ghosh
  • 731
  • 8
  • 22
  • 2
    This is perfectly normal. Attaching the same class to many child elements is wasteful and that's the entire point of child/descendant selectors in CSS. – Mitya Apr 10 '18 at 08:54
  • 1
    Nothing wrong with it. If you want to have a more "modular" way of using CSS you may want to take a look at the BEM methodology. – Cata John Apr 10 '18 at 08:59
  • Yes, even I thought so. But the logic from my code reviewer is the browser starts parsing from the deepest node matched. So if it encounters `li` then it would search for every possible parent/child css declaration for all `li`s which would be slow in terms of parsing compared to the case where if it would have a class assigned to it, it could have directly applied those styles. – Souvik Ghosh Apr 10 '18 at 09:00
  • I see what you mean. But sometimes I style some tags depending on body class. Like links or anything else. And i have no performance issue. But in your case I think that the best way is to add a class to the ul and style li according to it. Because maybe one day, you will have to add another ul in the parent div but with other li styles. – Alexis Vandepitte Apr 10 '18 at 09:06

1 Answers1

0

Performance wise it is better to add class in ul and best to add class in all li . But you may not be writing this piece of code to be used millions of time per day, so you can just ignore the optimization and continue with whatever you have already wrote.

If we talk about code maintenance wise, adding class in each li would be an overkill but you can add class in ul which is not a tough task to do.

To learn more about the performance based on CSS selectors read more here: Is CSS faster when you are specific?

Note: CSS Ninjas can update this answer if my answer is misleading in some way.

codemirror
  • 3,164
  • 29
  • 42