Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What do you think about writing long chains of element specification in CSS?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading