Tuesday, March 15, 2016

CSS Rules of Thumb

While going through old piles of paper on my desk I found a list of CSS rules of thumb. Rather than toss them I will out them on my blog.

1. Avoid long chains

Don't have long chains of rules. This is very easy to do with Less or Sass, but these are both fragile and hard to reuse. This kind of code is seductive because you can assure that CSS you add won't cause any other problems, but it leads to too much CSS that is not reused.

2. Use right element

HTML is not very semantic, but it does convey information. Use elements that make sense. A button should be a button, a label should be a label, a link should be a link. You can make a button out of some other element, but it makes the HTML markup harder to read.

3. Use grids for grid behavior

There are lots of grid based packages for CSS. They are very nice for layout and you should use them instead of trying to do them yourselves. Note that grids may not be the best thing for a left aligned and right aligned layout.

4. Use div to group elements

The structure of divs should align with the structure of the page.

5. Try to avoid single div inside a div

Most of these can be removed and add nothing. Page performance is related to the number of dom elements so removing useless DOM nodes is a valuable thing to do.

6. Separate out parts of a class

A CSS class can have many parts including fonts, coloring, positioning. It is better and more flexible to separate out these things. Instead of having one class that defines everything break it into multiple classes that define each individual part. Think of it as Interface Segregation for CSS.

7. Use special cases

Try to use basic patterns. If they don't work, try to create a special class that would be like class="foo bar" with foo being the basic pattern and bar being the special case. Then in the CSS you would define a rule like ".foo.bar" to highlight the special case. Note that this pattern is not supported in IE6, but if your web site does anything for IE6 beside redirecting to a place to download a new browser, you are part of the problem.

1 comment: