CSS is essential for web development; however, it’s difficult to get right for your average developer, who may have interests elsewhere in the stack. Read this article to avoid needling inconsistencies and adopt best practices.
I’ll go over my top 10 Bad Practices in CSS.
Based on my experience with CSS as a developer, here are my top 10 “Don’ts.”
- Don’t Overuse Classes Use ID instead of classes where it makes sense. It’s a faster way for the browser to access DOM elements.
- Don’t Throw Everything Into One CSS File Partition your CSS to make it more manageable. Each CSS file could be broken into logical components like header.css, footer.css, etc.
- Don’t Name Your Selectors “.red-with-green-dashed-lines” Name your selectors as to what your components are on the page. For example: “header-left,” “content-title,” or “content-date” is more descriptive.
- Don’t Forget Comments Comments are extremely important in CSS to understand how each style could relate to another and what color scheme applies to which components.
- Don’t be Afraid of Dev Tools Each browser now has their own set of development tools, usually by pressing F12. These tools are critical when “debugging CSS.”
- Don’t be Afraid of Overrides Of course, CSS frameworks like Bootstrap and Foundation are massive, but each one needs a little tweaking based on your needs. When you get an update to the framework, it will overwrite your changes. Instead of digging into the huge CSS file, create a bootstrap-overrides.css file to bend the framework to your will, but just…
- …Don’t Overuse !important The whole idea with CSS is that the styles “cascade” down from one to another. !important just stomps all over previous styles and says “I’m more important… forget about all of that other CSS stuff and use me!” :-)
- Don’t Use a Ton of WebFonts This may be something obvious, but there are people who really love their typography. Use one or two (max three) WebFonts for your site and fall back to the browser defaults to keep your site optimized.
- Don’t Hand-code ALL of Your CSS For keeping your CSS DRY (Don’t Repeat Yourself), use a CSS preprocessor like LESS or SASS. The biggest benefit to using these preprocessors is that you can define variables like your color scheme at the top and reuse it throughout all of your CSS instead of tracking down every color when you have to modify them.
- Don’t Let Your CSS Become “Obese” Spaces in a CSS file take up…umm…space. Since we all want our CSS to load extremely fast, use a CSS minifier to shrink it down before deploying to a site. While there isn’t a “CSS Best Practices,” each company (or individual) has a certain culture or way of implementing CSS.
These are just some of my “Don’ts” when writing CSS as a developer.