Wednesday, April 1, 2009

Use cascading style sheets (css) with your webpage

I'm going to assume you're familiar with the different properties you can set using css. If not, check out the tuturial here. There are a few different ways you can include cascading style sheets (css) on a webpage.

1. Inline
2. With the <style> tag
3. Using an external stylesheet


You can simply set the style property for various HTML tags. This works best if the css property you are defining is unique to that particular tag. If it is not unique, you will be better off using one of the other two options

<div style="position:absolute; color:red; width:100%; top:50px; ></div>

Using the <style> tag

You can use <style> to define css properties for an entire page. This helps to keep you from having to define the same properties over and over, and makes changes much easier. However, if the properties carry over from page to page, you most likely will want to use the next option of external stylesheets. The text below does the same thing as the inline example, except it will affect all <div> tags on the webpage this is defined in.

<style type="text/css">
div { position:absolute; 
top:50px; }

Including an external stylesheet (.css file)

If you have a styles that need to span multiple pages on your site, the best way to do that is with an external file that contains all of the defined styles needed. You can then link that file to any of your pages using a simple tag in the section, which will allow you to use the css properties within that file in any of those pages. This helps consolidate your properties to a single location so you can make site-wide changes by modifying a single line. This example assumes you have a file containing you css properties already, it's at the root of your site, and it's named myCSS.css.

<link rel="stylesheet" type="text/css" href="myCSS.css" />

It's relatively simple, and can make modifying your pages much, much easier later on. You should understand css inheritance as well. It's a top-down approach, and the style most closely defined to any particular element is the one that takes precedence.  This means you can override a css property defined in a linked stylesheet, or in a <style> tag, by using an inline style. If you want to find out more about css inheritance, I suggest checking out

No comments: