An Introduction To CSS

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. View Plans

This section gives you a short description of CSS. CSS stands for Cascading Style Sheet, a means of separating the layout and style information from your HTML resulting in more manageable and maintainable code and additionally makes your pages work better across different browsers including screen readers used by disabled people.

Using CSS also means that you can completely change the look and feel of your site very easily without changing the HTML at all.

Objectives

The objectives of this module are to give you a solid understanding of how to use CSS within your web pages.

We will discuss the different ways to include style information and the different ways you can apply your styles to your HTML.

We will cover using CSS for layout as well as for formatting.

CSS syntax is straightforward.

identifier { property : value; property : value; }

The code is arranged in blocks a bit methods or functions, they begin with an identifier and then a pair of braces contain property name and value pairs with the name and the value separated by colons and the pairs separated by semicolons.

There are three basic types of identifier, tag type, class and id.

Type

Style blocks identified by the type of tag (h2, div, hr etc.) will be applied to all tags of that type on the page. For example if your CSS includes the following code then all level two headers will be displayed in blue.

h2 { color : blue; }

Class

If you start your identifier with a period (.) followed by a name then it will be a class, that class can then be used by any element. The following is an

Example of a class:

.warning-text { font-weight : bold; color : red; }

Id

Any block that uses an identifier starting with a hash (#) will be applied to the HTML element with a matching ID. Below is an example.

#page-title { text-align : center; font-style : italic; }

Combinations

It is also possible to use types, ids and classes in combination, there are a number of different options.

You can make an identifier more specific by joining types, ids or classes into a single identifier, for example the following example will define a class that only applies to paragraphs that use it. Note how the class identifier is prefixed with the tag type.

p.warning-text { font-weight : bold; color : red; }

You can expand an identifier so that, whether or not the style is applied also depends on the identify of an element's parent element. For example, the follow properties will only be applied to a hyperlink (anchor) with a class of hot-link if that hyperlink is inside a div with a class of navigation. Note the space between the parent and child identifiers.

div.navigation a.hotlink { color : green; }

Finally you can avoid duplication by applying the same properties to several identifiers by comma, separating them as follows. This will center headers at all levels.

h1, h2, h3, h4, h5, h6 { text-align : center; }

Using all these techniques allows you minimize duplication of properties and highly optimize your CSS but be careful to ensure your code stays clean and readable.

Importing CSS

Once you have written your CSS you need to ensure it gets downloaded by the browser along with the HTML. There are two ways of doing this, you can either include a style tag in the head section of your HTML document or you can use a link tag to import it from an external file. The following code demonstrates both methods.

<head> <link rel="stylesheet" type="text/css" href="mySite.css"> <style> #page-title { text-align : center; font-style : italic; } </style> </head>

It is important to consider how you are going to import your CSS based on how it is used. For example if you have CSS that is used on a number of pages it is better to store it in a separate file and link to that file on each page so that if you need to change it you only need to do so in one place. Likewise if you have CSS that is only used on one page it would be better to have it in its own file or included on the page.

A common scenario is that you will have a section of CSS that defines the theme of the site and is used on every page and then a section of CSS that is specific to each page, in this case you are best off having a global CSS file and a separate file for each page and have each HTML document link to two CSS files.

Referencing elements

There are three to associate a block of style information with an HTML element, they all use different attributes to make the association.

Style

Using the style attribute allows you to embed style properties directly in the

HTML elements as follows:

<span style="font-weight:bold;color:red;">Hello World</span>

Hello World (Red colored text)

Class

The class attribute allows you to specify one or more classes that should be applied to your element.

<span class="warning-text">Hello World</span>

Id

The id attribute allows you to assign a unique id to an element, you can then reference the element from with your CSS (or JavaScript) code.

<span id="page-title">Hello World</span>

Special cases

There a couple of extra rules regarding CSS syntax to help you handle some common situations.

Anchors

You will know that hyperlinks often have different styles depending whether you are hovering over the link or you have previously visited the page that the link refers to. The following code demonstrates how to achieve this.

a { color : red; text-decoration : none; } a:visited { color : green; text-decoration : none; } a:hover { color : orange; text-decoration : underline; }

As you can see, simply follow the normal tag identifier with a colon and the mode to identify the style block to be used for the different modes.

Properties with Multiple Values

Some properties allow you to assign multiple values by separating them by spaces.

This is a shortcut to using multiple properties with single values. The two style blocks in the following example are in fact exactly the same.

div.banner { border : 1px dashed red; } div.alt-banner { border-width : 1px; border-style : dashed; border-color : red; }

Bringing it all together

Now that you know the syntax and how to use it there are a couple of other bits of information that will make life a little easier for you.

Get an Editor

An editor can help you ensure that your syntax is correct and provide you with a good reference. Knowing what styles are available is as important as knowing how to use them.

Order of Precedence

As you have seen there are a number of ways to reference any one element so obviously there has to be an order or precedence so that we know which method will override another. The rule is actually quite simple, The more precise a reference is the high it is in priority. Consider the following example.

h4 { text-align : center; } h4.title { text-align : right; }

All the level four headers on the page will have their text center aligned unless they have class of title, in which case it will be right aligned, because the identifier with the class is a more precise reference than the one without. An id is more precise than a class, a class is more precise than a tag type.

Formatting text

There are a number of styles available to you to assist in the formatting of text as the following example demonstrates.

div#style-demo { font-family: "MS Serif", "New York", serif; } div#style-demo span.bold { font-weight: bold; } div#style-demo span.large { font-size: large; } div#style-demo span.highlight{ background-color: yellow; } <div id="style-demo"> Lorem ipsum dolor sit amet, <span class="bold">consectetuer</span> adipiscing elit. Nunc eu eros. Maecenas et orci a augue semper molestie. In hac habitasse platea dictumst. Mauris faucibus leo dictum ligula. <span class="large">Curabitur lobortis</span> est. Vestibulum ut lacus vel libero tempor malesuada. Nam id metus ut magna molestie tincidunt. Fusce enim. <span class="highlight">Phasellus consectetuer</span> massa at elit. Fusce rutrum lacus at purus. Ut ligula elit, semper porttitor, auctor sed, vehicula non, metus. </div>

The code above executed in a web page results in the wording AND style below. (Execute the code above in a web page to see the result)

We can learn quite a lot from this example. The first thing to note is that the tag span is an inline element which means that unlike block elements it does not effect the page flow. Another important thing to mention is that when setting the font you wish to use it is a good idea to specify more than one, the first font in the list will be used unless the user does not have it installed, the browser will then try the next one in the list, when it has reached the end of the list, the browser will make a guess and, depending on the users browser, may choose the next font in alphabetical order. This will be a problem if the next font is actually a set of symbols rather than letters like webdings.

Positioning

Positioning is one of the most important areas of CSS to make sure you understand properly. It is easy to wrongly guess the effect of a particular style and get confused but if you follow the rules explained here you will be fine.

Code the HTML first. Obviously write your HTML in a logical and make sure it is understandable and readable before you start styling it. Test as you go. Don't expect to write a stylesheet for an entire page without checking it as you do it. Position the bigger sections first. You page will often be made up of several sections (header, navigation, body & footer for example), position these first and then move on to the nested elements. Only block elements like div and p can be positioned, inline elements like span can't. (Some browsers will allow you to but you will end up with a page that doesn't work cross-browser.)

Positioning Options

When positioning an element you always position it in relation to another element and you have two main choices, relative and absolute. It is important you understand these two terms.

Relative

If you use relative positioning, you will be positioning the element in relation to where it would naturally appeared. Additionally the space where it would have appeared does not automatically get filled by the next element.

Absolute

If you position an element absolutely, it will be positioned relative to its first ancestor that has it's positioning mode set. (This is where most people get a little confused.)

For example, if you position a div absolutely and it's parent does not have it's position style set then the browser will check the parent of the parent and so on until it finds an element that is positioned or it reaches the body element. When positioning an element absolutely it is promoted to its own layer meaning it can be positioned over other elements and its space is not saved for it.

Once you have set the position property you can use top, left, bottom and right properties to set the coordinates of your element. Look at the following examples to demonstrate this.

<div style="position:relative;width:150px;height:150px; background-color:pink;"> <div style="width:50px;height:50px;background-color:red;"> </div> <div style="position:relative;top:-25;left:50;width:50px;height:50px; background-color:green;"> </div> <div style="width:50px;height:50px;background-color:blue;"> </div> </div>

You can see in this example of relative positioning that the blue block has not moved up to fill the space left by the green block.

<div style="position:relative;width:200px;height:200px; background-color:silver;"> <div style="margin:25px;width:150px;height:150px;background-color:pink;"> <div style="width:50px;height:50px;background-color:red;"> </div> <div style="position:absolute;top:0;left:0;width:50px;height:50px;background-color:green;"> </div> <div style="width:50px;height:50px;background-color:blue;"> </div> </div> </div>

In this example of absolute positioning, the pink block does not have its position mode set so when we position the green block it is positioned in relation to the silver block. Additionally note how the blue block has moved up to fill the space left by the green block.

Floating

An alternative to position is floating. If we float an element (either to the left or right), it drifts across either until it reaches the edge of its parent or another element. If it frees up enough space the element below its original position will move in to the space. Look at the following example.

<div style="width:150px;height:150px;background-color:pink;"> <div style="width:50px;height:50px;background-color:red;"> </div> <div style="float:right;width:50px;height:50px;background-color:green;"> </div> <div style="width:50px;height:50px;background-color:blue;"> </div> </div>

We have floated the green block to the right and the blue block has automatically moved up. Although less flexible, this method is neat and often useful.

Conclusion

Having completed this course and followed all the instructions, it means that you can completely change the look and feel of a site very easily without changing the HTML at all with the solid understanding of how to use CSS within web pages gained from the course.