Learn Programming

Cascading Style Sheets (CSS)

What are Cascading Style Sheets

Let's say you make yourself a website one day. Your new website starts out with only 5 pages but after a few months it has grown to 100 pages. You decide that you don't like the old colour scheme and you want to change it. It will take a long time to change the colours on all 100 pages.

If you had used a stylesheet then you would have been able to change the colours in only the stylesheet file and they would be applied to all 100 pages immediately.

How to use a stylesheet

To use a stylesheet you must put a link to the stylesheet file inside your head tags like this:

<html>
 
<head>
<title>My first CSS page</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
 
<body>
</body>
 
</html>

Save this file as something like index.html. We now need to create the stylesheet.css file. The first thing we will do is change the background colour. Type the following line in the stylesheet:

body{background:#FF0000;}

Save the stylesheet and then take a look at the html file in your web browser. You will see that the background is red.

The example above will let you change the properties of the body tag in all the html files that link to that stylesheet. Any tag can be used in a stylesheet. Here is an example of the h1 and p tags:

h1{color:#FFFF00;}
p{font-family:sans-serif;font-weight:bold;}

Separating tags with a comma allows you to apply a style to all of those tags. Here is how you make all h1 and h2 tags have green text:

h1,h2{color:#00FF00;}

You can apply a style to a certain tag that is inside another tag by seperating the tags in the stylesheet with spaces. The following example will make all the bold tags in a paragraph blue.

p b{color:#0000FF;}

IDs and classes

You don't have to be restricted to only using styles by the tag name. If you want to make one set of p tags have red text and another set have blue text then you must use the id property. First assign an id to the p tags.

<p id="p1"></p>
 
<p id="p2"></p>

In the stylesheet you put the name of the id with a # in front of it.

#p1{color:#FF0000;}
#p2{color:#0000FF;}

You are only allowed to use id names in 1 tag. To give the same id to many tags you must use the class property instead.

<h1 class="abc"></h1>
 
<p class="abc"></p>

Classes have a . in front of them instead of a #.

.abc{text-decoration:underline;}

Styles in html tags

You can use a style inside an html tag if you want to by using the style property on that tag. You should try not to do this because it defeats the purpose of CSS but it can be useful in some situations.

<p style="font-size:20px;text-align:center;"></p>

Style names

Many of the new style names such as text-decoration are not like the ones used in html. It is a good idea to get the W3C's stylesheet reference to help you learn the new names.