Coding Standards - CSS Best Practices

This article will give you details on best practices to follow while writing CSS code.

1. Organize the Style sheet with a Top-down Structure
It always makes sense to lay your stylesheet out in a way that allows you to quickly find parts of your code.

Generic classes (body, a, p, h1, etc.)

/* Main Content */
Styles go here

/* Footer */
Styles go here

2. Combine Elements

Elements in a stylesheet sometimes share properties. Instead of re-writing previous code just combine them

h1, h2, h3{ font-family:thoma ; color: #333}

3. Use Multiple Classes

Use Shorthand

You can shrink your code considerably by using shorthand when crafting your CSS. For elements like padding, margin, font and some others, you can combine styles in one line. For example, a div might have these styles:


margin-top: 8px;


margin:8px 5px 6px 2px;

4. Use CSS Compressors

CSS compressors help shrink CSS file size by removing line breaks, white spaces, and combining elements. This combination can greatly reduce the the file size, which speeds up browser loading. CSS Optimizer and CSS Compressor are two excellent online tools that can shrink CSS.

5. Make Use of Generic Classes

You'll find that there are certain styles that you're applying over and over. Instead of adding that particular style to each ID, you can create generic classes and add them to the IDs or other CSS classes.

For example, I find myself using float:right and float:left over an over in my designs. So I simply add the classes .left and .right to my stylesheet, and reference it in the elements.

.left {
float: left;
.right {
< id="coolBox" class="left"> Content 

This way you don't have to constantly add "float:left" to all the elements that need to be floated.

6. Avoid Extra Selectors

Add Margins and Padding to All. Different browsers render elements differently. IE renders certain elements differently than Firefox. IE 6 renders elements differently than IE 7 and IE 8.

You can do this quickly with a global reset as shown below:

* {

Now all elements have a padding and margin of 0, unless defined by another style in the stylesheet.

7. Use Multiple Stylesheets

Avoid Using Inline Styles

Written by Piece User :