You are on page 1of 6

FEATURES | CSS

Cascading style sheets


Will Head looks into one of the best developments to grace the web since its invention: CSS

Employing

HTML documents to be modified, followed in curly brackets by a list of declarations that specify exactly which aspect of that element look to modify. A declaration takes the form of a property, followed by a colon, then a value, followed by a semi-colon. So, an example rule would be:
p{ color: fuchsia; font-weight: bold; }

n the early days of web design, HTML was used to define the structure and layout of pages, but this approach quickly became unmanageable. To solve the problem, the CSS (cascading style sheets) standard was introduced, with the aim of separating the design from the content of web pages. If CSS is implemented properly, its possible to alter the appearance of an entire website just by modifying one file. So, rather than having to go through file after file to make changes, all the information that relates to the design is in one place. CSS also makes web pages more accessible to those using alternative methods to browse the internet, the primary beneficiaries being people with limited vision. Using screenreader software, reading out the text of a page is far less error-prone if a site correctly separates style from content with CSS, since it makes the job of deciding which bits should be read and which bits shouldnt much easier. CSS also provides far greater control over the layout of websites than HTML ever did, so if you want a modernlooking, easy to maintain and accessible website, you should be using CSS to define the look of your pages.

projects, though. TopStyle Lite (www. bradsoft.com/topstyle/tslite) is a free editor, which makes creating stylesheets easier and less error-prone, as it includes syntax highlighting. It also has code completion, so as you type your code it will display a drop-down list of any items that match. If you prefer a more visual approach, KompoZer (www.kompozer. net) includes a built-in CSS editor that allows you to specify properties through a dialog box rather than writing them by hand. See the walkthrough opposite for more on KompoZer. Each CSS rule starts with a selector that identifies the element of your

EXTRA!

You'll find part 1 of this series on the cover disc and on-line at web id 101696.

In this example, the selector is the HTML element p, so the rule will apply to all text within paragraph tags in its associated webpage or pages. Two declarations are specified, which result in the text being rendered fuchsia in colour and bold.You can immediately see the syntax of CSS is clear, simple and easily readable. While the ability to make all text within paragraphs tags the same is useful for consistency, there are times when youll need greater control over which parts of the document you want the rules to apply to. CSS provides a range of selectors for this purpose.

Type selectors
Type selectors correspond to HTML elements of the same type, such as p or h1. For example:
p { declarations }

Class selectors
Class selectors apply to HTML elements that belong to a particular class. They dont pre-exist in the HTML specifications; you create them, giving enormous flexibility.You define

AdvAnced cSS
Just as there are different versions of HTML, there are also different versions of CSS. CSS 2 is the latest official release. CSS 2.1, which fixes a number of bugs in CSS 2 and adds some new features, is a working draft and requires further revision before final release. Work has begun on CSS 3, but it will be a while before its finalised. One feature introduced in CSS 2 is the Clip property for images, which creates a white border around the image, inside the content box. If we take the picture on the right, we could use the Clip property to crop it down to just the centre part of the chip. This is an extreme example, but it shows how the property works:

CSS syntax
CSS has a fairly simple syntax thats easy to follow. Each stylesheet is a list of rules, specifying which elements of the page you want the sheet to affect and what you want to do to them. Since CSS files are simply text files with a CSS extension, its possible to use Windows Notepad to create them. Its only really suitable for quick

The CSS clip property is a useful new addition to CSS.


to top, right, bottom and left. The values are the distance from the top left-hand corner of the image. The Clip property is supported by both Firefox 2 and Internet Explorer 7, although it will only work in IE if the rect values arent separated by commas. This is technically incorrect, but the only way to make it work with Microsofts browser.

img { position: absolute; clip: rect(230px 470px 390px 200px); }


Clip can only be used on absolutely positioned images. The rect value specifies how much of the image to display, with the four values corresponding

90 PC AUTHORITY March 2008 www.pcauthority.com.au

CSS | FEATURES

WAlkTHROUgH: USInG KOMPOZeR fOR HTML And cSS

KompoZer (www.kompozer.net) is an unofficial bug-fix release of the opensource Nvu a web editor that hasnt been updated in more than two years. Different versions are available for many operating systems.

Once you've downloaded and installed KompoZer, define a site. Click the "Edit sites" button in the Site Manager pane on the left and enter a site name, web address where the site will live and local directory to store your file.

Enter a heading and some body text into the web page pane on the right. Highlight your heading and select Heading 1 from the style list in the top left. Repeat for the body text, but select Paragraph.

Click the KaZcadeS button on the toolbar to launch the CSS editor. Click the button that looks like a paint palette in the top-left corner to create a new rule.

Select the style applied to all elements of type option and enter h1, then click Create Style rule. To change the body text, enter p instead

Click on the Text tab and enter #ffffff in the Color box, choose Bold for Font weight and Center for Alignment. On the Background tab, enter #990000 for Color and click OK. To adjust other values, click the KaZcadeS button again. www.pcauthority.com.au March 2008 PC AUTHORITY 91

FEATURES | CSS
the elements in the HTML page by using the class attribute. For example:
<p class=brightpink>.

Class selectors can either apply to all elements of a particular class or be restricted to a specific one. Theyre identified by preceding the name with a full stop:
.brightpink { color: fuchsia; } /*Applies to all HTML elements of the class brightpink*/ p.brightpink { color: fuchsia; } /*Only applies to p elements of the class brightpink*/

ID selectors
ID selectors are similar to class selectors, except all ID values within a document must be unique. For example, <p id=introduction> can only be used once in the HTML page. Theyre identified by preceding the name with a hash symbol:
#introduction { colour: green; }

Descendent selectors
Descendent selectors allow you to control what happens to elements that are contained within other elements. For example:
<h1>This is <em>very</em> important</ h1>

Here, the em element is within the h1 element. If you wanted to change the style of em within h1 and nowhere else, youd use a descendent selector. For example:
h1 em { color: white; }

elements such as <p> or <h1>. In these cases, you can use the div and span HTML elements. These have no meaning in themselves, but can be used as containers to identify areas of a document. In CSS terms, div is a block-level element, so should be used to specify areas covering more than one line, whereas span is an inline element, so should be used to identify sections within a single line. Blocklevel elements can contain both blocklevel and inline elements in addition to text, whereas inline elements can only contain other inline elements and text. By assigning ID or class attributes to div or span elements, they can be styled individually using the #id or .class selectors. An example using div and span elements would be:
<div id=footer> <p>All text copyright <span class=company-name>Brill Web Industries</span> 2007. All rights reserved.</p> <p>Created using a computer.</p> </div>

Our test page before CSS is applied.

border, which means the size of the box depends on how big the margin, border and padding are, as well as the actual content. See the screenshot below for an example. Boxes can contain other boxes, creating a hierarchy, with the browser window forming the top level. Boxes are either block level or inline, depending on whether the HTML elements that define them are block level or inline. By default, block-level boxes are positioned vertically from top to bottom, while inline boxes flow horizontally from left to right. By using CSS positioning, however, its possible to override the default behaviour and place boxes exactly where you want them. If we start with a basic page, with a header, a navigation menu and some body content, the HTML would look like:
<div id=header><h1>Header</h1></ div> <div id=menu><ul><li>Home</ li><li>About</li><li>Things</li></ul></div> <div id=body><p>Body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text body text</p></div>

Multiple selectors
If you want to apply the same effect to a number of elements, you can list them separated by commas rather than having to write identical rules for each element:
h1, em { color: purple; }

Pseudo classes
Pseudo classes refer to items that arent specific to an elements name, attributes or content. For example, browsers display visited links in a different colour to those that havent been clicked on. The link and visited pseudo classes are used to distinguish between them. Other pseudo classes are hover, active and focus. For example:
a:link {color: yellow; } a:visited {color: brown; }

This defines a block element that can be styled using the #footer selector and an area of text that can be styled using the .company-name selector.

The Box Model


So far, weve only looked at CSS rules that affect how the HTML is displayed, such as colour and font weight, but you can also control where elements appear on the page. Prior to CSS, layout was usually achieved using tables a practice that was generally complicated and messy to implement. To enable accurate positioning of items, CSS uses the Box Model, which defines all elements within the document as rectangular boxes. A box is made up of content, surrounded by padding, a border and a margin. Padding defines the space between the content and the border, while the margin defines the area outside the

The size of the CSS box is determined by the margin, border padding and finally its content.

Here, weve defined three blocks: the header, the menu that contains a list and the body. By default, the three blocks would be laid out vertically, starting with the header, followed by the menu, then the body text (see screenshot above). However, using CSS, we can place the menu and body in vertical columns. To do this, we use the float declaration, which specifies that blocks should be moved as far to one side of the screen as possible, and further blocks will flow around them. To achieve this in CSS, we need to use the following rule:

Arbitrary areas
With use of the correct selectors, its possible to define which elements of an HTML document you want to style to a high degree. However, sometimes youll find things you want to do that cant be achieved using normal HTML

92 PC AUTHORITY March 2008 www.pcauthority.com.au

CSS | FEATURES
absolute positioning. By using the following code, its possible to position text within the span element wherever you want:
<span id=absolute>positioned absolutely</span>

How to implement CSS in a web page


There are three ways to use CSS to style an HTML document: inline, internal and external. Inline code is added directly into an HTML page using the style attribute. Rather than creating a list of rules that match specific selectors, as weve been doing so far, youre adding the code to each individual item. So, to get a paragraph of fuchsia text using inline code, youd edit your HTML page:
<p style=color: fuchsia;>This text is fuchsia.</p>

The CSS code would be:


#absolute { position: absolute; top: 20px; left: 80px; }

#menu { float: left; width: 100px; }

Our test page with float positioning.

This will force the menu block to appear to the left of the body text rather than above it. Its important to define the width of the block when using the float property; otherwise, the result can be unpredictable. With the example above, any body text below the bottom of the menu block will flow underneath the menu (see screenshot above, left). If youd rather create distinct columns for the menu and body text (see screenshot above, right), its necessary to use the float property for the body block as well. For example:
#body { float: left; width: 200px; }

This places the top of the phrase positioned absolutely 20 pixels down from the top of the page and 80 pixels from the left. If you dont know exactly where you want an item to be, but just want it to be a certain distance from its normal placement, you can use relative positioning instead. For example:
This text is <span id=relative>relative</span> #relative { position: relative; top: 20px; left: 80px; }

Float provides a reasonable level of control over your layout, but you can go further and position items exactly where youd like them to be using

This positions the word relative 20 pixels down and 80 pixels to the right of where it would have originally appeared. One thing worth noting about absolute positioning is that its still relative to any containing element. In the first example above, the browser window is the containing element. If, however, it was inside a div element that was positioned 200 pixels down and 400 pixels from the left, the text would appear 220 pixels down and 480 pixels from the left.

While this approach works, it doesnt separate the design from the content and isnt much different from using font tags, which have been deprecated from HTML. If you use this approach, and decide later to change the text colour, youll need to go through each page, find every tag and change it manually. If you consider that a page could have many such tags, and a site many pages, it quickly becomes unmanageable. Using inline code is fine if you quickly want to see what a command does, but it isnt recommended for use throughout a document. Where it does become useful is if your pages are being generated programmatically, for instance through a PHP script, but its still best to separate as much CSS code as possible from the HTML elements. An internal stylesheet is used to specify the styling of an individual HTML page the code is added to the head section of the HTML document. The style tag is used for this purpose, so to add CSS to a document youd use:
<head> <style type=text/css>

WILL IT WORK In eveRY BROWSeR?


One of the original problems with HTML was that different browsers supported different features, making it difficult to produce pages that displayed properly in all of them. CSS, in theory, helps solve this problem; however, youll still run into problems when using some features. This is more of a problem with older browser versions, but can still crop up with the latest releases. For example, releases of Internet Explorer prior to version 6 calculated box widths incorrectly a problem that became known as the box model bug. According to the standards, if the size of a block- level element is specified, it should only apply to the content, with padding, border and margin added afterwards. IE5 includes the padding, border and margin in the size, which results in a box smaller than it should be. Provided IE6 or 7 isnt running in Quirks mode, which is provided for backwards compatibility (and is triggered by badly formed HTML), this is no longer a problem. CSS support in the latest browser versions is much improved, but you can still run into items you cant use in both Firefox and IE. IE, for example, doesnt support the :before pseudo class or Content property, which is used to insert content at the beginning of a specified element. So the following code would have different results in each browser:

h1:before { content: Chapter: ; } <h1>Everything you wanted to know about CSS</h1>


In Firefox, the header would be displayed as Chapter: Everything you wanted to know about CSS, with the Chapter: text before the title. IE, on the other hand, will only display the title

CSS is not without its compatibility problems.


on its own (see above). You can find a list of which CSS elements are supported by which browsers at www.webdevout. net/browser-support-css

www.pcauthority.com.au March 2008 PC AUTHORITY 93

CSS | FEATURES
p{ color: fuchsia; text-align: right; } h1 em { color: red; } </style> </head>

the font and weight by using the fontweight and font-family properties:
#menu ul li a { padding: 0.2em 1em; text-decoration: none; font-weight: bold; font-family: Arial,Helvetica,sans-serif; }

This has the advantage that if you decide to change how one element is displayed, you only have to change it in one place. So to change all the paragraph text from fuchsia to green, you only need to modify one line of code. However, if you have multiple pages on the same site, youll still need to change each one to get the same effect. An external stylesheet can be applied to multiple pages, so its the best approach to use when creating a site that involves many pages with a common design. In this case, the stylesheet information is stored in a separate file with a CSS extension and linked to in the head section of the HTML document. So, if your stylesheet was called styles.css, youd link to it as follows in the head section of your HTML page:
<link rel=stylesheet href=styles. css type=text/css>

case, they arent. Although the bullet point isnt visible, the list is still indented. This can be corrected by setting the padding and margin properties to zero (see bottom screenshot above). For example:
#menu ul { margin: 0; padding: 0; list-style-type: none; }

The first stages of producing a modern-looking menu.

By specifying a list of values for fontfamily if the viewer doesnt have the first font installed, the browser will use the first one it recognises. Modifying the colour of the background will make the menu stand out more. This can be done using the Background-color property and Color property:
#menu ul li a { padding: 0.2em 1em; text-decoration: none; font-weight: bold; font-family: Arial,Helvetica,sans-serif; color: #ffffff; background-color: #cc0000; }

The menu is displayed vertically, because lists are a block-level element. However, we can override this using the Display property of the li element:
#menu ul li { display: inline; }

The styles.css document would contain the same rules that were used on the internal stylesheet, but now it can be applied to every page that includes the link tag. Now you can update styles across every single page on the site just by modifying a single file.

The Color property applies to the text, which when set to white (#ffffff) is easier to see against the red background. Finally, by using the hover pseudo class, its possible to change the background colour when the mouse is placed over the menu, in this case making it dark red (see bottom screenshot below):
#menu ul li a:hover { color: #ffffff; background-color: #990000; }

Putting it all together


By building up styles, you can dramatically alter the layout and design of the HTML in your document. Here is the basic code for a menu:
<div id=menu><ul><li><a href=home>Home</a></li> <li><a href=news>News</a></li> <li><a href=reviews>Reviews</a></li> <li><a href=features>Features</a></ li></ul></div>

The menu now displays horizontally, but the items are very close together. In order to space them out, we can use the padding property of the a (anchor) element, since the menu items are links. We can also remove the underline that links have by default with the textdecoration property (see top screenshot below):
#menu ul li a { padding: 0.2em 1em; text-decoration: none; }

NEXT MONTH
Add Web 2.0 interactive and animated elements to your site.

By modifying just 12 properties of four items in the document, its possible to create a vastly different design. And, as the design is separate from the content, if you want to change it at a later date, you need only modify the stylesheet rather than having to tinker with all the website files.

It defines a block element called menu, which contains a list of four items that are links. By default, it appears quite basic (see top screenshot above). The first thing we can do is remove the bullet item by using the following code:
#menu ul { list-style-type: none; }

By using the selector #menu ul, the rule will only apply to unordered list (ul) elements within the menu block. The list style-type property defines how the bullet points are displayed in this

The padding property takes up to four values, which correspond to the top, right, bottom and left edges in that order, effectively clockwise around the box. However, if you omit a value, it will take the same number as its opposite, so if you leave off the final left value, left will be the same as right. In this case, only two values (top and right) are specified, so the left will be 1em and the bottom 0.2em. Sizes can be specified in a number of units, such as pixels or percentages. Em is a unit related to the current font size, so by specifying the padding in ems, if the font size increases so will the padding proportionally. To make the menu items stand out from normal body text, you can change

The menu items are now inlined...

...and fully styled, all without changing the HTML. www.pcauthority.com.au March 2008 PC AUTHORITY 95

You might also like