How to add CSS to a page

Feb 15 2012 Wednesday   |   Views (3263)   |   Comments (4)
Untitled DocumentCSS is an incredibly powerful language and diverse in its application. This tutorial will explain how to incorporate CSS into a webpage using a variety of methods.

CSS Application
There are 3 main ways in which you can incorporate CSS in to a page:

1. In-line CSS Style
CSS is written in to the HTML code at the point where you want it to be applied.
Example: <span style="color:red">This text is red </span>
Result: This text is red

By using the attribute 'style', you can place any type of CSS code to control the text, images, URL links, etc with the confines of the enclosing tag - in this case a '<style></style>'. You could also apply it to other HTML tags:

<b style="color:red">Red and bold</b>
<i style="margin:10px">CSS Margins</i>
<h2 style="font-weight: normal">Non-bold header</h2>


2. Internal CSS Style
An Internal CSS style is where you have your CSS at the top of your code (usually inside the '<head></head>' area) within '<style></style>' tags. This will cause any reference to that styling throughout the rest of the page to conform to it.

<head>
<style type="text/css" media="screen">
h2 { font-weight: normal }
p { color:red }
</style>
</head>

<body>
<h2>This is not bold</h2>
<p>This paragraph is red</p>
<h2>This also is not bold</h2>
<p>Yep, you've guessed it, this paragraph is also red!</p>
</body>

3. External CSS Style
Internal CSS is good for introducing styling that is particular to that page, but external CSS allows even greater control. External CSS is CSS code that is place in to a file that is referred to by 1 or more pages.

Example: Using your source editor, create a new page and call it something like 'my-style.css'. Whatever name you choose, just make sure that it ends with '.css'. Within your css page, add the following:

p {color:blue}
b {color:red; text-decoration: underline}


Now create an HTML document - call it whatever you like, but add this to the top of it, preferably within '<head></head>'the section:

<head>
<style src="my-style.css" type="text/css" media="screen"></style>
</head>

<body>
<p>This paragraph of text is coloured blue. And any <b>bold</b> text is both <b>red and underlined</b>.</p>
</body>


Now make sure you have saved both documents in the same folder. You can put the css into another folder, just make sure that the 'src' or 'source' points to the file correctly. When testing the HTML file within your browser, you should see something like the following:

This paragraph of text is coloured blue. And any bold text is both red and underlined.

By James Middleton

Comment

* No comments so far

Comment