This past week I had an opportunity to browse through a company's coding guideline, some of which I found very useful not only in collaborative set...
For further actions, you may consider blocking this person and/or reporting abuse
Some other things that I've picked up at my current place:
backgroundoverridingbackground-image. The exception is when using prefixed properties (-webkit-*,-moz-*, etc), which should be grouped together.background: url(…);will override any existing background colour.I like the alphabetization of properties, some people don't like it, but for me it works. With regards to prefixed properties, I would strongly suggest not doing that manually but defining autoprefixer rules.
I agree with that, although there are times when you might need to manually specify prefixed properties, e.g. to offer a slightly different experience to some browsers
Great hints, thanks for that!
One general note regarding 7.: Comments are for what they are meant for: Commenting code that’s unable to explain itself by good naming.
It should NEVER been used to disable parts of code and commit that. Just delete it, that’s what version control systems are for.
I agree with this bit about commenting out code. Except for some occasions in personal projects when I want to save a WIP and it breaks the rest of the project in its current state, then I might commit something with commented out code...
Of course this is not the best way to handle this and it would make more sense to put it in its own branch, but you know... personal projects :)
I agree with all except on using IDs. IDs are meant to scope your following css rules nested on it, making it easier to find, adds scalability and performs much better regarding on how browsers render the views.
Also using IDs and adding !important statements are not equal in terms of specificity and priority. !important statements are priorized much more aggressively.
So you must add IDs on your styling for scoping code but not for adding properties that are likely to need an override. 😁
Cool, thanks for the tip Joel! I was a bit surprised too when I saw that the guideline advised against using
IDs. I have been quite cautious about using!importantstatements though.Some points on guides around here have their reasons that may not fit into your project or needs. Remember that html and css (or sass/scss) are not programming languages so there's no much point on getting "best practices" or "do this instead of that". They simply work or not, this tips are about increasing performance, readability or scalability.
With this in mind, there's tones of opinionated articles that didn't tested or benchmarked anything about the content, always test this tips by yourself 😁 assomeone else may go for performance and you want scalability or vice versa (some tips are contradictory depending on the tarjet), get that ones which fits best for you 😆
CSS is a programming language.
But even it it wasn’t, why would you say there’s no point in teams or developers formulating lists of best practice which are most suited to their needs?
CSS is NOT a programming language. CSS is a design language to define how HTML (which is a markup language and in fact, not a programming language) elements should be displayed.
Dev teams can of course define a list of best practices for a given project (not a generic one for all projects) depending on the goal they want to achieve. That's performance, accessibility, readability, compatibility (with old browsers) or scalability, or a mix of some or all of them. But you'll find some points where doing something could benefit a target and harm another.
For example, using multiple isolated classes can definitely benefit readability and scalability but can harm compatibility with old browsers ( I.E. 6 and older wasn't good managing multiple classes on a single html element).
So if you are into a project where you need compatibility, you must take the decision on doing one or another, you can't keep it all. That's why there's no much point on defining some things as "css best practices" globally or generically.
I wrote an article of css best practices by myself some weeks ago that you can check here:
dev.to/joelbonetr/css-and-scss-bes...
where I tried to explain what I do and why I do this, so you can discern if it fits into your code or not.
I'm not giving compatibility to old browsers because the users of my client's sites that use old browsers are less than 0,05%. I don't care much about accessibility on standard projects (clients usually does not want to pay the extra analysis and development for it) so I usually go for performance and scalability to make the modifications faster (and cheaper) to us, and getting better SEO due to mobile friendly and site low weight.
After all, everyone has to check all best practices, understand the details of every statement and check if each one can fit into their needs or not for a given project.
Why is CSS not a programming language?
Some nice tips here, most of them I agree with based on my experience.
Performance is an lesser known benefit when using the mobile first approach. The browser can just ignore the media queries which results in faster css processing as well as less processing.
Not sure if, with hierarchy, you meant to say html structure. I believe it's important to note for someone who may think this. I believe strongly we should not bind css classes to html hierarchy. Meaning if you do .teaser-content-title and then have to add another element between content and title, your css is inconsistent. I'm a proponent of using BEM and Atomic design which make the process of thinking about your classes much clearer.
Nesting with &__section is quite troublesome with regards to reading, searching, and refactoring the code. Some find it useful and like the brevity, but autocompletion in most IDEs solves this non-issue.
I agree with the sentiment of mobile first, its a good philosophy to follow. However, I've never seen the need to use min-width with desktop styles over max-width with mobile styles. At the end of the day, they accomplish the same thing and are almost identical, albeit a mirrored version of each other. As long as you keep your html structured in a way that will be possible to style for both, I think you're good.
However, I definitely wouldn't mix and match, especially not in the same stylesheet. That's just a headache waiting to happen.
What's wrong with
background-color: #000;??That one was not about colors, but using
.classvs.#id, which is debatable, as you might notice from the comments. I should've kept the color code consistent, sorry for the confusion. That said, the guideline prefers RGB values, and here's their full explainer on colors: github.com/we-make-websites/wmw-co...It makes sense, I never thought about the readability of rgb vs hex. Probably cause I've been using hex for years xD
Great article! I'm curious what others would say, but I found it useful to use !important for utility classes such as
m-t-5 { margin-top: 5px !important; }.Utility class with important is a place where important can indeed be used. The tricky bit is that in general you rarely would want to use utility class at all. At least that's the goal. It pretty much says "Design seems inconsistent, let's make our code inconsistent too".
Inline comments in CSS? 😂
PLEASE, specify that you're using Sass or whatever, because at least few of those things are not working in pure CSS
Yeah the guideline has separate rules for inline and introductory commenting, which I never thought about. And thanks for pointing out the SCSS specificity. Just modified my title accordingly.
I find number 8 to be a struggle all the time, but I think it comes down to how many nested classes your mind has the capacity to remember. Personally anything more than 2 nested classes results in me scrolling longer than actually reading and apprehending the code.
The rest - totally agree. Very informative post!
I’m curious on the last one about where to put media queries. I’ve used both ways but have found that I prefer the first way as it keeps everything together. The processor takes care of optimizing the code from what I’ve read so performance isn’t a reason as far as I understand. The second way, the preferred way in the article, ends up becoming distracting to navigate back and forth. What are the reasons to push the media queries to the bottom like that and break up information about the same class in two places? I did the preferred way first for a number of years and after I switched to the first (non-preferred) way it ended up working much better for maintainability for me.
This baffled me too. I’ve done both and ended up learning the “deeply nested” method ended up being far easier to comprehend in the long run, given the context was focused on the element being styled, not the media query. Particularly when reading the code of other developers’ code. For example, you may never realize (or may forget to check) for a particular element that there maybe yet another style being applied, maybe with a slightly different selector lower down in another media query.
I’m not sure if there are other technical considerations rather than just for code clarity and organization.
I learned to avoid nesting like this the hard way... this can make searching for certain classes with "cmd+f" extremely difficult, and I've sometimes spent way too long pulling out my hair looking for certain selectors:
To make my code more searchable but at the expense of "less beautiful code" I've been doing this more often (sometimes I do break my rule though):
Pretty good article, but you’re mistaken about #ids. Using #ids is invariably dramatically more performant than using .classes when the downstream CSS is processed in the browser. Whatever you might subjectively gain in style in SCSS (I’d argue against that, too) will not come even close to matching what you’ll lose objectively in CSS processing/rendering time.
I agree with most of the rules.
I disagree with leading zeros. You don't need them, so I don't use them. It's faster and easier to type.
Second one i disagree with is nesting media queries. The approach you've shown introduces a lot of repeating selectors in css. And if you search your code base for specific thing you will have a lot of unnecessary hits. Also, nesting media queries helps me to reduce actual nesting, because I tend to think more about it with this approach. Most of the code, with mobile first approach is in the root of the selector, and in the transition from mobile to larger screen, so I rarely have a lot of nested media queries, and if that happens I use approach that you've shown here. Only then, and that's rare.
Also, important rule can be very useful to prevent accidental override of certain layout rules. Definitely don't overuse, but it can be very useful.
As for the leading 0s, I know many linters/formatters add them (automatically for me) so I keep them there for consistency. If they're added automatically it doesn't take any time anyway.
For the media queries, that one is pretty situationally dependent. Either you're repeating selectors or you're repeating media queries, so if you have a lot of media queries, you'll end up repeating yourself more if you nest those over selectors. I tend to agree with the author however, and keep my queries as their own blocks, I find it easier to keep track of personally.
For leading zeroes, I guess it depends on the linter settings. I didn't run into problems omitting them. IE adds them by itself for example. It's just a personal preference of mine.
As for media queries I tend to observe each selector as a self contained module. For example class navbar has all of its media queries nested in itself. This way I can easily extract each of those modules in separate files, or reposition them or nest them differently. I don't have to search for all occurrences across the file. Shortcoming of this approach is, as you've said, repetition of media queries. But so far, in my case, repetition of selectors was a lot bigger pain in the but, especially for large legacy code bases.
There is nothing wrong with either of these approaches. Use what works for you. Cheers
Ah, I see. The guideline I was referring to also has a DRY (Don't Repeat Yourself) rule, which seems to contradict with the nested media queries problem you mentioned here 😅 Thanks so much for sharing your own experience! It's wonderful to see how different devs approach responsive design, as I have struggled with it at my (currently) early stages of front-end dev.
I must have missed DRY. My bad. Sry. Good article btw. Keep 'em commin'. As you've said, it's nice to see different approach and experience to responsive design.
No you were right, I didn't mention DRY here in my post, it was just stated in the guideline. I was merely echoing your comment that their Nested Media Queries rule was not so DRY after all lol. Again, thanks for the quick reply and encouraging comments :)
All good tips, but I have a different preference regarding the nested media queries definitions: I actually prefer nesting them separately inside each declaration. I find it easier to check what's happening and don't need to scroll much to find the changes for each media query.
Also, for better performance, it is a good practice to merge all media queries on processing the SCSS files, using something like github.com/SassNinja/postcss-combi..., for example
Thanks, this is an excellent post!
Heres a few additional things that helped me:
1Avoid naming colour variables after the colour. Go for $primary, #secondary, $light, $dark, etc. Eg:
You never know when a company will change it's colour scheme, and you can re-use the same colour.scss file accross multiple projects.
Another handy thing I use is creating new variables at the top of sections .scss files. For example, if I have a footer.scss file, at the top I might have:
That way I don't accidentally miss changing colours.
Nice article, thanx! Can you please share the Guideline or other resources With best practices in css/sass?
Sure, this is the guideline I was referring to: github.com/we-make-websites/wmw-co...
As for other resources, frankly I just pick up things sporadically, although I tend to come across CSS-Tricks site a lot.
Let me know if you find anything helpful as well :)
Thank you 💖 this is super helpful🤩
Thanks for reading the post, Ram! As other commentators pointed out, I think I need to solidify my understanding of CSS vs. SCSS capabilities. Perhaps that would be my next post 😉
please notice ! your css syntax works for scss or something like styled component in react not pure css. Otherwise good post.
Great catch, just changed my title to specify SCSS. Thanks so much for letting me know!
This is a really good summary. The only one I'm regularly guilty of is nesting the media-queries. I always do it and then regret it later!!
Great tips for beginers
Thanks for your nice posting
Look forward to your next post
Great article! Thanks!
Awesome!