Monday, October 17, 2011

CSS for beginners

If we want to style any control in an html page (by control I mean textboxes, labels and all other html elements that can be displayed in an html page), we can easily do it using the style property. For example if we have the following heading:

<h2> Heading </h2>

And we wish to change its colour to green and make it italic, we can easily do so using the style property as shown below:

<h2 style="color: green; font-style: italic;"> Heading </h2>

Similarly, we can use a range of properties to stylize any control we want. However, this is not a very good programming practise. If we want to stylise our controls in a way that makes our styles more re-useable, we need to do it in the following way:

On top of the page we need to write the following code to make a style class with any name we want (in this example I have used the name MyHeading).

<style>
        .MyHeading
        {
            color: Green;  
            font-style: italic;
        }
</style>

Then in our html we can write the following code:

<h2 class="MyHeading"> Heading </h2>

With this code we will be achieving exactly the same result as above with the added benefit of code re-use in other places such as:

<p class="Myheading">This is a paragraph</p>

In this approach, we are using a style class to style our page. This can be a good approach to style a page; however we can go one step further by using a cascading style sheet.

Cascading style sheets (or CSS) allow us to create a “.css” file containing many style classes. This css file can then be attached with any webpage giving it access to all its style classes.

 To attach a css file to an html page, we need to write the following line on top of the webpage (above its html code):

<link rel="Stylesheet" type="text/css" href="/Location/File.css" />

In the css file, we need to write the following code to create a style class:

.MyHeading
{
      color: Green;  
      font-style: italic;
}

After this, we can use any class from the css file to style the controls of our page. The benefit of using this approach is that css files allow us to use the same style sheet throughout our website, and ensure a consistent layout across all pages, thus allowing maximum code re-use.

No comments:

Post a Comment