Chris
0

Cascading Style Sheets are the cornerstone of your website's presentation. They control the appearance and position of HTML elements on your site. We've already taken a look at some tips for writing better markup, now let's do the same for CSS.

1. Be specific

The portion of a style declaration that identifies the element it belongs to is called the "selector". It is the first part of the declaration and the most important. If you wanted to add a 10px top margin to each image in your site for example, you would use "img" as your selector as you are selecting the <img> element to apply styles to it.

img{
	margin-top:10px;
}

Great! Except...now you realize that you don't want a top margin on every image, just a few. Also, you're being asked to add a red border to only one specific image. Now we need to select certain images and exclude others; we need greater specificity. To do this, CSS allows us to use classes, id's, and attributes as selectors.

.myClassName{
	margin-top:10px;
}

#myID{
	margin-top:20px;
}

img[title=myTitle]{
	border:1px solid red;
}

Now, our styles are attached to only those elements that need them. We can even attach styles to the descendants or siblings of HTML elements using the ">" and "+" characters respectively. "Pseudo-classes" and "pseudo-elements" allow you to select elements based on changes in state or make subselections within an element. This is most often the case for styling links when the mouse cursor hovers over them using the ":hover" pseudo-class.

.myAwesomeLink:hover{
	text-decoration:none;
}

Using the above declaration, the underline on the link will disappear as the cursor hovers over it.

2. Use a Reset style sheet

If you create a webpage in HTML but don't style it, your browser will automatically apply default "user agent" styles to your document. This will do very simple things like add margins and padding to text elements, so that they are easy to read in the absence of specific styling. This is problematic since the browser styles will apply where you haven't specified your own styles. To add insult to injury, different browser's user agent styles are different. For example, a level one heading (<h1>) will generally be given margins by each browser. Internet Explorer 8, however, applies 0.67 em top and bottom margins, while Firefox 3 applies 21.4333 pixel top and bottom margins. Clearly, you can see how this might be frustrating if you were unaware this is happening or how to fix it.

To avoid these difficulties, sometimes it's best to utilize a reset stylesheet. Attach the reset style sheet to your document before your own styles and it will "reset" or override any defaults the browser puts in place. Now, you're free to specify each property of each element precisely. There are plenty of tutorials for how to initially reset styles but there are also pre-made style sheets available. Personally, I prefer Yahoo's YUI3 CSS Reset although Eric Meyer's CSS Resest is also highly effective. Either link to these above your current style sheet or include their declarations in it and you're good to go!

3. Make your styles modular

The majority of styles you write will end up being specific to certain objects. However, you will find yourself applying certain properties to multiple elements. This is especially true for floating elements left or right, hiding an element's overflow, or displaying an item as block or inline. For these cases, you may be best served by making several modular classes that perform only those functions.

To do this, create each rule as it's own class and append those classes to whichever object you need to use them on. In the case of floats, you end up with a "left" or "right" class that contains only your "float:left" or "float:right" rules.

left{
	float:left;
}

Now add that class to your element and it will gain that functionality. Want a blue paragraph that is floated to the left? Simply add your "blue" and "left" classes to your paragraph and you're done!

<p class="myParagraph left">My awesome floated paragraph.</p>

4. Comment and Organize your code

A very important development habit is making sure to comment and organize your styles into logical sections. This is critical if you're working with other developers and sharing code back and forth.

Consider working on a website and your fellow developer hands off his early style sheet to you. Except, instead of being a nice, orderly document, it's messy, hard to read, and the declarations are simply listed in the order that your coworker came up with them.

body{color:black;line-height:16px;}p{font-weight:bold;}div{width:500px;}.myClass{background:blue no-repeat;font:verdana;}#myID{margin:10px 0px 1px 8px;padding:0 0 0 0;}

This is a nightmare to try and make sense of and can bog you down trying to simply read and understand what you're looking at when you should be concentrating on writing awesome styles.

To avoid this, try grouping your styles according to their function, their location, or whatever scheme you find works best for you and your team. For example, you could create and group all of your navigation styles together, your article styles together, or maybe, your "About" page styles together. Placing commented headers to these sections is going to be important for readability, so label them appropriately. A big, chunky comment header is an easy way to decipher where your sections of code begin and end.

/* ---------------------------------------- 
	My Navigation Styles
------------------------------------------- */

If you have a complicated workaround, hack, or otherwise find it necessary to include extra information about your style rules, you should include a comment on those lines. This is the perfect way to notify your other developers of potential issues or specific problems you ran into and have a physical note or reminder of it's exact location in your stylesheet.

.myClassName{
	margin:100px;
	_margin:100px; /* Hack: Makes IE6 not suck at everything */
}

Lastly, make sure that your declarations are easier to read by separating each rule onto it's own line. In a production environment, this is much easier to glance at and get an understanding of what the declaration is actually doing.

.myClassName {
	background: blue no-repeat;
	margin:10px 0px;
	padding: 0px;		
}

Once you're ready to push your site live, your can run your style sheet through a compressor to remove extra white-space and format your code for efficiency, rather than readability.

5. Hacks, Workarounds, and Progressive Enrichment

Hacks will unfortunately be a necessary part of production development. Each browser is supposed to interpret style declarations according to W3C recommended standards. However, in practice, this is not the case. Some features may be adopted quickly, while others go unsupported for years or have significant issues affecting their usage. If you're still using IE6 as your primary browser you may as well forget about compliance entirely.

Fortunately, the intertubes are awash with workarounds, fixes, and hacks to force browsers to behave or pretend they're standards compliant. Some are reliable, others are not. Some will fix one problem only to upset another portion of the design, like a fine game of Whack-a-Mole. The best way to avoid dealing with css hacks is...to not deal with them! Find any alternate way to do what you're trying to do without a hack. If you do have to hack something, try to isolate the hack as much as you can. Make sure it's not creating dependencies that break other portions of your code. If you're including hacks for IE bugs, you should use conditional comments to target specific versions of that browser as necessary. This is done by inserting a new link to an IE specific stylesheet (say, IE6.css or IE7.css) and wrapping it in a proprietary comment structure that only IE will understand. All other browsers will ignore these comments and the linked style sheets, leaving you with totally isolated hacks for that browser and nice, clean, standards-compliant code for every other browser.

<!--[if IE 6]>
	<link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen, projection" />
<![endif]-->
		
<!--[if IE 7]>
	<link rel="stylesheet" type="text/css" href="css/ie7.css" media="screen, projection" />
<![endif]-->

If you don't have to support old browsers like IE6 (and there are so many reasons not to), don't invest the time trying to make your design look similar on that platform. You will be much better served by focusing attention on enhancements for users that DO have modern browsers. This is a concept referred to as "Progressive Enrichment", where you do what you can to ensure a reliable experience for users of older browsers but utilize modern browser features to make your site's experience as good as it can be. For example, the most recent versions of Apple's Safari, Google's Chrome, and Mozilla's Firefox browsers have begun to implement portions of the forthcoming HTML5 and CSS3 specifications. These specifications are incomplete, so support for some features is still on the way, but these browsers allow you to add some pretty neat effects today. These features are accessed using a propreitary selector for each browser. In the case of Safari or Chrome, the prefix is "-webkit-" while Firefox uses "-moz-". Append this prefix to the property you want to use and the effect should appear in those browsers.

.myClassName{
	-moz-border-radius:5px;
	-webkit-border-radius:5px;
}

The style declaration above tells Safari, Chrome, and Firefox to apply a border radius to an object, giving it rounded corners without the extra markup or styling that is usually necessary to accomplish this effect. There are great things coming down the pipe, but you can use some of them in your projects right now if you invest time in utilizing them, rather than supporting antiquated browsers. This is absolutely going to depend, however, on who your target audience is. If you're designing a company intranet that just has to work on IE6 (why you would make this your company's policy no one knows), then you're not likely going to get anywhere by including things like border-radius or css transforms for advanced users. Vice versa, if your metrics show your traffic is predominately Safari 4, Chrome, or Firefox 3.6 users, it makes plenty of sense to give your users some cool features and never look back.

 

I hope everyone finds these tips to be useful when developing CSS. Encouraging best practices my seem at first like a hassle. It generally takes a bit longer to get things done the right way, however, that extra time will be well spent. Clearly defined selectors, no more messed up, illegible code to try to read through, fewer complicated hacks or workarounds for broken browsers, and a focus on feature enhancements for modern browsers. Sounds pretty good to me!

Bookmark and Share

Add comment




biuquote