Sunday, September 18, 2011

Importing CSS - 3 different ways

A web page constructs from 3 different layers:

 1. The structure & content layer (HTML)
 2. The style & presentation layer (CSS)
 3. The behavior layer (Script)


Creating a Web page, it is important to keep the layers separate. Keeping this separation makes site maintenance much easier and reduces bandwidth usage. Using CSS is the recommended way to control the presentation of web pages. It allows the presentation layer to remain separate from the two other layers.

<style>
Adding the <style> to your page "head" is the easiest (But not recommanded) way to include styles in your web page. It is not recommanded because it violates the separation we would like to keep between the structure & content layer and the style & presentation layer.

To use the style, just add it to your document:

<style type="text/css">
body {
background-color:red;
}

.myDivClass {
text-align:right;
}
</style>



Importing external (or using internal) CSS rules allows you to include style sheets code in your document.

<link>
Linking is a method for including an external style sheet on your web page. It's actually linking together your web page with your style sheet. It is added to the of your HTML document the following way:


<link href="myStyleSheet.css" type="text/css" />


The CSS @import rule
Another way to create a style sheet within your document is by using the @import rule. Remember that if you are using the @import than it should be the first thing in your document.
To use the @import rule, type:

<style type="text/css">
@import url("myStyleSheet.css");
</style>



There is no obvious difference between linking or importing it. Either way is correct, and either way will work equally. But please note the following:
  • Old browsers (IE v.4, Netscape 4) do not support the @import rule

  • Using @import rule you can use multiple style sheets on your page but only one link in your <head> seaction

  • Good programming practice is to separate the page style (CSS), the page behavior (javascript) and markup (HTML), Following this rule you should include on CSS line using <link> and link all your CSS to your page.