A few CSS rules to keep in mind

When writing CSS, there are a few simple rules that will make your life easier. 
1. Using ‘* {box-sizing:border-box;}’.
Using this will wrap all your elements in a nice little compact box-model that will give you the width you want, like so... widthbox.png It is also fast and well supported across browsers. 
2. Center div using {margin: 0 auto};
From the CSS specification, “If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”
This rule is easy to understand and remember. As long as the width of the parent container of the div you want to center is larger than its child element, using margin: 0 auto will center a div. 

3. Group CSS on one line.
For readability concerns, do this: 
border: 1px black solid

Open in new window

instead of this: 
border: black;
                      border: 1px;
                      border: solid;

Open in new window

4. RARELY use !important;

This one is fairly intuitive, as long as you know what ‘!important’ does. But in case you don’t. ‘!important’ breaks all the rules that CSS sets up for us. For instance, there is an order of operations (of sorts) to CSS that allows you to keep track of what selectors have priority. #id is more important that .class, but both are less important than inline CSS in html.

Using ‘!important’ breaks all these rules and tells your compiler to use the rule specified no matter what the order of operations tell us. This can be extremely difficult to keep track of as your site grows.

5. Keep selectors simple/intuitive.

Don’t do this.
.class div div h1 > a#someid{}

Open in new window

 This code is hard to read and is (slightly) slower than simply targeting the element you want with an id. I’ll let the guys over at CSS-Tricks explain it in further detail for you. http://css-tricks.com/efficiently-rendering-css/. But in the meantime, just add an id to what you want to select.

6. Understand rem vs em.
‘em’ is the size of text proportional to its parent containers' font-size. ‘rem’, which stands for 'root em' is the size of text relative to the html (root) size.
 For example: If you have font-sizes that scale relative to the html root, you’ll use ‘rem’. If you have font-sizes that will inherit sizes from their parents, you’ll use ‘em’.


7. Be aware of the IE rule limit.
       IE 6 – 9 have a rule limit of:

  • A sheet may contain up to 4095 rules
  • A sheet may @import up to 31 sheets
  • @import nesting supports up to 4 levels deep


Comments (1)

Can you provide practical example on # 2? Excellent

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.