Understanding Cascading Style Sheets (CSS)

From Techotopia
Revision as of 17:12, 17 May 2007 by Neil (Talk | contribs) (Importing an External Style Sheet into a Web Page)

Jump to: navigation, search

To fully understand the power of JavaScript it is first necessary to understand Cascading Style Sheets (CSS). If you are already familiar with CSS then you can safely skip this chapter and move on to the next chapter (JavaScript and CSS).

Whole books have been dedicated to learning CSS and there is far more to CSS than can be covered in this chapter. The purpose of this chapter, therefore, is to provide a basic understanding of CSS and convey enough information to enable you to work with CSS and JavaScript to create dynamic styles and layouts in your web pages.


Contents


What are Cascading Style Sheets for?

In the early days of the world wide web all we had to create content on web pages was HTML. HTML does some things very well, but does not provide a great deal of control over style of web page content. Furthermore, what control it does give us has to be embedded into the content. Essentially this meant that style was not separated from content. If we wanted to change the overall look and feel of a web iste we had to edit each individual web page and chaneg the style settings.

Cascading Style Sheets allows us to specify the style of the content in a separate file which can be changed such that modifications are reflected in all pages that include that style sheet.

Withthe introduction of CSS it is now possible to define the document structure and content in HTML, while controling the style and appearance using CSS.

Embedding CSS Styles into a Web Page

CSS style can be embedded in an HTML document using the <style> tag as follows:


<style type="text/css">
  H1 {color: red;}
</style>

The above style settings as the effect of making all <H1> headers in the web page appear in red.


Importing an External Style Sheet into a Web Page

Whilst it is possible to include all your CSS styles by embedding them into each HTML page this, to a certain degree, defeats one of the main objectives of CSS. It is much better to place the styles in a separate CSS file and import that file into each weeb page. This means that a change to the overall style only needs to be made to the external file in order for the change to take effect in all pages that include it.

First, we can create our external CSS file. This is the same concept as outlined for embedding the styles into an HTML file, except the <script> tags are not required. For example we can create CSS filed myStyle.css as follows:


H1 { color: red}
H2 {font-weight: bold }

To include our style sheet into a web page we simply use the <link> tag:



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

Creating CSS Rules