How should CSS being setup (Part 1)?
Published in
3 min readSep 8, 2018
This is not a CSS tutorial post, just some share of my personal experience and some best practices.
You can say that CSS is easy to learn and play with, but in deep it could be really complicated if you do not have some rules to follow, here are some rules that I think quite important to follow.
- Keep everything simple and plain.
CSS is not something that let you to show off how you can create something really complicated, but to create simple CSS to let other people to follow easily. Remember these other people could be your colleagues or even your own future. So please do not create some selector name is really hard to understand. - Prevent using ID as a CSS selector.
You may already know ID is a quite specific in CSS selector, which is relatively hard to overwrite (ID > Class > Tag Name). And even if you really could overwrite it, that action is possibly already mess up your code and you may not even know at the time being. I am not saying that do not use ID at all! ID is useful in javascript, I will cover this in future article. - Prevent using !important at the style property.
The reason is similar to prevent using ID as a selector, but this one is even harder to overwrite, so, please please please avoid to use it. - Nope, tag name is wrong too.
Tag name is too not specific enough, you may think like, ah I love to use blue as my background color, so you set div{background-color: blue}. Imagine what will happen? Sure you can do that, but, come on, why……? - Yup, please use class.
Class is specific but not too specific and it’s also easy to overwrite, and if you want to create an element with a ID attribute you could also give it a class name same as it’s ID to create a unique style, but please remember do not use it everywhere. - Do not use text editor prefixer.
Some text editor come with a prefixer which make it easier for you to handle cross browser issues, but if you are also using grunt or webpack you may come across a tool named autoprefixer or postcss. This tool help you to add prefix to your css code automatically, and you can use different setting to target how many previous browsers to support, which is quiet handy. Read more here. - Put your own css files after CSS framework(e.g. Bootstrap, Foundation, UIKit, etc.)
This one is simple to understand, since your code could cascade their code. - Only use what you want in CSS framework.
If you are using or want to use CSS framework, remember some CSS framework allow you to pick some particular modules that you need, if you do that, your CSS file size could be much smaller, since you already remove those redundant modules.