CSS

Page 1


Preface If you are being dragged kicking and screaming into the world of cascading style sheets, take comfort in the fact that you are not alone. In the two years since I first issued “Introduction to CSS” from my site, quite a bit has changed regarding how web sites are designed and built. XHTML is now replacing HTML as the language of the web; table-based templates are quickly being replaced by dazzling CSSpositioned ones; new browsers have been released and are designed to read CSS efficiently and correctly. It’s a brave, new world. Why CSS? This story should sum it up nicely. You are a web designer and have just completed a 40-page site for your client. He is thrilled with your work but wants to make a few minor changes. Instead of using Arial as the default font, he would like for you to change it to Verdana. It’s a simple request. You look at your HTML coding and see that there are font markup tags that specify the font as Arial. You have to change each and every <font> tag. At approximately 100 tags per page times the 40 pages, you have to change about 4,000 items. Doing them one at a time is now a major headache and will take hours. However, if you had defined your font using CSS (rather than using deprecated font tags), you would make the change on only one page and the changes would be made automatically on every page in the site. You’ve just cut the job down from hours to only a few seconds. This guide is designed to teach you the basics of CSS. It cannot cover all topics or all situations. This will give you a great start on learning about style sheets and how they work, and will give you a springboard to continue learning. While covering valid CSS, remember that nothing is guaranteed to work in all browsers all of the time. Don’t obsess over pixel perfection across the different browsers. If something doesn’t work, search for online resources that discuss possible alternatives. Rather than searching for CSS “hacks” (like hammering a square peg into a round hole), you may need to rethink your design or the approach you are taking. Most importantly, relax and have fun. The terminology is probably foreign to you, but the concepts are fairly simple. Take it one step at a time and don’t try to rush through everything in this guide in one sitting. Print out this guide and take it one step at a time. There’s a lot of information to absorb and put to use.

Page 2 RTBWizards.com © 2007 | All Rights Reserved


Lesson 1: The Basics We all have to start somewhere and the best place to begin is with the basics. All subsequent lessons will be built on this foundation. CSS isn’t difficult to learn and it’s a lot of fun. CSS is the acronym for Cascading Style Sheets. CSS is an extension to basic HTML that allows you to style your web pages. Each browser has a set of parameters for how it reads paragraphs, headings, tables, etc., and then renders it in your browsers. Each of these HTML tags can be “defined” so that you tell the browser how to display it. With this in mind, you can think of your CSS file as a sort of dictionary with a clear definition of how each item is displayed on the screen. While we can’t cover every aspect of CSS in these lessons, this guide will cover the basics plus you will be given resources where you can learn more.

Learning the rules It’s all in the details and rules are important. With CSS, you can set up rules (or definitions) to tell specific HTML tags how to display content, or you can create generic rules and apply them to tags when you need them. There are THREE types of rules: HTML selector, Class, and ID HTML Selector: An HTML selector redefines an HTML tag. By redefining an HTML tag you change the way that tag displays its content. All tags will keep their default behavior unless they are changed. Below is an example of a redefined paragraph tag: p {line-height: 14px;} To apply a redefined HTML tag, simply use it in your document. Using the example above, simply adding a paragraph tag to a web document will apply all of the tag’s default properties as well as the line-height attribute added in your style definition example. All instances of a paragraph tag are automatically affected when declared in an embedded or external style sheet. You can define a style for multiple tags at one time. For example, if you want all Heading tags to be the same color, you simply add selectors to the selector section, separated by commas as follows: h1, h2, h3 {color: #c00000;} If you want additional properties for only one of the tags in the group, you can define it separately: h1, h2, h3 {color: #c00000;} h2 {font-family: Verdana;} Class: A class is a rule that can be applied to an HTML tag. You can give a class any name you want with the exception of reserved words (listed in the Resources Section.) Here’s an example of a CSS class: .myclass {font: bold 14px Verdana;}

Page 3 RTBWizards.com © 2007 | All Rights Reserved


A class can only be set in an embedded or external style sheet, and cannot be used inline. Classes have an advantage in that you can create a number of different classes and apply them to different paragraphs, headings, divs, etc. ID: ID rules are similar to a class but they can only be applied once on a page to a particular HTML tag. IDs are commonly used in CSS positioned layouts since items like a header or footer are only going to appear once on a page. An ID rule looks like the following: #myid { background-color: #ffffff; height: 40px; padding: 10px 20px;}

Parts of a CSS rule There are THREE parts to a CSS rule: selectors, properties, and values The selector can be an HTML selector, a class or an ID, as discussed above. Properties and values are contained within curly braces following the selector. The properties and values within the braces are definitions. A property is separated from its value using a colon and you cannot specify a property without also including a value. You can assign multiple definitions for a selector and a semicolon separates each definition. Below is the syntax for a CSS rule: selector {property: value;} Note that not all CSS definitions can be applied to all HTML tags. Much depends on the nature of the tag. While this does seem a bit confusing at first, in these lessons we will learn which definitions can be applied to the various HTML tags.

CSS rule placement You can apply CSS rules in THREE different places: inline, embedded, and external Inline: An inline style is the style that is attached to one specific element. There may be times when you only need a style definition that you don’t plan to use anywhere else in your document. The syntax for an inline style rule different from that of embedded or external rules. The syntax looks like this: <h1 style=”color: #c00000”> . . . </h1> Inline styles have both advantages and disadvantages. One advantage would be if you want to override an already defined style. A disadvantage is having a lot of inline styles adding bulk to your HTML coding. Embedded: An embedded style is the style attached to one specific web page. Embedded rules are placed within the head section of an HTML document and the rules affect the entire page. The style rules are placed in the <head> of your document between opening and closing <style> tags.

Page 4 RTBWizards.com © 2007 | All Rights Reserved


External: An external style sheet is a file containing style information that can be linked with any number of pages. This is a very convenient way of formatting the entire site as well as restyling it by editing just one file. External style sheets are text documents with .css file extensions. The syntax for the style rules in an external style sheet is the same as that in an embedded style sheet except without the opening and closing <style> tags. The syntax for linking to an external style sheet is as follows: <link rel="stylesheet" type="text/css" href="style.css">

Creating your own inline tags Sometimes you’ll want to apply a style to a tag that has no pre-existing conditions. This is where you’ll use the <span> tag. The span tag has no inherited properties and serves as a blank slate for creating your own inline tag. You can apply a class rule to a span tag and the tag will take on only the properties assigned to the class. For example, let’s say you create a highlight class as follows: .highlight {background-color: #ffff80;} The class is then applied to a few words within a paragraph as follows: <p>A paragraph to which <span class=”highlight”>I apply a highlight</span> to words I want to emphasize.</p> This is the result: A paragraph to which I apply a highlight to words I want to emphasize.

Creating your own block-level tags While a <span> tag allows you to apply a style to a tag within another set of tags, the <div> is used to create a “block” of text that separates itself from other content within a document. Unlike the <span> tag, the <div> tag has the inherited properties of adding a break both before an after the tag. This is what creates the block. You can apply a class or ID to a <div> just like any other tag. The exercises in this guide use DIVs rather than tables to create blocks that hold the web page content.

Inheriting properties from a parent HTML documents are structured hierarchically. Except for the <body> tag, HTML tags have a parent tag. For example, a list item tag <li> will inherit the style you assign to the parent unordered list <ul> tag. Another example is the <table> tag. It is the parent for the <tr> and <td> tags nested inside of the table. Not all properties are inherited. One such property is the background. However, since its initial value is transparent the background of the parent element will shine through by default unless it is explicitly set. Another example is the text-indent property that indents the first line of a paragraph. It would not apply to an inline tag such as the <span> tag discussed earlier.

Page 5 RTBWizards.com © 2007 | All Rights Reserved


Contextual selectors A contextual selector is a selector that addresses a specific occurrence of an element. It is more than one selector separated by a space. Only when the pattern matches exactly will the style apply. Contextual selectors are separated by a single space and do not use a comma.

Lesson 2: Backgrounds, Colors & Fonts In this lesson we are going to incorporate background, color and font controls into our style sheet. To begin, we need to discuss “shorthand” properties. This is a way to shorten your style sheet definitions from multiple lines into a shorter one-line version.

Using shorthand properties Some properties are made up of several values. For example font-weight, font-variant, fontsize and font-family all refer to the font. To reduce the size of style sheets and also save some keystrokes as well as bandwidth they can all be specified as one shorthand property. For example the font properties listed below: h1 { font-size: 18px; font-weight: bold; font-family: Verdana;} …can also be written together as follows: h1 {font: 18px bold Verdana;} Shorthand properties exist for many items such as background, font, border and margin controls; however, it is important that the values be listed in a specific order. Each shorthand property, in the specific order in which the attributes must be listed, will be discussed as we work through these lessons.

Background properties There are five background properties that can be used to set the background of an element. They are listed in order as follows: background-color background-image background-repeat background-position background-attachment Background-color: This specifies the background color for an area such as a page background, a table cell, a div block, etc. You can use a hex value (#ffffff), a named color (blue), or an RGB value written as RGB(00,00,00), or use a value of transparent. You can apply a background color to an entire page by redefining the body tag or to other elements where you want a background color to appear. The example below sets a white background color within the body tag using a hex color value: body {background-color: #ffffff;} Page 6 RTBWizards.com © 2007 | All Rights Reserved


Background-image: This setting allows you to set an image as a background. There are only two settings for the attribute: none and url. Using url requires that you specify the file location of your image as shown below: body {background-image: url(‘filename.jpg’);} If your image is contained in a folder rater than in the root web, you must include the full path in the url reference so that the file path is correct: body {background-image: url(‘foldername/filename.jpg’);} Setting the value to none is normally used when you want to remove an image that was previously set. Background-repeat: The default setting for the background-repeat value creates a tiled effect so that your image repeats both horizontally and vertically to fill the screen. The settings include repeat, no-repeat, repeat-x, and repeat-y. No-repeat causes the image to appear only once at the position you set. Repeat-x makes the image tile horizontally while repeat-y makes it tile vertically. Background-position: This property sets the background position of the image relative to the element. Position values are as follows: top left top center top right center left center center center right bottom left bottom center bottom right A style rule using the background-position property would look like this: body { background-image: url(‘folder/file.jpg’); background-position: top right; } Background-attachment: Values for this property are scroll or fixed. You can choose whether or not to have your background remain in a fixed position when the page scrolls. Fixed instructs the browser not to scroll the background with the rest of the elements. Scroll is the default setting and instructs the background to scroll along with the other page elements.

Color controls Color controls refer to the text color. The attribute accepts the name of a color, a hex value, or an RGB color value. A color statement that sets all of the text on a web page to black would look like the following: body {color: #000000;}

Page 7 RTBWizards.com © 2007 | All Rights Reserved


Font controls No other style will have as much impact on your site visitors than your font controls. The appropriate fonts, colors, and sizes have a lot of impact on how user-friendly your site is to others. Keep in mind that a web page is not the same as a printed page in a magazine. There are five attributes that define fonts in a web document. They are listed in order as follows: font-style font-variant font-weight font-size font-family Font-style: There are three settings for the font-style attribute: normal, italic, and oblique. Normal refers to standard type. Italic and oblique will render the text as italicized. In the shorthand property, you do not have to specify a font-style. The default is normal. Font-variant: This property has two values: small-caps and normal. Small-caps displays the text in capital letters with the first letter being normal sized but other letters smaller than normal. The small-caps setting should be reserved for titles or other specific text because it may be difficult to read at smaller sizes. In the shorthand property you do not have to specify a font-variant. The default is normal. Font-weight: Font-weight refers to letter thickness. You are probably familiar with the bold setting that makes the text darker than normal. A font-weight of bolder makes the text even darker. A setting of lighter makes the text less bold than the bold setting. You can also specify a value range from 100 (the lightest) to 900 (the thickest), in increments of 100. Font-size: Font-size settings can be an exact size such as pixels, a percentage relative to the default setting, or keywords such as x-small, small, medium, large, x-large, and xx-large. Larger and smaller keywords are set relative to the size of the parent element. Font-family: Font-family sets the actual name of the font you are using such as Verdana. Remember that CSS will only display a font if it is installed on your visitor’s computer. In a font-family declaration, you can specify more than one font setting. If the first font in the list isn’t available on the visitor’s computer, the browser will select the next font listed. It is recommended you use a generic font type such as serif or sans-serif as the last font. Generic fonts include serif, sans-serif, cursive, fantasy, and monospace. Cursive and fantasy are not recognized in most browsers. Separate font names with commas. An example of a font-family rule is as follows: h1 {font-family: Verdana, Arial, Helvetica, sans-serif;} Fonts that have spaces in their names, such as MS Comic Sans, must be enclosed in quotation marks.

Lesson 3: Text While the last section discussed the important of font controls, the text controls are also important for the readability of your web pages.

Page 8 RTBWizards.com © 2007 | All Rights Reserved


Text Controls Text controls do not have shorthand properties, but there are a lot of properties you can use to control the look of your text. Text-align: The text-align property sets the horizontal alignment of your text on the screen. Your value choices are left, right, center, or justify. Left orients the text to the left, right orients the text to the right, and center orients the text to the center of an area. Justify aligns the text so the left and right edges are aligned. An example of the text-align rule looks like the following: .myclass {text-align: left;} Text-indent: The text-indent property will indent the first line of a paragraph. The value can be either a fixed length value such as 20px or it can be set as a percentage such as 10%. A text-align rule would look something like this: .indent {text-indent: 20px;} Caution: The text-indent value can also accept a negative length value in order to create a hanging indent. An example of this would be .indent {text-indent: -20px;}. There must, however, be enough padding to accommodate it. If your containing block has a padding of 10px, you cannot set a negative value to more than 10px. Note that not all browsers will display a hanging indent correctly. Text-transform: The text-transform property changes text from lowercase to uppercase. It can also change text from uppercase to lowercase. Text-transform values are capitalize, uppercase, lowercase, and none. An example of a text-transform rule would look like this: h1 {text-transform: uppercase;} Letter-spacing: The letter-spacing property sets the amount of spacing between letters. It’s a great way to add a bit of pizzazz to things like headings or small amounts of text. While a little bit of spacing can add a great look, remember that a little goes a long way and can sometimes make text more difficult to read. The default for this property is “none”, so if you want to add a bit of spacing you can specify the length in ems or pixels. An example of a letter-spacing rule would look like this: .expanded {letter-spacing: 3px;} Line-height: The line-height property controls the amount of spacing between each line of text. The value can be set as a number or length, as a percentage, or using the default of none. For example, a number of 2 would set the spacing to double space. A value of 20px would set twenty pixels of space between each line. A percentage value calculates the height relative to the font size. An example of a line-height rule would look like this: .tall {line-height: 20px;} The line-height value can also be used within a font shorthand property. It needs to be placed after the font size value and is separated by a forward slash with no space added. An example looks like this:

Page 9 RTBWizards.com © 2007 | All Rights Reserved


p {font: 12px/20px Verdana, Arial, sans-serif;} Text-decoration: The text-decoration property has five values: underline, overline, linethrough, blink, and none. An example would look like: h1 {text-decoration: underline;} The underline value adds an underline to a word or group of words. Be aware that the underline is most commonly used to identify hyperlinks. Use caution if you wish to underline words that are not hyperlinks because it can confuse visitors who may expect the results to be an actual link. The overline value is most commonly used along with the underline value and will add a line above your words. It is especially useful to add a bit of emphasis to an anchor tag as in the example below: a:link {text-decoration: underline;} a:visited {text-decoration: underline;} a:hover {text-decoration: underline overline;} a:active {text-decoration: none;} In this example of styling hyperlinks the normal link is underlined, the visited link is underlined, the hover link has both an underline and an overline, and the active link is not underlined. Because hyperlinks are underlined by default, in order to not have an underline for the active link, the value of none must be specified. The line-through value will draw a line through the word or group of words. You have probably seen this on catalog pages to show the difference between a regular price and a sales price as in the example below: For example: $12.95 $10.95 The blink value is not supported in all browsers and is rarely used.

Lesson 4: Margins, Borders & Padding This section discusses controls for borders, margins and padding. First we start with the box model. Below is an example of a box with each different color area showing the different regions that can be formatted.

Each box model element has four sides and is specified in order going clockwise: top, right, bottom, and left. Every box element can have a width and height defined. Page 10 RTBWizards.com Š 2007 | All Rights Reserved


Width and height properties accept a length value, a percentage value, or auto (which leaves the dimensions up to the browser). An example is as follows: .myarea { width: 300px; height: 100px;}

Margin controls Margins define the space surrounding an element. In the example shown above, the margin is the gray area. You can set each margin individually as shown in the example below: .myclass { margin-top: 20px; margin-right: 30px; margin-bottom: 20px; margin-left: 10px;} You can also use the margin shorthand property. In the example below, a 20 pixel margin will be added to all four sides: .myclass {margin: 20px;} If you use two values, the first value applies to the top and bottom and the second value applies to the right and left sides. An example would look like the following: .myclass {margin: 20px 10px;} If you wish to use all four values, you can apply each value separately as follows: .myclass {margin: 20px 10px 20px 30px;} Note that there are no commas, only a single space separates each value.

Border controls Border controls enable you to add a visible border around an area. You can specify the border’s style, width, color, and you can set each individual side of an element. Using the border shorthand properties, the attributes are listed in order as follows: border-width border-style border-color A shorthand property rule might look something like this, which applies a 1 pixel solid dark gray border around any element with the .myclass rule applied: .myclass {border: 1px solid #666666;}

Page 11 RTBWizards.com Š 2007 | All Rights Reserved


Border-width: The border-width property accepts a length value such as 1px(0 prevents a border from appearing) or a relative-size keyword such as thin, medium, or thick. Border-style: The border-style attribute refers to the type of border such as solid or dashed. Note that not all values are recognized in all browsers. If a browser does not recognize a value, it will usually either be ignored or will display as a solid border. The different values are: none, dotted, dashed, solid, double, groove, ridge, inset, outset. Border-color: The border-color property accepts a value in either hex or RGB. It will also accept a color name, but can have unexpected results. It is best to use either a hex value or an RGB value. Each border has four separate sides and you can define each side individually with the following properties: border-top border-right border-bottom border-left

Padding controls Padding sets the amount of space between the border and the element. Padding is shown in gold in the image shown at the beginning of this section. This property can use a value set as a percentage or a width specified in pixels or ems. A padding shorthand property setting all four sides differently would look like this: .myclass {padding: 10% 10px 5px .5em;} You can also set all four sides as follows with the values assigned in the same order as for margins and borders: padding-top padding-right padding-bottom padding-left

Float The float property is most commonly applied to images, tables, and divs and accepts the values of right, left, or none. If you have a need to display your images in various ways, you can define a class and apply the class to a single image. In the example below, the image would be positioned to the left of the containing area, have a top and bottom margin of 5 pixels, a left and right margin of 10 pixels, and have a one pixel black border on all four sides of the image: .imageleft { margin: 5px 10px; border: 1px solid #000000; float: left;}

Page 12 RTBWizards.com Š 2007 | All Rights Reserved


Lesson 5: Lists This section will discuss the various ways to style list items. There are three different types of lists: Unordered lists which typically display some type of bullet. Ordered lists which follow an alpha or numeric sequence. Definition lists which consist of a term and its definition.

Unordered lists The list properties allow you to control the appearance of your lists by choosing a “marker” (such as a disc, circle, square, etc.) or by setting an image. You can also then determine where the marker is placed. There are three properties used to control the appearance of an unordered list: list-style-image list-style-type list-style-position List style properties can be defined in an external or embedded style sheet or they can be defined inline. To obtain different bullets for different items, an inline style might work best for you. To define different bullets for different list items, you would want to define classes and assign each class to the <li> tag you want to receive each defined bullet. If you do not use contextual selectors, however, you might create problems if you try and define decimal, roman or alphanumeric bullets in the same list. An example of a contextual selector rule applied to a list item <li> inside of an unordered list <ul> using the shorthand property would like the following example: ul li {list-style: url(‘foldername/image.gif’) disc inside ;} List-style-image: The list-style-image property lets you use a small graphic image in place of a bullet in a list. A typical rule would look like this: ul li {list-style-image: url(‘foldername/bullet.gif’);} Because list items can have up to three levels of bullets, you can define a different bullet for each level. For second and third level bullets, your style coding would look similar to this: ul li li {list-style-image: url(‘foldername/bullet2.gif’);} ul li li li {list-style-image: url(‘foldername/bullet3.gif’);} List-style-type: The list-style-type property controls the type of bullet used for list items. The possible values are disk, circle, square, and none. You can also define a different type of bullet for all three levels as follows: ul li {list-style-type: disc;} ul li li {list-style-type: circle;} ul li li li {list-style-type: square; }

Page 13 RTBWizards.com © 2007 | All Rights Reserved


List-style-position: The list-style-position property controls the alignment of text with respect to the list item bullet. The two possible values are inside or outside. Inside aligns subsequent lines of text with the bullet. An outside value causes subsequent lines of wrapped text to ine up with the first letter in the first line of text.

Ordered lists If you have ever had to do an outline for a school paper, you are already familiar with ordered lists. These follow and numerical and/or alphabetic sequence such as decimal (1, 2, 3), lower roman (i, ii, iii), upper roman (I, II, III), and upper alpha (A, B, C). Ordered lists also use the list-style-type: ol li {list-style-type: upper-roman;} As with unordered lists, ordered lists can also be defined for up to three levels: ol li {list-style-type: upper-roman;} ol li li {list-style-type: upper-alpha;} ol li li li {list-style-type: decimal;}

Definition lists A definition list consists of three HTML parts: the container <dl>, the definition term <dt>, and the definition description <dd>. All three parts can be styled, but only the definition description can contain block level items like paragraph <p> tags. If you are unfamiliar with definition lists, consider the advantages of styling your FAQ page. Typically you have a question (the definition term) followed by an answer (the definition description). The following is an example: dt { font-weight: bold; letter-spacing: 2px; color: #bf2c22; padding: 15px 0;} dd {

color: #5455d4;}

Lesson 6: Hyperlinks Since the very beginning of HTML, hyperlinks have been a vital part of the way we navigate through the web. Not surprisingly, one of the most requested examples of CSS code is how to “style” links (the anchor <a> tag). Webmasters have known from the start that hyperlinks can seem complicated because they can have various configurations depending upon whether that have been clicked or not, if they are being clicked, or if the cursor is over the hyperlink. To handle these numerous configurations (or declarations), the CSS “pseudo-class” was developed. The syntax for a pseudo-class is as follows:

Page 14 RTBWizards.com © 2007 | All Rights Reserved


selector:pseudo-class {property: value}

Anatomy of a hyperlink A hyperlink uses the anchor <a> tag. The anchor can have four different states: link, visited, hover, and active. (There is actually a fifth state named focus, but it is not supported in all browsers so will not be discussed here.) Each state can define how a hyperlink looks at a particular time. If you wanted every link state to be the same, you would not have to add the pseudo-class and would style the link as follows: a {color: #c00000;} If you wanted each link state to be the same except for the hover link, you would add the pseudo-class to the hover link rule. An example is as follows: a {color: #c00000;} a:hover {color: #0000c0;} To set each link state differently, you add the pseudo-class to each state as follows: a:link { color: #c00000; text-decoration: underline; font-weight: bold;} a:visited { color: #c0c0c0; text-decoration: none; font-weight: bold;} a:hover { color: #0000c0; text-decoration: underline; font-weight: bold;} a:active { color: #c00000; text-decoration: none; font-weight: bold;} Note that links must be defined in order: link, visited, hover and active. An easy way to remember the order is LoVe HAte.

Multiple link styles on the same page In the real world of web design, you will probably have a page with different color blocks. For example, your main text area may be white, but a sidebar area may be blue while the footer area may be black. Rather than trying to come up with a color scheme for links that would work well again all three different color blocks (a difficult, if not impossible, task), we can specify link colors for each separate area using contextual selectors (discussed in Lesson 1 ). Page 15 RTBWizards.com Š 2007 | All Rights Reserved


Rather than styling just the anchor <a> and pseudo-class, we can style links to be dependent on a certain outer class that surrounds the area where we would like for our link style to be different. For example: #sidebar a:link { color: #c00000; text-decoration: none;} #sidebar a:visited { color: #c0c0c0; text-decoration: none;} #sidebar a:hover { color: #0000c0; text-decoration: underline;} #sidebar a:active { color: #c00000; text-decoration: none;} #footer a:link { color: # #ff4040; text-decoration: none;} #footer a:visited { color: # #e0e0e0; text-decoration: none;} #footer a:hover { color: #4040ff; text-decoration: underline;} #footer a:active { color: #ff4040; text-decoration: none;}

Lesson 7: Forms HTML forms are probably one of the ugliest things to hit the web. The are generally boring and utilitarian and don’t offer much in the way of good looks. But with CSS, that can change. Combining CSS with the more advanced form tags can get you some really nice looking forms. Chances are you will have at least one form on your web site. It may be a simple form where your visitors sign up for a newsletter or it may be a more complex form such as a customer help or feedback form. Since forms are composed of common HTML tags, it is possible to change their default appearances using CSS. Some common form tags are: <form>, <input>, <select>, and <textarea>.

Styling forms Below is a typical form that has no styling applied. The screenshot shows how the form renders in IE6 Windows XP:

Page 16 RTBWizards.com Š 2007 | All Rights Reserved


Here’s the code behind it: <form method="POST" action="#"> <label for="name">Name: </label> <input type="text" name="name" /><br /> <label for="email">Email: </label> <input type="text" name="email" /><br /> <label for="choice">Select One: </label> <select name="question"> <option>Presales Question</option> <option>Support Question</option> </select><br /> <label for="comments">Comments: </label> <textarea rows="4" name="comments"></textarea><br /> <input type="submit" value="Submit" /> <input type="reset" value="Reset" /> </form> In the code example above, the <label> tag is used for accessibility reasons. It is important for your visitors to know what a particular field is for, especially those with screen readers. A bonus is that the label tag can be styled so you no longer have to place your form into a table to keep items aligned. By styling the <label> tag as follows: label { width: 120px; float: left; text-align: right; margin: 0 10px 10px 0; clear: both;} Our form now looks like this:

Page 17 RTBWizards.com Š 2007 | All Rights Reserved


In the form example above, you can see that the form contains several different <input> tags. To separate the style of an input text field from an input button field, you can create contextual selectors and then apply the class to the individual input fields as needed. You can style input tags as shown below: input.text { color: #000000; background-color: #b6c8da; padding: 2px; border: 1px solid #606060; width: 200px;} input.btnsubmit { font: bold 14px Verdana; color: #ffffff; background-color: #6090b0; border: 1px solid #808080; padding: 5px; margin: 10px 10px 0 130px;} input.btnreset { font: bold 14px Verdana; color: #ffffff; background-color: #6090b0; border: 1px solid #808080; padding: 5px; margin: 10px 10px 0 0;} Below is an example of the styled form and the HTML coding:

Page 18 RTBWizards.com Š 2007 | All Rights Reserved


<form method="POST" action="#"> <label for="name">Name: </label> <input type="text" name="name" class="text" /><br /> <label for="email">Email: </label> <input type="text" name="email" class="text" /><br /> <label for="choice">Select One: </label> <select name="question"> <option>Presales Question</option> <option>Support Question</option> </select><br /> <label for="comments">Comments: </label> <textarea rows="4" name="comments"></textarea><br /> <input type="submit" value="Submit" class="btnsubmit" /> <input type="reset" value="Reset" class="btnreset" /> </form> You can also style the <select> and <textarea> tags as shown in the example below: select { color: #000000; background-color: #b6c8da; padding: 2px; border: 1px solid #606060; width: 200px;} textarea { color: #000000; background-color: #b6c8da; padding: 2px; border: 1px solid #606060; width: 200px;} By adding the following styles, you form now looks like the following:

Page 19 RTBWizards.com Š 2007 | All Rights Reserved


You can also replace the form’s usual submit button with an image. Warning: you cannot have both a submit button image and a reset button image. Using an image will cause the reset button to also submit the form in Internet Explorer. If your form is small, you may decide that a reset button is not necessary. You can replace the submit portion of your form: From this: <input type="submit" value="Submit" class="btnsubmit" /> <input type="reset" value="Reset" class="btnreset" /> To this: <input type="image" src="button-submit.jpg" value="Submit" alt="click to submit form" class="btnsubmit" /> Adjust your CSS styles as follows: From this: input.btnsubmit { font: bold 14px Verdana; color: #ffffff; background-color: #6090b0; border: 1px solid #808080; padding: 5px; margin: 10px 10px 0 130px;} To this: input.btnsubmit { margin: 10px 10px 0 130px;} NOTE: Since the reset styling is not being used, you may delete it. Your form will now look like the sample below:

Page 20 RTBWizards.com Š 2007 | All Rights Reserved


Fieldsets and legends You can get a very slick look on your forms by adding the <fieldset> and <legend> tags.

Place the opening <fieldset> tag before your <form> tag. Placing the closing fieldset tag </fieldset> tag after your closing form tag </form>. This wraps your form in a box. In your style, you can set the width, padding, border, and more. The rule for the fieldset tag might look like the following: fieldset { width: 375px; border: 3px double #c0c0c0; padding: 20px 10px 10px 10px; margin: 0;} After your opening <fieldset> tag, you can add the <legend> tag and type in the wording that will appear at the top of the form box. Your coding would look like this: <fieldset> <legend>Customer Form:</legend> <form method="POST" action="#"> ... </form> </fieldset> Page 21 RTBWizards.com Š 2007 | All Rights Reserved


You can style your <legend> tag and set the font size, color, etc. Your CSS rule would look something like this: legend { color: #454a77; text-transform: uppercase; font-weight: bold; padding: 0 5px; letter-spacing: 2px; margin: 0;}

Lesson 8: The Doctype Declaration Every HTML document should have a document type declaration. The “doctype” begins the web page and tells the browser how to interpret the coding on the page. It also tells a validator which version of HTML to use in checking the document’s syntax. When you use a CSS file, omitting the document type will throw the browser into “quirks” mode and can give you unpredictable results. Since CSS is designed to tell the browser how to display the content, why make the browser guess? Add a doctype! While there are a variety of document types from which to choose, chances are you will want to select from one of four options:

HTML 4.0 Strict HTML 4.0 Strict is a trimmed down version of HTML 4.0 that emphasizes structure over presentation. Deprecated elements and attributes, frames, and link targets are not allowed. By writing to HTML 4.0 strict, you can achieve accessible, structurally rich documents that easily adapt to style sheets and different browsing situations. The document type declaration for HTML 4.0 Strict is: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

HTML 4.0 Transitional HTML 4.0 Transitional includes all elements and attributes of HTML 4.0 Strict, but allows presentational attributes, some deprecated elements, and link targets. The document type declaration for HTML 4.0 Transitional is: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

XHTML 1.0 Strict Most web sites that use CSS for positioning elements will use XHTML rather than HTML coding. The W3C (World Wide Web Consortium) currently recommends using XHTML instead. This hybrid language looks and works much like HTML but is based on XML, the web’s “super” markup language. XHTML requires a more “logical” document structure. XHTML 1.0 Strict is an XML version of HTML 4 Strict and is written as follows: Page 22 RTBWizards.com © 2007 | All Rights Reserved


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> It is also recommended that you include the “namespace” information in your opening <html> tag.

XHTML 1.0 Transitional XHTML 1.0 Transitional is an XML version of HTML 4 Transitional and is written as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> It is also recommended that you include the “namespace” information in your opening <html> tag.

Lesson 9: XHTML Rules As stated above, XHTML requires a more “logical” document structure. When writing your text for the web, think about logically setting up your content. <h1>Your Main Topic Heading</h1> <p>Content that follows your main topic.</p> <h2>Second Topic Heading</h2> <p>Content that follows the second topic heading</p> You want to avoid using deprecated tags to add text to simulate the logical order like <font size="7">Your large text</font>. If you’re concerned about the appearance of your web pages, remember that Cascading Style Sheets (CSS) separate presentation from structure, allowing you to style any element as you wish.

Rules of XHTML Moving from traditional HTML to XHTML 1.0 Transitional is easy, as long as you work carefully and observe the following rules: Open with the proper DOCTYPE & Namespace: XHTML documents must begin with tags that tell the browser how to interpret them. We begin each template page with the following that appears before the opening head <head> tag: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> Documents must be well-formed: This means that all elements must have closing tags and must be correctly nested. For example overlapping tags may work in most browsers but are NOT allowed in XHTML. <b><i>This is incorrect</b></i> <b><i>This IS correct.</i></b>

Page 23 RTBWizards.com © 2007 | All Rights Reserved


All element and attribute names must be lower case: XML is case-sensitive so because XHTML is an application of XHTML it is important that all elements and attributes are lower case! You can no longer have <H2> or <P>, it must be <h2> and <p>. Non-empty elements must have a closing tag: In HTML some elements were not required to have closing tags. For example a paragraph <p> would be closed by the next paragraph to follow, but in XHTML you are required to close all elements so <p> would be closed by </p>. <p>This is a paragraph.</p> <p>This is another paragraph.</p> Empty Elements must also be closed: Where previously we could use <br> or <hr> or <input type="text"> we now need to close these elements with />. So the examples shown become <br/>, <hr/> and <input type="text"/> BUT in order to be backward compatible we add an extra space, so currently you should use: <br />, <hr /> and <input type="text" />. Attribute values must always be quoted: For example <img alt="Photo 2" src="images/photo2.jpg" width=”100” height=”75” /> is correct but <img alt="Photo 2" src="images/photo2.jpg" width=100 height=75 />is incorrect. Script and Style elements: Where previously you had <style type="text/css"> <!---> </style> you now would have the following: <style type="text/css"> /*<![CDATA[*/ <!---> /*]]>*/ </style> This can be a problem for most current browsers, as they do not like the CDATA block. For now, the best solution is to call any JavaScript and CSS from an external file. For example: <script language="JavaScript" type="text/javascript" src="main.js"></script> <link rel="stylesheet" type="text/css" href="style.css" />

Lesson 10: Validation Issues If you don’t hang around webmaster circles, you may not know what validation is or that HTML validation and CSS validation are sometimes controversial issues with some people.

What does validating mean? For those who are unfamiliar with what validating a web page (i.e. validating your HTML or CSS code) means, it basically refers to using a program or an online service to check that the web pages you create are free of errors. In particular, an HTML validator checks to make sure the HTML (or XHTML) code on your web pages complies with the standards set by the W3C (World Wide Web Consortium), the organization that issues the HTML standards. The W3C has its own online validator that you can use for free located at http://validator.w3.org . Page 24 RTBWizards.com © 2007 | All Rights Reserved


A CSS validator checks your cascading style sheets in the same manner. It will check to make sure your coding complies with the CSS standards set by the W3C. You can get free validation for your style sheets at http://jigsaw.w3.org/css-validator/

The Pros The proponents of HTML and CSS validation say that there are a number of reasons why you should validate your code: It Helps Cross-Browser, Cross-Platform, and Future Compatibility: Although you may be able to create a web pate that works just fine in your browser, your page may contain errors that do not show up in that browser due to an existing quirk or bug. Another person using a different browser may wind up viewing the same page but it will not show up correctly for them. It is also possible that the next new version of your browser will cause the page to be broken. Coding your pages so that they are correct and without errors will result in pages that are more likely to work across different browsers and system platforms. It is also a form of insurance against future versions or browsers since all browsers aim towards compliance with HTML and CSS standards. Search Engine Visibility: When there are errors on a web page, browsers typically try to compensate in different ways. Hence some browsers may ignore the broken elements while others make assumptions about how to display the content. The problem is that when search engines obtain your page and try to parse them, they also have to make certain decisions about what to do with errors. Like browsers, different search engines will probably make different decisions about those errors. The worst case is that a search engine would ignore your page entirely. Professionalism: Even if you test your web site will all of the various browsers in existence on all platforms in use and find that it works perfectly, errors within your site reflect poorly on your skills. The issue is two-fold: first, a poorly coded web page reveals that the web designer does not know his stuff or is a sloppy worker; second, it affects his marketability.

The Cons Those who are against a blanket rule about validation often cite the following reasons: Validation is no Guarantee that the Page Works: Even if you validate your code, you still have to test it in the various browsers. Having code with no syntax errors does not mean that the HTML or CSS code will do what you want. Hence some of the proponents of this view argue that the main goal when designing a web page is to make sure that is viewable and useable by visitors, no some esoteric goal of standards compliance. Time Constraints for Conversions: In an ideal world, you want all of your pages to be useable and error free. In the real world, however, many web designers with thousands of existing pages will be hard-pressed to find time to convert all of those pages so that they validate correctly. Since these pages are already doing well on the web, time is better spent doing work that is actually productive. The Average Visitor Doesn’t Look at the Code: Against the argument about professionalism is the counter-argument that the average visitor to your site is not likely to go around your site viewing the source code in an effort to locate HTML or CSS errors. To the visitor, how the page appears in the browser is the true test of the web designer’s skill.

Page 25 RTBWizards.com Š 2007 | All Rights Reserved


Our View Validating your HTML and CSS code for standards compliance does have benefits. It protects your pages from problems arising from syntax errors in your code due to different ways of interpreting errors by the search engines and browsers.

Lesson 11: Resources Reserved Words You should avoid the following words when creating class or ID names. These words are frequently used in connection with other scripting languages so it is best not to use them. Abstract Boolean Break Byte Case Catch Char Class Comment Const Continue Debugger

Default Delete Do Double Else Enum Export Extends False Final Finally Float

For Function Goto If Implements Import In Instanceof Int Interface Label Long

Native New Null Package Private Protected Public Return Short Statistic Super Switch

Synchronized This Throw Throws Transient True Try Typeof Var Void White With

Books While you might rather curl up with the latest Dean Koontz thriller, having some good reference books available can be invaluable. The following books sit in my office and I still refer to them often. These books are available through Amazon.com, BarnesandNoble.com, or through your local area book dealer. Cascading Style Sheets: The Definitive Guide, 2nd Edition by Eric Meyers Eric Meyer on CSS: Mastering the Language of Web Design by Eric Meyers The CSS Anthology: 101 Essential Tips, Tricks and Hacks by Rachel Andrew

CSS Links The Web Standards Project: Provides coverage of interim releases of major browsers’ CSS implementations. http://www.webstandards.org/ CSS Validator: Validating using one of three different methods. http://jigsaw.w3.org/cssvalidator/validator.html#validate-by-uri The Layout Reservoir: A few excellent CSS layouts to borrow, steal, abduct, and torture. http://www.bluerobot.com/web/layouts/ CSS School: The best CSS web site available. http://www.w3schools.com/css/ CSS Reference Table: An excellent table reference to CSS properties. http://builder.com.com/5100-31-5071268.html Zen Garden: An amazing CSS “inspiration” site. http://www.csszengarden.com/

Page 26 RTBWizards.com © 2007 | All Rights Reserved


CSS Play: A bonanza of CSS menus, photo galleries, and more. http://www.cssplay.co.uk/menu/index.html Layout Gala: 40 different free CSS page layout designs. http://blog.html.it/layoutgala/ Max Design: Some unique ways to style definition lists http://www.maxdesign.com.au/presentation/definition/

Color Inspiration If you need a bit of color inspiration, these sites will be useful to you. http://www.colorschemer.com/online.html http://www.colormix.com/ http://www.colormatters.com/entercolormatters.html http://www.neteffect.dk/colormatch/ http://www.graphic-design.com/Web/PixelSmith/colors/charts/index.html

Page 27 RTBWizards.com Š 2007 | All Rights Reserved


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.