Sunday, August 2, 2009

Diferent ways to apply CSS to an HTML document

There is actually three different ways by which we can apply CSS to an HTML element. I will discuss here all three ways. But it is recommended the last one. That is put CSS in a file and then from HTML make a link to the style sheet. This is because in that case all CSS can be easily monitored just one file and we can easily use that file along the whole site. It is flexible too.

Way 01: In-line (the attribute style)
One way to apply CSS to HTML is by using the HTML attribute "style". Suppose we need to set color of a text. Using CSS color we can do that. But before that put the color attribute within style like below,
<span > This is red color</span>
And it will look like,
This is red color
If we run above code we will notice color becomes red.

Way 02: Internal (the tag style)
Second way of putting CSS elements is inside title tag of HTML. Within title tag using <style type="text/css"> CSS elements can be entered and then those CSS elements will be applied to whole page HTML in the page.

<html>
<head>
<title>Just an CSS example</title>
<style type="text/css">
body {color: red;}
</style>
</head>
<body>
This is red color
</body>
</html>

Way 03: External (link to a style sheet)
A third and good way of putting CSS things into a file. Like let's name the file as style.css and put all CSS things inside the file. Its contents are below.
body {
color: red;
}

And then the trick is to create a link from the HTML file to the style sheet (style.css). The following code inside HTML does the thing.

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

My full HTML code will look like,

<html>
<head>
<title>My document</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
This color becomes red because of stylesheet.
</body>
</html>

Related Documents

1 comment:

  1. Another important note to make is the order of precedence between the methods. I mean if all different methods are used and there are conflicts for a given element, which style is used in the browser?

    ReplyDelete