Over the years I’ve seen hundreds of different writing styles for Cascading Style Sheets (CSS) and I’ve yet to see any consistency or logic in these styles. Many coders, and designers, create styles on an as needed basis generally lacking any organization whatsoever. Though most try to organize their CSS they commonly end up making more of a mess or create an exhaustive list of multiple style sheets.
So is there a right way to write CSS files? Not really, but I believe I’ve found the simplest and most organized solution. The common challenge is maintenance, how can coders write style sheets for every document of their site while easily maintaining the style sheet?
One CSS File To Rule Them All
Practice writing only one CSS file for your entire site. By creating multiple CSS files browser caches aren’t efficiently used, if a user goes from the home page to the about us page their browser would have to make an additional request to retrieve the new style sheet specifically for the about us page, instead create one file that will be loaded and cached when a user first visits your domain.
Short And Sweet
Practice writing shorthand CSS. Shorthand CSS are one-liners for multiple HTML Elements, Identifiers or Classes containing shared styles. The example below demonstrates how shorthand CSS is generally written, including an optional comment at the start of the line.
/* A Comment */html,body,#myid,.myclass{color:#000;}
Keep It Organized
Practice logical sorting to allow quick reference. To help keep your CSS organized, write the selectors in a logical order based on what comes first in the documents for your site. In the following example, assume that there is a div containing an h1 and p tag in a properly formatted HTML document.
/* These come first */html,body{color:#000;}
/* Followed by this */div{display:block;}
/* And then this */h1,p{color:#666}
Select What You Must
Using the inspector for Chrome or Safari, or Firebug for Firefox, coders can quickly and efficiently identify CSS selectors. Choose selectors that don’t require parental selectors to decrease the amount of selectors in your CSS file.
They All Look The Same
Cross Browser compatibility is the most common issue on the web, to avoid inconsistencies many coders will reset basic HTML elements. There are many reset solutions on the web, however I strongly advise coders to create a basic HTML document and determine what HTML elements they commonly reset (body, ul, li, div, p, etc) for a more personal solution to match their coding style.
Avoiding Bad Practices
By following the above suggestions you can avoid common CSS issues. Most coders will write their CSS files with claims of going back and cleaning it up, except they rarely do. Writing a CSS file the right way the first time around will save you hours of debugging and rewriting.
- Posted in Blog
- Tagged with
- Be the first to comment
Connect With Me On LinkedIn
Follow Me on Twitter
Jay's Plugin Development For WordPress