CutCodeDown

Web Development => HTML / CSS => Topic started by: Gary-SC on 18 Nov 2019, 02:57:46 am

Title: CSS selector order: what is the best practice?
Post by: Gary-SC on 18 Nov 2019, 02:57:46 am
I have been wondering about this article which I came across a while ago:

https://meiert.com/en/blog/how-to-order-css-selectors/

What is the best practice for ordering CSS selectors? What do you suggest?  In general, I've been following this article's advice; going from global to more specifics.
Title: Re: CSS selector order: what is the best practice?
Post by: Jason Knight on 18 Nov 2019, 05:12:54 am
In terms of the various stages of CSS being applied, the difference is so negligible as to be unmeasurable unless you do something stupid like make a 2 megabyte HTML file with hundreds of thousands of tags.

Hence I place them in the "most useful order" for me. The order I find most useful?

webfonts > reset > source order, with like elements hoisted > media queries.

@font first as some older browsers ignored them if they weren't first in the file. Doesn't matter really on modern browsers but it's an old habit.

Any "reset" or global properties next because they set your baseline.

Then source order because

1) it's the order in which I build my stylesheet, top down, since I use progressive enhancement. That means content FIRST, markup second, CSS third.

2) Later on when debugging sections, it's just easier to navigate if things are in the same order in the stylesheet that they would be in the markup.

The exception to source order being when multiple sections receive the same style, since rather than derping pointless code-bloat classes into the markup to say what things look like, I say what things are and then hook it from the stylesheet.

Source order first also makes "specificity" hell less common, since things further down the page can easily override earlier ones.

... and media queries last because they have to be applied OVER the starting layout to make changes.

In general that's just always been what's made the most sense to me. The attempts to group by "purpose" or "size of selector" or anything else other people do feels -- to me at least -- harder to work with as it doesn't match my workflow.
Title: Re: CSS selector order: what is the best practice?
Post by: Gary-SC on 19 Nov 2019, 07:25:11 pm
Thank you for your insights. It makes sense. I will try that idea for my next job.  8)