Goal

Modularize CSS styles for a HTML page in flexible components (HTML + CSS) that can be freely moved around without breaking anything.

How

To achieve the above goal, we will do the following writing CSS.

1. Avoid using IDs and element selectors, sticking only to class names.

Only include a selector that includes semantics. A span or div holds none. A heading has some. A class defined on an element has plenty. By adding the classes to the elements, we have increased the semantics of what those elements mean and removed any ambiguity when it comes to styling them.

Instead of:

Code:
<div class="fld">
    <span>Folder Name</span> 
    <span>(32 items)</span>
</div>
Make it like this:

Code:
<div class="fld">
    <span class="fld-name">Folder Name</span> 
    <span class="fld-items">(32 items)</span>
</div>
2. When we style the same module differently at different positions, avoid specifying the parent element in the selector, but sub-class it.

Try to avoid conditional styling based on location. If you are changing the look of a module for usage elsewhere on the page or site, sub-class the module instead.

Instead of:

Code:
.pod { 
    width: 100%; 
} 
.pod input[type=text] { 
    width: 50%; 
}
#sidebar .pod input[type=text] { 
    width: 100%; 
}

.pod-callout { 
    width: 200px; 
}
#sidebar .pod-callout input[type=text],
.pod-callout input[type=text] { 
    width: 180px; 
}
Make it like this:

Code:
.pod { 
    width: 100%; 
} 
.pod input[type=text] { 
    width: 50%; 
}
.pod-constrained input[type=text] { 
    width: 100%; 
}

.pod-callout { 
    width: 200px; 
}
.pod-callout input[type=text] { 
    width: 180px; 
}
So the HTML is like:

Code:
<div class="pod pod-constrained">...</div>
<div class="pod pod-callout">...</div>






This article is a digest of this one.