-1

In my CSS code I've always used long chains of text to specify the element:

ol > li > ul > li > button:last-child {color: hsl(0, 0%, 30%);}

I've also heard that using mostly classes is a common practice. In my opinion these long chains of text aren't the best way to do this so I'm asking how most of you write code in situations like that.

  • 1
    For better understanding I think you need to read this: https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left/5813672#5813672 and this: https://css-tricks.com/specifics-on-css-specificity/ – Saddam Habibie Dec 24 '21 at 15:06

1 Answers1

0

There is nothing wrong in writing:

ol > li > ul > li > button:last-child {color: hsl(0, 0%, 30%);}

But, the thing is you should not make your CSS file, without any reason - Lengthy. That is NOT a good practise.

Also, > operator (child-selector) should be used only, when there is extreme urgency. In your scenario, the following code would have also worked:

ol ul li button:last-child{...}

There are more than 50 selectors in CSS, and there are 100s of elements in dom. Is it necessary to go through everyone of them? Is it right - YES, was it necessary? - NO!

You could have also written your code as:

html body ol > li > ul > li > button:nth-last-of-type(1) {...}

But, you didn't write why? Then, that is also correct!

The thing is even in SASS (CSS Pre-processor), it is recommended, that you should avoid, more than 2-levels of predecessor! It would be right even if you go to extra lengths, but just make an extra class (where you want to make changes) ... don't just keep on adding selector after selector, if it is NOT required! Just make your code smaller -- so that, even after code-minification your file is having minimum lenghth, NOT unnecessary big.

Deadpool
  • 7,811
  • 9
  • 44
  • 88