CSS Tips

Some guidelines I find useful when writing CSS styles:

Use an identifier, not the tag name

Except for setting those general styles at the body, headers, anchors etc. you should never go for this:

.someRegion div { ... }
.someRegion div a { ... }

Just because you may decide to make that “div” a “p”, or an anchor, which would force you to change the style selector to maintain the style. But also, because forcing a combination of HTML tags could make you lose styles or scripts assigned this way in case the DOM chain changes (moving an element outside of its “div” or “p”).

A better approach would be:

.someRegion .myElement { ... }
.someRegion .linkType { ... }

Don’t name identifiers by their current style

If you have a green box in your website, you may be tempted to add the style “.greenBox”, but unfortunately in future that green box may end up being red. It will look wierd to have a red box with a style “.greenBox” and could be too time-consuming and even risky to change the style name. Much better to avoid generating a problem by not setting such a name, think about the purpose of that box or its behaviour and try to find better names like “.notesBox, .warningBox, .tipsBox, .hihglightedBox, …”. That will give you no trouble when changing the styles.

In the case you can’t find a descriptive name, at least avoid adding a confusing name. This is, better call it “.genericBox” than “.greenBox”, as the green could change in future and be confusing, even if “.genericBox” doesn’t guide you much it doesn’t misguide you either.

Be care with very common identifier names

As adding widgets, plugins and javascript libraries has become quite common, we do not have the full control over elements names anymore, we could think it’s so logical to call a box style “.box”, but may end up finding out that some other pieces of code done by external developers that we include into our project also uses such style to set some script feature or styling. To avoid this, and also because even we could need to generate a second box type in future, it seems better to avoid very simple style names.

If a style like .header really looks like “the right one” but also looks “too common” a right approach is using cascading to add a combination that will make it sure that header is displayed on the appropriate place. For example:

.someRegion .header{ ... }
.someRegion .footer { ... }

That way you make sure that header and footer are displayed there without affecting other header and footers that may be declared on the site.