Sunteți pe pagina 1din 49

CSS Tutorials : Lesson 1 – Introduction

In this tutorial you will learn about Cascading Style Sheets (CSS), Introduction to CSS, What you should
already know? History, What is CSS? CSS saves a lot of work and time, CSS reduces the file size of HTML
documents and CSS can be designed for different media

What you should already know?

The tutorial assumes that you have basic understanding of the following topics:

• HTML/XHTML

History

In the old days we had only HTML, which was good, with HTML you can make good web designs, you can
adjust the layouts using tables, and the layout problems can be fixed using the single-pixel gif image, but
this is not good.

The layout problem and many others were fixed using CSS, with CSS design became a straight forward
process, all web development/design tools now contain a CSS designer that makes using CSS a first
choice for web designers.

What is CSS?

• CSS stands for Cascading Style Sheets.


.
• CSS is a language that works with HTML to define how to present the contents.
.
• Styles are placed directly into HTML, HTML document head, and/or in a separate sheet.
.
• CSS contains rules to define how HTML elements will be styled.
.
• Many HTML files can use the same CSS file, and one HTML file can use many styles.

CSS saves a lot of work and time

Single CSS file can control the appearance of multiple HTML documents; to make a change to all
documents you don’t have to make the change in every document, just make it in the CSS file, and it will
be reflected on all documents that are linked to it.

Even for one document, the CSS can define the appearance of an HTML element; all you have to do to
change the appearance of that element all over the document is to change it in the CSS, this saves a lot of
time and work.

CSS reduces the file size of HTML documents

By removing the presentation from the HTML documents and saving it in a smaller size CSS file, you get
rid of presentation attributes and spacing images which reduces the size of the document and makes site
navigation faster.

CSS can be designed for different media

A document can be styled in a way that is suitable for the presentation media, you can have many style
sheets linked to one document, every sheet is for content presentation on a specific media, including
browsers, printers, handheld devices, and projectors.

Anish Varghese Page 1 10/17/2008


CSS Tutorials : Lesson 2 – Syntax
In this tutorial you will learn about Cascading Style Sheets (CSS) Syntax, Rule set, Combining selectors,
The class selector, The id selector and Comments

Rule set

A rule or rule set tells the browser how to render an element, the rule set consists of the following:

1. The selector: represents the HTML element to be affected by the rule.


.
2. The declaration block: represents the effect to be applied to the element(s), and it contains one
or more property value pairs.

Example:

p {text-align: right; color: red}

The selector here is the HTML element < p >, all what follows is the declaration block, the declaration
block has to start with an opening curly brace “{“, and ends with a closing curly brace “}”, every
property/value pair has to be ended with a semi column”;”, the semi column can be only omitted for the
last property/value pair, the property and the value are separated with a colon “:”, spaces and line feeds
may be added for better readability, it doesn’t affect the CSS validity, the previous rule can be written as:

p
{
text-align: right;
color: red;
}

Combining selectors

When many selectors have the same declarations, they may be grouped, this will reduce the CSS file size,
and makes it easier to update the style.

Example:

h1, h2, h3
{
text-align: center;
color: red;
}

Note that selectors are separated with a comma.


If one of the elements has an additional declaration it can be added later.

Example:

h1, h2, h3
{
text-align: center;
color: red;
}
h2
{

Anish Varghese Page 2 10/17/2008


font-style: italic;
}

So all the elements h1, h2, and h3 will have center-aligned text, and red color, and only h2 font style will
be italic.

The class selector

You can define different style for the same HTML element using the class selector.

Example:

td.header {
font-weight: bold;
font-variant: small-caps;
text-align: center;
}
td.normal {
text-align: left;
}

To use it in the HTML document:

< table >


< tr >
< td class=”header” > ID < /td >
< td class=”header” > Department < /td >
< /tr >
< tr >
< td > 1 < /td >
< td > Web Design < /td >
< /tr >
< /table >

The tag name can be omitted too, this will enable any HTML element to use the rule, the previous CSS
rules can be written as:

.header {
font-weight: bold;
font-variant: small-caps;
text-align: center;
}
.normal {
text-align: left;
}

It’s used the same way in the HTML document.

The id selector

You can define the same style for different HTML elements using the id selector.

Example:

#red
{
color: red;

Anish Varghese Page 3 10/17/2008


}

You may use it in the HTML document this way:

< h1 id=”red” > This is a red header < /h1 >


< p id=”red” > This is a red paragraph < /p >

You can restrict the id to a specific element:

p#red
{
color: red;
}

This way only the < p > element with id of red < p id=”red” > will be styled using this rule.

Comments

CSS comments can be placed anywhere in the CSS, it will be ignored by the browser, the comment has to
start with “/*” and ends with “*/”.

Example:

/* comment /
p
{
/ another comment /
text-align: right; / another comment */
color: red
}

CSS Tutorials : Lesson 3 – Applying CSS


In this tutorial you will learn about Cascading Style Sheets (CSS), Applying CSS, External style sheets,
Internal styles, Inline styles and Multiple style sheets

There are different types for specifying styles to be used with HTML documents, they can be specified in
an external CSS file, inside the < head > element of the HTML document, or/and inline to be specific to a
single HTML element, also there is the browser default style.
These styles will be cascaded in a single HTML documents at the following priority:

1. Browser default.
.
2. External CSS file.
.
3. Internal < head > style.
.
4. Inline style.

Inline style has the highest priority.

External style sheets

Anish Varghese Page 4 10/17/2008


The external style sheet can be applied to many HTML documents, a .css file has to be created, and you
link to it from the HTML document using < link > tag.

Example:

< head >


< link rel=”stylesheet” type=”text/css” href=”cssfile.css” / >
< /head >

The CSS file may look something like:

body
{
background-color: #00CCFF;
}
h1
{
color: #0000FF;
}
p
{
font-family: Arial, Helvetica, sans-serif;
}

Internal styles:

The internal style will be applied only to the document that declares it.

Example:

< head >


< style type=”text/css” >
body
{
background-color: #00CCFF;
}
h1
{
color: #0000FF;
}
p
{
font-family: Arial, Helvetica, sans-serif;
}
< /style >
< /head >

Inline styles:

The inline style is only applied to the HTML element that declares it.

Example:

< p style=”color: red;” >This is a red paragraph.< /p >

Multiple style sheets

Anish Varghese Page 5 10/17/2008


If multiple styles for the same element are used in the same document, the browser will use styles priority
to select the style to be applied for this element presentation.

Example:

The external style sheet:

p
{
font-size: 9px;
font-style: normal;
font-variant: small-caps;
}

The internal style inside the element:

p
{
font-size: 10px;
font-style: italic;
}

Any < p > element in the document will be styled as:


p
{
font-size: 10px;
font-style: italic;
font-variant: small-caps;
}

This is because the internal style has higher priority than the external style sheet.

If a < p > element is defined in the same document as:

< p style=” font-size:12px;”>Inline Style< /p >

Then it will be styled as:

p
{
font-size: 12px;
font-style: italic;
font-variant: small-caps;
}

This is because the inline style overrides any other used styles.

CSS Tutorials : Lesson 4 – Background


In this tutorial you will learn about Cascading Style Sheets (CSS), Background, Background Color,
Background image, Repeating background image, Background position and Background attachment.

Background color

Anish Varghese Page 6 10/17/2008


To set the background color of an element, use the “background-color” property.

Example:

body
{
background-color: #FF0000;
}

This sets the background color of the document to red.

Background image

To set an image as a background, use the “background-image” property.

Example:

body
{
background-image: url(bg_image.jpg);
}

Repeating background image

To repeat a background image, use the “background-repeat” property.

The value of this property defines how the repeat will occur, the value can be one of the following:
• repeat : The image is repeated both horizontally and vertically.
• repeat-x : The image is repeated only horizontally.
• repeat-y : The image is repeated only vertically.
• no-repeat : The image is not repeated.

Example:

body
{
background-image: url(bg_image.jpg);
background-repeat: repeat-y;
}

This will repeat the image vertically.

Background position

To set the background position of a background image, use the “background-position” property.

The value of this property can be on of the following:


top left, top center, top right, center left, center center, center right, bottom left, bottom center, bottom
right.

The horizontal position is specified first, and then the vertical position, If only one value is used, it sets the
horizontal position only and the vertical position will be center by default.

Percentage and length values can be used also.

Example:

Anish Varghese Page 7 10/17/2008


body
{
background-image: url(bg_image.jpg);
background-repeat: repeat-y;
background-position: 100% 0%;
}

This will use “bg_image.jpg” as a background image, place its upper-right corner in the upper-right corner
of the body, and repeat it vertically.

Background attachment

To set if a background image is to be fixed or to scroll with the page use the “background-attachment”
property.

The value of this property can be one of the following:


• scroll : to scroll with the rest of the page.
• fixed : to be fixed.

Example:

body
{
background-image: url(bg_image.jpg);
background-attachment: scroll;
}

This will make the background image scrolls with the rest of the page.
Using the shortcut
You can set all background properties in one declaration using the shortcut property “background”, the
values have to be in the following order:
background-color, then background-image, then background-repeat, then background-attachment, and
finally background-position.

Example:

body
{
background: #00FF00 url(bg_image.jpg) repeat-y fixed 100% 0;
}

This sets the background color to green, uses the image “bg_image.jpg “ as a background, repeats it
vertically, and places its top right corner at the top right corner of the page.

CSS Tutorials : Lesson 5 – Text


In this tutorial you will learn about Cascading Style Sheets (CSS), Text, Text color, Text background color,
Text direction, Text align, Text indent, Text transform, Text decoration, Letter spacing and Word spacing.

Text color

To set the text color, use the “color” property.

Example:

Anish Varghese Page 8 10/17/2008


p
{
color: #FF0000;
}
h1
{
color: red;
}

This sets the HTML element < p > and the HTML element < h1 > to red.

Text background color

To set the background color of an element, use the property “background-color”, this property was
explained in CSS background lesson.

Text direction

To set the text direction, use the “direction” property, it can take one of two values:

• ltr: sets the direction to be from left to right as in English and French.
• rtl: sets the direction to be from right to left as in Arabic and Hebrew.

Example:

body
{
direction: rtl;
}

This sets the text direction of the whole document to be from right to left.

Text align

to align the text contained in an element to the element, use the property “text-align”, this property can
take one of the following values:
left, right, center, or justify.

Example:

P
{
text-align: right;
}

This aligns the element < p > text to the right of the element that it’s contained in.

Text indent

To indent the first line of a text, use the “text-indent” property, the value can be an absolute length, or a
percentage value.

Example:

P
{

Anish Varghese Page 9 10/17/2008


text-indent: 15px;
}

This indents the first line of the HTML element < p > 15 pixels.

Text transform

To set the text letters case, use the property “text-transform”, this property can have one of the following
values:

• none: no transformation.
• capitalize: the first letter of each word will be in upper case.
• uppercase: all letters will be uppercase.
• lowercase: all letters will be lowercase.

Example:

P
{
text-transform: lowercase;
}

This sets all the < p > element text characters to be in lowercase.

Text decoration

To set the text decoration, use the property “text-decoration”, it can have one of the following values:

• none: no decoration
• underline: the text will be decorated using a line under it.
• overline: the text will be decorated using a line over it.
• line-through: the text will be decorated using a line through it.

Example:

.underline
{
text-decoration: underline;
}

This causes any text element that uses this class to be underlined.

Letter spacing

To increase or decrease the space between characters, use the property “letter-spacing”, it can have one
of the following values:

• normal: the normal letters spacing of the used font.


• A length value.

Example:

Anish Varghese Page 10 10/17/2008


Body
{
letter-spacing: 1px;
}

This sets the space between all characters in the document to 1 pixel.

Word spacing

To increase or decrease the space between words, use the property “word-spacing”, it can have one of the
following two values:

• Normal: the normal words spacing of the used font.


• A length value.

Example:

P
{
word-spacing: 2px;
}

This sets the space between all words in the document to 2 pixels.

CSS Tutorials : Lesson 6 – Fonts


In this tutorial you will learn about Cascading Style Sheets (CSS), Fonts, Font family,Font size, Font weight,
Font style and Font variant.

Font family

To set the font for a specific text, use the property “font-family”, the value can be more than one family
separated with a comma, the browser will display the text using the first font, if it’s not supported by the
operating system, it will use the next font, if no font is supported, it will use the default font.

Example:

body
{
font: Arial, Helvetica, sans-serif;
}

This sets the HTML document font to one of the specified fonts starting from left, if no font is supported,
then the browser default font is used.

Font size

To set the font size, use the property “font-size”, the value can be one of the following values:
xx-small, x-small, small, medium, large, x-large, xx-large, smaller, or larger
It can be also a length value or a percentage.

Example:

Body
{

Anish Varghese Page 11 10/17/2008


font-size: 12px;
}

This sets the font size of the whole HTML document to 12 pixels.

Font weight

To set the weight of a font, use the property “font-weight”, the value can be one of the following values:
normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, or 900

Example:

.strong
{
font-weight: bold;
}

This sets all the text of the elements that use this class to be bold.

Font style

To set the style of a font, use the property “font-style”, the value can be one of the following values:
normal, italic, or oblique.

Example:

.italic
{
font-style: italic;
}

This sets all the text of the elements that use this class to be italic.

Font variant

To set the variant of a font, use the property “font-variant”, the value can be one of the following values:
normal or small-caps.

Example:

.caps
{
font-variant: small-caps;
}

This sets all the text of the elements that use this class to be uppercase.

CSS Tutorials : Lesson 7 – Borders


In this tutorial you will learn about Cascading Style Sheets (CSS) Borders, Border width, Border style,
Border color and Using the shortcut

Borders in CSS are not just the table borders as in HTML, with CSS any HTML element can have borders,
CSS adds many effects to be applied to these borders.

Anish Varghese Page 12 10/17/2008


Border width

To set the width of a border, use the property “border-width”, the value of this property can be one of the
following values:
thin, medium, thick, or an absolute value as the table “border” attribute in HTML.

Example:

table
{
border-width: 2px;
}

This sets the width of the border of the < table > element to be 2 pixels.

Border style

To set the style of a border, use the property “border-style”, the value of this property can be one of the
following values:
none, dashed, dotted, double, groove, hidden, inset, outset, ridge, or solid.

Example:

Table
{
border-width: 1px;
border-style: dotted;
}

This sets the border style of the < table > element to be dotted, and its width to 1 pixel.

Border color

To set the color of a border, use the property “border-color”, the value of this property can be any HTML
color.

Example:

table
{
border-width: 1px;
border-style: dotted;
border-color: blue;
}

This sets the style of the border of the < table > element to dotted, width to 1 pixel, and color to blue.

Note: All the previous properties can take up to 4 values, in the previous example if color is defined as:

border-color: blue green;

The top and bottom borders will be colored as blue and the right and left borders will be colored as green.

If the rule is declared as:

border-color: blue green red;

Anish Varghese Page 13 10/17/2008


The top border will be colored as blue, the right border will be colored as green, the bottom border will be
colored as red, and the left border will be colored as the right border.

If the rule is declared as:

border-color: blue green red yellow;

The top border will be colored as blue, the right border will be colored as green, the bottom border will be
colored as red, and the left border will be colored as yellow.

The rule is:

1. The first value is for the top border


2. If there is no other value, then all borders color will be set to the only declared value.
3. Else, the second value is for the right border.
4. If there is no other value, then the bottom border value will be the same as the top border, and the left
border value will be the same as the right border.
5. Else, the third value is for the bottom value.
6. If there is no other value, then the left border value will be the same as the right border.
7. Else, the last value will be for the left border.

This applies all border properties.

Using the shortcut

You can set all the properties in one declaration, to do so use the property “border”, and the order is:
border-width, then border-style, and finally border-color.

Example:

Table
{
border: 1px dotted blue;
}

This sets the border width of the < table > element to 1 pixel, the style to dotted, and the color to blue.
There are other border properties to set the border values for only one of the borders, they have the same
values, they are:

border-top-width, border-top-style, border-top-color, border-top, border-right-width, border-right-style,


border-right-color, border-right, border-bottom-width, border-bottom-style, border-bottom-color, border-
bottom, border-left-width, border-left-style, border-left-color, and border-left.

The only difference between these properties and the previously explained properties is that they can’t
take more than one value to be set for that single border.

CSS Tutorials : Lesson 8 – Margin


In this tutorial you will learn about Cascading Style Sheets (CSS) Margin and Using the shortcut

The margin is the space around the element from the four sides, the margin attributes enables you to
increase or decrease this space; the space can be a negative value, which may make elements overlap.

Using margins is very easy and straight forward, to declare the margin you can use the following
properties:

margin-top, margin-right, margin-bottom, and/or margin-left.

Anish Varghese Page 14 10/17/2008


The values of these properties can be an absolute length, a percentage.

Example:

.margins
{
margin-top: 5px;
margin-right:10px;
margin-bottom: 5px;
margin-left: 12px;
}

This will set the top margin of any HTML element that uses this class to 5 pixels, the right margin to 10
pixels, the bottom margin to 5 pixels, and the left margin to 12 pixels.

Using the shortcut

A shortcut property can be used to set all the margins in one declaration; the property is “margin”, and
the order is:

margin-top, then margin-right, then margin-bottom, and finally margin-left.

Example:

The previous example can be written as:

.margins
{
margin: 5px 10px 5px 12px;
}

This will cause the same effect as the previous example.

You can use from 1 to 4 values for the “margin” property, and the browser will assign a value for each side
the same way as in borders.

CSS Tutorials : Lesson 9 – Padding


In this tutorial you will learn about Cascading Style Sheets (CSS) Padding,

The padding is the space between the element border and the element content from the four sides, the
padding attributes enables you to increase or decrease this space; unlike spacing padding space values
can’t be negative.

To declare the padding you can use the following properties:


padding-top, padding-right, padding-bottom, and/or padding-left.
The values of these properties can be an absolute length, a percentage.

Example:

table
{
padding-top: 5px;
padding -right:3px;
padding -bottom: 5px;

Anish Varghese Page 15 10/17/2008


padding -left: 2px;
}

This sets the top padding of the < table > element to 5 pixels, the right padding to 3 pixels, the bottom
padding to 5 pixels, and the left padding to 2 pixels.

Using the shortcut

A shortcut property can be used to set all sides padding in one declaration; the property is “padding”, and
the order is:

padding-top, then padding-right, then padding-bottom, and finally padding-left.

Example:

The previous example can be written as:

table
{
margin: 5px 3px 5px 2px;
}

This will cause the same effect as the previous example.

You can use from one to four values for the “padding” property, and how the browser will assign a value
for each side works the same as in borders and margins.

CSS Tutorials : Lesson 10 – List


In this tutorial you will learn about Cascading Style Sheets (CSS) List, List style type, List style position,
List style image and Using the shortcut.

List style type

To set the list style marker type, use the property “list-style-type”, this property can have on of the
following values:

none, circle, disc, square, decimal, decimal-leading-zero, lower-alpha, upper-alpha, lower-greek, lower-
latin, upper-latin, lower-roman, upper-roman, armenian, cjk-ideographic, georgian, hebrew, hiragana,
hiragana-iroha, katakana, or katakana-iroha.

Example:

< ul style=”list-style-type: disc;” >Fruits:


< li >Apples< /li >
< li >Bananas< /li >
< /ul >

This will be presented as follows:

Fruits:
• Apples
• Bananas

Anish Varghese Page 16 10/17/2008


List style position

To set the position of the list item marker, use the property “list-style-position”, the value that can be
assigned to this property may be on of the following:

inside or outside.

Example:

< ul style=”list-style-type: disc; list-style-position: inside ;” >Fruits:


< li >Apples< /li >
< li >Bananas< /li >
< /ul >

This will be presented as follows:

Fruits:
• Apples
• Bananas

List style image

To use a custom image as a list style marker, use this property “list-style-image”, the value of this
property is a URL.

Example:

< ul style=”list-style-image: list_image.jpg” > Fruits:


< li >Apples< /li >
< li >Bananas< /li >
< /ul >

This sets the image “list_image.jpg” as the marker for this list style.

Using the shortcut

A shortcut property can be used to set all the properties of the list style in one declaration, the property is
“list-style”, and the order is:

padding-top, then padding-right, then padding-bottom, and finally padding-left.


list-style-type, then list-style-position, and finally list-style-image.

Example:

ul
{
list-style: disc inside url(“list_image.jpg”)
}

This sets the marker style to disk, the position to be inside, and overrides the marker to be the mage
“list_image.jpg” instead of disc.

CSS Tutorials : Lesson 11 – Dimensions

Anish Varghese Page 17 10/17/2008


In this tutorial you will learn about Cascading Style Sheets (CSS) - Dimensions, Line height, Width and
Height.

The dimension properties enable you to increase or decrease the height and width of HTML elements.

Line height

To set the distance between the lines of an element, use the property “line-height”, the value of this
attribute can be an absolute value or a percentage.

Example:

p
{
line-height: 0.3cm;
}

This sets the distance between lines to 0.3 cm.

Width:

To control the width of an element, you can use three properties, they are:

• “width”: sets the element width.


• “min-width”: sets the minimum width of an element.
• “max-width”: sets the maximum width of an element.

The value of these properties can be an absolute value or a percentage.

Example:

table
{
width: 100%
}

This sets the width of the

CSS Tutorials : Lesson 12 – Elements Display


In this tutorial you will learn about Cascading Style Sheets (CSS) - Elements Display, Float, Position,
Visibility, Cursor, Vertical align and z-index.

The display properties enable you to set the way to display elements and the position of the element
relative to another element or to the whole document.

Float

To set the appearance of an element or an image relative to another element, use the property “float”, this
property can have on of the following values:

left, right, or none.

Anish Varghese Page 18 10/17/2008


Example:

img
{
float: left;
}

This sets the image position to be at the left of the element.

Position

To set the position of an element, use the property “position”, this property can have on of the following
values:

• absolute: relative to the parent element.


• relative: relative to the normal position of the element.

Example:

h3
{
position: relative;
right: 10px;
}

This will position the < h3 > tag at 10 pixels to the right relative to its original position.
The “position” property just defines the position and it needs one of the following properties:

“top”, “right”, “bottom”, and “left”

These properties declare the amount as an absolute value or a percentage.

Visibility

To set if an element will be visible or invisible, use the property “visibility”, it van have one of the following
values:

visible or hidden.

Example:

.hide
{
visibility: hidden;
}

This will make the element that uses this class to be invisible when the document is rendered.

Cursor

To set the type of the cursor, use the property “cursor”, this property can have one of the following values:

crosshair, help, move, pointer, text, url, wait, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize,
s-resize, or w-resize.

Example:

Anish Varghese Page 19 10/17/2008


body
{
cursor: crosshair;
}

This sets the cursor of the whole document to crosshair.

Vertical align

To set the vertical alignment of an element, use the property “vertical-align”, this property can have one of
the following values:

sub, super, top, bottom, middle, text-top, text-bottom, an absolute value, or a percentage.

Example:

td
{
vertical-align: top;
}

This sets the contents of the table cell to be in the top.

z-index

If there are elements that overlap, and you want to display them as layers, you can define the order of the
element using the property “z-index”, the value is a number that represents the element order.

Example:

img
{
z-index: -1;
}

This will place the < img > element behind all other elements.

CSS Tutorials : Lesson 13 – Pseudo Classes


In this tutorial you will learn about Cascading Style Sheets (CSS) - Pseudo Classes, Link, First letter and
First line

CSS has pre-defined pseudo classes.


pseudo class has special syntax, the rule starts with the selector, then the pseudo class, and finally the
declaration, the selector and the pseudo class are separated with a colon “:”.

CSS defines the following pseudo classes:


link, hover, active visited, first-line, and first-letter.

Link

To define link properties, you can use four pseudo classes, they are:

• link: sets the style of the unvisited link.


• hover: sets the style of the link when mouse goes over it.

Anish Varghese Page 20 10/17/2008


• active: sets the style of the link when activated.
• visited: sets the style of the visited link.

Example:

a:link
{
color: #0000FF;
}
a:visited
{
color: #FF0000;
}
a:hover
{
color: #00FF00;
}
a:active
{
color: #0000FF;
}

This sets the link color to be in blue when unvisited and when active, to be in red when visited, and to be
in green when mouse goes over it.

First letter

To set a different style for the first letter of an element, use the pseudo class “first-letter”, this can set the
first letter font, color, and text properties.

Example:

p
{
font-size: 10px;
}
p: first-letter
{
color: red;
}

This will display the first letter of the element < p > in red color.

First line

To set a different style for the first line of an element, use the pseudo class “first-line”, this can set the
first line font, color, and text properties.

Example:

p
{
font-size: 10px;
}
p: first-line
{
color: red;
}

Anish Varghese Page 21 10/17/2008


This will display the first line of the element < p > in red color.

CSS Tutorials : Lesson 14 – Media Styles


In this tutorial you will learn about Cascading Style Sheets (CSS) - Media Styles, Internal different media
CSS and External CSS files.

CSS adds support for different media types, you can create many styles, and each style defines how the
document will be styled when its media type is used.

There are two ways to use a different CSS for different media types in the same document, you can place
the style internally in the HTML document, or you can create as many CSS files and link them to the HTML
document.

Internal different media CSS

To use internal media CSS, use the “@media” rule, the rule(s) will be inside the < style > elements.

Example:

@media screen
{
p
{
font-size: 12px;
}
}

@media print
{
p
{
font-size: 10px;
}
}

This will set the size of the text of the < p > element to 12 pixels when displayed at the screen, and to 10
pixels when printed.

External CSS files

To use external CSS files, add a < link > element inside the < head > element of the HTML document for
every CSS file to be used, add the attribute “media” to the element, and specify the media type that will
use this file, media values can be one of the following:

all, aural, braille, embossed, handheld, print, projection, screen, tty, or tv.

Example:

We have two CSS files, the first one is named “screen_style.css”, and it defines how the HTML document
will be displayed on screen, the second one is named “print_style.css”, and it defines how the HTML
document will be displayed when printed, to use both of them in the HTML document:

< head >


< link rel=”stylesheet” type=”text/css” media=”screen” href=”screen_style.css” />< link />
< link rel=”stylesheet” type=”text/css” media=”print” href=”print_style.css” />< link />
< /head >

Anish Varghese Page 22 10/17/2008


This will use the “screen_style.css” for screen display, and “print_style.css” for printing.

Printing HTML documents always causes problems, with CSS you can specify a printing style and attach it
to the document.

CSS has a great support to document printing, it adds many rules that helps in adjusting the printing
measures of the document.

CSS Tutorials : Lesson 15 – Units, Colors, References


In this tutorial you will learn about Cascading Style Sheets (CSS), Units and Colors, Percentage, Values,
Colors, References - Font and Text, Color and Background, Layout, Classification, Positioning and Pseudo-
classes.

Units and Colors

Percentage

Percentage values have to be followed by “%”.

Values

The absolute values represent a measurement, there are many measurements in CSS, so the
measurement unit has to be stated.

CSS measurement units are:

• cm: centimeter.
• em: font size.
• ex: half of the font size.
• in: inch.
• mm: millimeter.
• pc: pica.
• pt: point.
• px: pixel.

Colors

Colors values can be in one of the following formats:

• color-name: the name of the color (red, green,…).


• #rrggbb: a hexadecimal representation of the color, the first two digits are for red, the following two
digits are for green, and the last two digits are for blue (#FF00FF).
• rgb(x,y,z): RGB values representation of the color (rgb(255,255,0)).
• rgb(x%,y%,z%): RGB percentage representation of the color (rgb(100%,100%,0%)).

Font and Text:

direction Sets the reading order of the specified element.


font Sets up to six separate font properties of the element.
font-family Sets the name of the font used for text in the element.
font-size Sets the size of the font used for text in the element.
font-style Sets the font style of the element as italic, normal, or oblique.
font-variant Sets whether the text of the element is in small capital letters.
font-weight Sets the weight of the font of the element.

Anish Varghese Page 23 10/17/2008


line-height Sets the distance between lines in the element.
letter-spacing Sets the amount of additional space between letters in the
element.
text-align Sets whether the text in the element is left-aligned, right-
aligned, centered, or justified.
text-decoration Sets whether the text in the element has blink, line-through,
overline, or underline decorations.
text-indent Sets the indentation of the text in the element.
text-transform Sets the rendering of the text in the element.
vertical-align Sets the vertical positioning of the element.

Color and Background

background Sets up to five separate background properties of the element.


background-attachment Sets how the background image is attached to the element
within the document.
background-color Sets the color behind the content of the element.
background-image Sets the background image of the element.
background-position Sets the position of the background of the element.
background-repeat Sets how the background-image property of the element is tiled.
color Sets the color of the text of the element.

Layout

border Sets the properties to be drawn around the element.


border-bottom Sets the properties of the bottom border of the element.
border-bottom-color Sets the color of the bottom border of the element.
border-bottom-style Sets the style of the bottom border of the element.
border-bottom-width Sets the width of the bottom border of the element.
border-color Sets the border color of the element.
border-left Sets the properties of the left border of the element.
border-left-color Sets the color of the left border of the element.
border-left-style Sets the style of the left border of the element.
border-left-width Sets the width of the left border of the element.
border-right Sets the properties of the right border of the element.
border-right-color Sets the color of the right border of the element.
border-right-style Sets the style of the right border of the element.
border-right-width Sets the width of the right border of the element.
border-style Sets the style of the left, right, top, and bottom borders of the
element.
border-top Sets the properties of the top border of the element.
border-top-color Sets the color of the top border of the element.
border-top-style Sets the style of the top border of the element.
border-top-width Sets the width of the top border of the element.
border-width Sets the width of the left, right, top, and bottom borders of the
element.
float Sets on which side of the element the text will flow.
Margin Sets the width of the left, right, bottom, and top margins of the
element.
margin-bottom Sets the height of the bottom margin of the element.
margin-left Sets the width of the left margin of the element.
margin-right Sets the width of the right margin of the element.
margin-top Sets the height of the top margin of the element.
Padding Sets the amount of space to insert between the element and its
margin or, if there is a border, between the element and its

Anish Varghese Page 24 10/17/2008


border.
padding-bottom Sets the amount of space to insert between the bottom border of
the element and the content.
padding-left Sets the amount of space to insert between the left border of the
element and the content.
padding-right Sets the amount of space to insert between the right border of
the element and the content.
padding-top Sets the amount of space to insert between the top border of the
element and the content.

Classification

display Sets whether the element is rendered.


list-style Sets up to three separate list style properties of the element.
list-style-image Sets which image to use as a list-item marker for the element.
list-style-position Sets how the list-item marker is drawn relative to the content of
the element.
list-style-type Sets the predefined type of the line-item marker for the .

Positioning

Bottom Sets the bottom position of the element in relation to the bottom
of the next positioned element in the document.
Height Sets the height of the object.
Left Sets the position of the element relative to the left edge of the
next positioned element in the document.
Overflow Sets how to manage the content of the element when the
content exceeds the height and/or width of the object.
Position Retrieves the type of positioning used for the object.
Right Sets the position of the element relative to the right edge of the
next positioned element in the document.
top Sets the position of the element relative to the top edge of the
next positioned element in the document.
Visibility Sets whether the content of the element is displayed.
Width Sets the width of the object.

Pseudo-classes

active Sets the style of anchor when the link is engaged or active.
cursor Sets the type of cursor to display as the mouse pointer moves
over the element
hover Sets the style of the anchor when the user hovers the mouse
over the links.
link Sets or retrieves the style of the < a > element for the default
state of the link.
visited Sets the style of the anchor for previously visited links.

Anish Varghese Page 25 10/17/2008


CSS Lists: Part 1
Lists have been used as an active navigational element for a while now, by using CSS to style them in a
fashion that makes them recognizable as part of the page’s navigation. They weren’t originally intended
for this, however. The more you look back at HTML specifications, the more it’s obvious that their purpose
was as a visual, documentational aid. Indeed, those of you who are veterans to the web will remember
the very old pages characterized by the left-aligned black text on a white background, the ubiquitous
Times New Roman font, the very long pages with many anchors, and the black circle bulletpoint lists.
Actually, the HTML part didn’t change much since those times as far as lists are concerned, apart from the
class attribute.
We’ll start with just such a list:
• List Item 1
• List Item 2
• List Item 3 The HTML used for it is:
<div class=”list_container”> <ul> <li>List Item 1</li> <li>List Item 2</li> <li>List Item 3</li> </ul>
</div>

I opted not to style the list ul or il elements themselves, but rather encase the list in a DIV so that we’ll
be able to address the different elements within it in a simple manner. This isn’t really necessary—you can
often achieve exactly what you need by styling the ul element and addressing the elements under it,
instead. Remember though, that the element that you wrap the list around needs to be a DIV, rather
than a SPAN, since strict XHTML won’t validate an Inline element having a Block child (you could, of
course, add display: block; to its class, by why go that far when DIV is ready and waiting to serve?).
Since I’m going to be referring to elements of the Box Model frequentry throughout this document, you
may want to check out the Box Model article to get better acquainted with how CSS tells the browser to
draw elements onto the display device.

We’ll start by taking the reigns and assigning values to several well-known properties:

.list_container ul { margin-left: 0; padding-left: 0; list-style-type: none; font-size: 14px; line-height:


17px; font-family: Trebuchet MS, sans-serif, Arial, Helvetica; }

The first thing we do is eliminate the padding and margin to the left of the text. We may want to recover
that later, but for now we’re simplifying the list. We also remove the bulletpoints completely by assigning
none to the list-style-type property. Lastly, we assign font and line-height properties. You may be
wondering why bother with line-height? This is a technicality that you’ll be able to experiment with later
—If you just set a font size, sometimes the listil items will distance themselves from each other in
Internet Explorer, creating what looks like a margin, even if you specify the li’s margin property to 0.
There is a similar problem with horizonal lists, however the solution to that problem is different. The
problem often shows itself when the line-height is too small compared to the font size, though your
best bet is to simply check your design in Internet Explorer and see how it renders. Also keep in mind that
while the UL element is a Block element, the LI element is of type list-item, which means that the line-
height property governs its height, rather than the height property. In fact, if you were to replace the line-
height property with the height property of the same value, you’ll get some amusing results, which will
vary from one browser to another.

Here’s what our list looks like now:


• List Item 1
• List Item 2
• List Item 3
The list has been simplified to simply lines at this point, though of course lists have inherent properties
that mere HTML lines do not. Before we keep adding properties to the list, let’s first turn the list items into
links. We do this as easily as it sounds, by encasing them in a elements:

Anish Varghese Page 26 10/17/2008


<div class=”list_container”> <ul> <li><a href=”#”>List Item 1</a></li> <li><a href=”#”>List Item
2</a></li> <li><a href=”#”>List Item 3</a></li> </ul> </div>

Now that we have links on our list, we should style them as well:

.list_container a { display: block; padding: 1px; padding-left: 10px; width: 200px; background-color:
#FFF; border-bottom: 1px solid #DDF; } .list_container a:link, .list_container a:visited { color: #369;
text-decoration: none; } .list_container a:hover { background-color: #369; color: #fff; }

Before going over the changes, let’s view them first:


• List Item 1
• List Item 2
• List Item 3
Suddenly it no longer looks like a “documentation aid” anymore... All that’s changed is that the items were
made into links, and the links were styled the same way you would normally use CSS to style any other
link. Actually that’s not entirely accurate: a very important property has been added - display: block;.
This transformed the a elements from Inline elements into into Block elements, similar to how DIVs and
Ps are. The block takes up whatever space it can, horizontally, within the il area. This way, the structure
of the list is taken advantage of, and you can add borders and padding that apply to all of the links in the
same manner. This is also helpful when designing mouse-over effects, of course, since the cursor will be
detected all over the link area, not just the text portion.

Notice that the only elements that were specified a width were the a elements. In other words, at the very
least, the encasing DIV is taking up all the horizontal space that it can. Normally, when encasing a list
with a DIV, you would need to specify a width for the a elements, and for the DIV itself. You can’t leave
the width of the a elements empty, or the il elements will react badly in different manners depending on
the browser. You also shouldn’t set the a width to 100%, since this will conjure its own set of problems,
even if you’ve set the DIV’s width to a specific amount of pixels. This may seem troublesome, but there’s
really nothing preventing you from setting both width properties to the same pixel value, which is the
recommended route.

Let’s not write off the list markers just yet. Remember that it’s always nice to get more graphical value out
of less code, when possible (and when appropriate!). We’ll make three changes to the CSS:

.list_container ul { margin-left: 2em; padding-left: 0; list-style-type: upper-roman; font-size: 14px; line-


height: 17px; font-family: Trebuchet MS, sans-serif, Arial, Helvetica; color: #369; }

upper-roman, the margin-left was set to 2em, and


The list-style-type property value was changed to
color: #369; was added, all to the .list_container ul selector. Here’s what we get after applying the
changes:
• List Item 1
• List Item 2
• List Item 3
The margin-left had to be increased, since the list markers would otherwise appear outside of the list’s
area, to the left (in fact, the list itself is no longer 200 pixels wide, only the a elements are). The list-
style-type property value was changed to upper-roman (check the list-style-type CSS property
reference for more options), and the markers themselves were colored using the color set to the UL
element. Note that this will allow the background behind the list to show through if you don’t set a
background-color (or a background-image) value to the .list_container class.

We’ve covered some basic uses of HTML lists as navigational elements. You can see this is no rocket
science, and is very easy to manipulate and scale. In CSS Lists: Part 2, we’ll get into more complex lists,
and more subtle property usage.

Anish Varghese Page 27 10/17/2008


CSS Lists: Part 2
In CSS Lists: Part 1, we took a plain HTML list, encased it in a DIV, and used CSS to style the list by
accessing it through the DIV’s decendant-elements. Here was how the list looked like when we finished
styling it (before re-adding the markers):
• List Item 1
• List Item 2
• List Item 3
It’s now clearly a navigational element, with mouse-over reactions to boot. Let’s look at a few variations
we can achieve simply by playing around with the CSS, while leaving the HTML as it is. Needless to say, if
we were to add HTML elements, there would be more for us to style, but for now, we’ll stick to the original
structure.

We’ll start with a version that intentionally seeks to maximize the graphical detail that we can attain, by
styling every element in the HTML. This is also where we’ll encounter the first CSS-standards browser
issue:
.list_container li { width: 200px; border: 1px solid #000; margin-bottom: 4px; } .list_container a
{ display: block; padding: 2px; padding-left: 10px; background-color: #A74B4B; border: 2px solid;
border-color: #C98787 #6C3131 #6C3131 #C98787; } .list_container a:link, .list_container a:visited
{ color: #FFF; text-decoration: none; } .list_container a:hover { border: 2px solid; border-color:
#6C3131 #C98787 #C98787 #6C3131; }

We left the UL element unchanged, since it mainly styled font properties which will stay the way they are
for now. Something may draw curious attention in the code above: The width property was moved from
the a element to the LI element—I’ll explain this in a moment. The LI element was also added a 1px
black border, and a margin of 4px in order to space the list items out. The main graphic element that was
added was the button-like border to the a element. I used the short-hand definition of border-color,
defining the four colors clock-wise. Here’s what we got:
• List Item 1
• List Item 2
• List Item 3
Considering how little HTML code makes up this list, this is quite remarkable. If you tried doing that using
tables, you’d probably have to use about 10 times the code. Now, why was the width property moved
from the a element to the LI? Didn’t I write in CSS Lists: Part 1 that you’re supposed to keep the width
property to the a element and the DIV? I did, and for good reason: this specific list will function one way
in Explorer 6, and another in Firefox and Explorer 7. This is because Explorer 6 does not implement CSS to
exact standards. Let’s first go over how the CSS standard browser “sees” things: Think about it like boxes
within boxes. If you define the inner box to a certain size, you dictate the outer box to at least that size.
Remember that since the a elements have the property of display: block, that they will take up
however much horizontal space that they can. Now consider that the a element is the one which dictates
the width, and the LI elements wrap around it—that would mean that the LI elements would have to take
into consideration all of the a element’s margins and borders, something that not all browsers do well.
Instead, we define the LI element’s width, and let the a element “flow” within it, taking up however much
space it needs, like pouring liquid into a specific-size container. This is easier for the browser to calculate
and render. This, again, has to do with the Box Model, as was mentioned in the previous article.
Internet Explorer 6 doesn’t support CSS standards fully, and renders things differently: Even though the
a’s property of display was set to block, the link’s active area will only react when the cursor touches the
text itself, not the entire list item. In fact, the oddity goes further—if you’ve assigned border reactions to
the a:hover (and we did), they will indeed take effect, but only if you trigger them by moving the cursor
over the link text itself.

Quite a few of you reading this are probably thinking to yourselves: “if this is some experimental future-
standards thing that isn’t applicable today, why didn’t you say so earlier?”... Well, because it isn’t. The the
above “mix” of properties is already implemented on many sites, for 3 main reasons:
• Even though it does not render exactly the same on the two latest versions of Explorer, both
versions render it acceptably. Even if you have no conditioning for alternate CSS when a different

Anish Varghese Page 28 10/17/2008


browser is encountered, it won’t “break” the page (and you could condition different style sheets
for the two different browser versions, if you really wanted to, in which you’d use the stricter set
of rules).
• You can always condition to have the browser load a different CSS file if a completely non-
supporting browser is encountered. In the meantime, why deny supporting browsers the most
effective manner of achieving the goal, using standard CSS?
• Generally, when you code for the web, you code for the most commonly supported standards,
slightly biased upwards, and then make sure that your design ‘downgrades’ gracefully. This way,
you’re giving users of modern browsers a better user experience, without hindering users of older
browsers. This does not, mind you, take into account mobile browsers, at least not the
nonconforming ones. The Opera browser, on the other hand, used on many non-PC devices, is
highly standards compliant, and is usually easier to code for than Internet Explorer versions.
Now let’s design a list that’s close in terms of outcome, but is more lenient on CSS standards. What would
we have to do in order for it to render exactly the same in all major browsers? Well, first, we’d use the
rule mentioned in CSS Lists: Part 1 -- assign a pixel width property to the DIV, and the a elements. Since
we’re not going to be assigning anything to the LI’s width property, there’s no point in adding a border to
it, because its width will be dictated by the a elements, which will cause problems if we try to outline it
(remember the boxes within boxes problem?). So how close can we get, if we have to change so much?
This close:
• List Item 1
• List Item 2
• List Item 3
Well, as you can see, one “layer” of detail had to be removed. Of course, we’re still using the original
HTML code—we could add HTML in order to achieve the goal, but then, we could just as well use tables
and burden the browser further. We’re trying to maximize our gain from lists and CSS, so for now, we’ll
stick with the original HTML. Before moving on to additional functions, let’s see a couple of additional
design options. First:
• List Item 1
• List Item 2
• List Item 3
Two new tricks were employed for this list. The first was to apply a different margin-left for the hover
mode, in order for the items to indent when they’re touched by the cursor. The second was to add a
border-left of a different thickness under the same condition. This adds a strong sense of selecting links,
since it appears like pulling tabs. This list won’t have any problems with Explorer 6, since it styles the a
element, and leaves the LI element alone. Here’s the complete CSS of the above list:
.list_container ul { margin-left: 0; padding-left: 0; list-style-type: none; font-size: 12px; line-height:
14px; font-family: Trebuchet MS, sans-serif, Arial, Helvetica; } .list_container a { display: block; width:
200px; padding: 1px; padding-left: 10px; background-color: #55F; border: 1px solid #005; margin-
bottom: 2px; margin-left: 0px; margin-right: 24px; } .list_container a:link, .list_container a:visited
{ color: #FFF; text-decoration: none; } .list_container a:hover { border: 2px solid; color: #00A;
background-color: #FFF; border: 1px solid #080; border-left: 15px solid #080; margin-left: 10px;
margin-right: 0px; }

A few things to note: When assigning specific margin values, or specific border values, make sure you
have a constant sum of values for the top/bottom, and for the left/right. If you don’t, the overall object
will actually change size. So why does the a element start with a margin-right of 24px? Because of the
potential margin plus the potential border. It starts off with just a 1px uniform border, so the object
moved 1 pixel to the right (because it is left-aligned). If you were to move your cursor over it, it would
increase its border-left to 15px, and its margin-left to 10px, a total of 25. So again, why 24 instead of
25? Because of the initial 1 pixel border—it’s counted in as part of the left/right sum. When the link is in
hover state, the margin-right is reduced to 0.
And now for something completely different:
• List Item 1
• List Item 2
• List Item 3
Images were expected at some point, weren’t they? This is the exact same HTML as the rest of the lists,
the only thing that’s changed is the use of images. In fact, this is a mild implementation of them—you can
achieve all sorts of effects using filters. Also there’s no position change, which, when using images, can be
used to create effects like pushing buttons or flipping switches. Here’s the CSS:

Anish Varghese Page 29 10/17/2008


.list_container_f { } .list_container_f ul { width: 140px; padding: 5px; margin-left: 0; padding-left: 5px;
padding-right: 5px; padding-top: 15px; padding-bottom: 15px; list-style-type: none; font-size: 12px;
line-height: 15px; font-family: Trebuchet MS, sans-serif, Arial, Helvetica; border: 1px solid #000;
background: url(‘wall4.jpg’) no-repeat; } .list_container_f a { display: block; font-weight: bold; width:
130px; padding: 1px; border: 1px solid #000; margin-bottom: 3px; background: url(‘wall2.jpg’) no-
repeat; text-indent: 50px; } .list_container_f a:link, .list_container_f a:visited { color: #FFF; text-
decoration: none; } .list_container_f a:hover { color: #FC0; border: 1px solid #FC0; }

As you can see, the UL element was heavily styled this time. It was given a background of its
own, and a 1px black border. Notice that its padding properties were addressed individually,
giving the UL area 5px horizontal padding, and 15px vertical padding. This padding had to be
accounted for in the width property, however—you’ll notice a 10px gap between the LI and the
UL elements. Also notice that the text-indent property was used to push the text to the right.
This is very convenient, since it leaves the padding and margin properties alone, which means
you don’t have to deal with the implications of setting them. What implications? Well, add
margin-left: 30px; to the a element. Then load the page in both Explorer 7, and Firefox.
Explorer will assume that you want the a elements to remain within the LI elements, which you’d
like to keep within theUL element. Firefox, on the other hand, assumes no such thing. It will
simply shift the a elements 30 pixels to the right, and the UL and LI elements will stay right
where they were prior to the change. This is just one of many disagreements between the
browsers, but don’t worry, if you find a disagreement between Explorer 7 and Firefox, there’s
usually a straight-forward way of mending the problem (unlike, for example, a rendering
difference between Explorer 6 and Firefox). Though these problems will crop up every now and
then, they’re worth the extra work of finding solutions for them: the reward is very little code
that defines a lot of details, and renders very easily (and quickly) in the viewer’s browser.

In future documents, I’ll expand on how additional HTML elements can be styled within lists while
maintaining the same course of containing the entire navigational area within one selector class.
I’ll give examples of horizontal lists, which are very useful, and have a special affinity for
background images and buffers due to their fixed height (you can guess where I’m going with
this, since the line-height doesn’t change...).

Until then, happy experimenting!

CSS Lists: Part 3 - Horizontal Lists


In this installment of CSS Lists, we’ll go over the always-handy horizontal lists. It’s recommended that you
at least read CSS Lists: Part 1 so that you understand how to transform static lists into dynamic
navigational components.
Horizontal lists differ from vertical lists in several ways, but in order to fully understand that, we need to
understand how they’re ‘made horizontal’. Oddly enough, all you need to do is to set the display property
value of the LI elements to inline. Well, that’s not all you’re going to want to do, but that’s the crux of it.

Here’s what I mean:


• List Item 1
• List Item 2
• List Item 3

That was a plain list. No properties were assigned to it. Now I’ll add the following CSS:
.horiz li { display: inline; }

After applying just that rule, here’s the same list:


• List Item 1
• List Item 2
• List Item 3

As was done in previous installments of CSS Lists, I’m wrapping the list with a DIV element, and styling it
and its descendant elements. The HTML/XHTML I’m working with is:

Anish Varghese Page 30 10/17/2008


<div class=”horiz”> <ul> <li><a href=”#”>List Item 1</a></li> <li><a href=”#”>List Item 2</a></li>
<li><a href=”#”>List Item 3</a></li> </ul> </div>

The next thing to do is to remove the “vestigial” inherent list properties, which means removing the
margin, padding, and list-style-type property values (by ‘removing’ I of course mean either resetting to 0
or none). While I’m doing that, I might as well set the font-family, font-size, and line-height property
values:
.horiz ul { margin: 0; padding: 0; list-style-type: none; font-family: Georgia, “Times New Roman”, Times,
serif; font-size: 14px; line-height: 17px; }

The list now looks like one stack of inline elements, which, in a way, it is:
• List Item 1
• List Item 2
• List Item 3

If you remember the sequence of steps from CSS Lists: Part 1, you know that I’ll now start messing
around with the A elements. However, one of the big differences between the lists I’ve demonstrated so
far, and horizontal lists, is that horizontal lists don’t have the same link width for each link. While this is a
mixed blessing, it’s more of an advantage than a disadvantage, since you waste less space on your page
overall.

Starting with the basics:


.horiz a { padding: 2px 1em 2px 1em; background-color: #a75355; } .horiz a:link, .horiz a:visited
{ color: #FFF; text-decoration: none; } .horiz a:hover { }

Here’s how the markup renders now:


• List Item 1
• List Item 2
• List Item 3

What’s unexpected, was that there would be any space between the list elements. Remember though, that
they’re inline elements now, which means that they’ll act like ones, and treat white spaces, which include
newlines, as, well, spaces... This requires a tweak to the markup:
<div class=”horiz”> <ul> <li><a href=”#”>List Item 1</a></li ><li><a href=”#”>List Item 2</a></li
><li><a href=”#”>List Item 3</a></li> </ul> </div>

If you’ve been around since the olden days of image stacking, you’ll recognize this trick as “tag breaks” or
“in-tag newlines”. There was a need to remove the newlines between the LI tags, so the first thing you
would think of doing is just placing them all in a row. This works, but makes for extremely un-
maintainable markup, especially when you have 8 list items and 8 corresponding link URLs. However,
neither HTML, nor XHTML, mind if there’s a newline within a tag. This lets us close the ending LI tags the
line after they open.

Here’s the result of that tweak:


• List Item 1
• List Item 2
• List Item 3

If you do want spaces between the list items, you’d usualy use the margin property instead of white-
spaces. We’re not barbarians, you know...
As well, I didn’t find the room to comment about the usage of the padding property in the A element style
rule until now. It’s the usual ‘top-clockwise’ shorthand syntax, but unlike vertical arrays, I had to pad all
sides. This is because, just like the LI elements, the A elements are also inline, which means that they’ll
take not a pixel more than they need to render (unlike block-level elements, which will take whatever
horizontal space you give them). This meant that I needed to pad their right side by the same amount as I

Anish Varghese Page 31 10/17/2008


padded their left side (I say “need” loosely, since you can really do whatever you wish that suits your
design).

Now to give them some hover reactions:


.horiz a { padding: 2px 1em 2px 1em; background-color: #a75355; border-right: 1px solid #693334;
border-bottom: 1px solid #693334; } .horiz a:link, .horiz a:visited { color: #FFF; text-decoration: none; }
.horiz a:hover { background-color: #bc787a; color: #FFF; }

Nothing new here. I just gave the :hover state a slightly brighter color. I also added some borders to the
links for spice. Here’s how the list looks now:
• List Item 1
• List Item 2
• Very Long Link
• Short

Before I move on, I should mention this little neat feature: you can center the list by centering the text of
the UL element. That is to say, by adding this:
.horiz ul { text-align:center; }

This is the list you’ll get:


• List Item 1
• List Item 2
• Very Long Link
• Short

Why would that happen? Well, now that every element that’s a descendant of the UL element is inline, it’ll
be effected by the text-align property. And remember that this rule selects the UL element, not the DIV,
so you can still throw things in there and have them unaffected by the centering.

If you consider the usage of horizontal links, they’re often used to guide the visitor around the broad
sections on the site. They also sometimes act as guides to where the visitor currently is. Look at the
following style rule:
.arbitrary { border-width: 5px 3px 5px 3px; border-style: solid; border-color: #bc787a; }

Now look at the following implementation:


<div class=”horiz”> <ul> <li><a href=”#”>List Item 1</a></li ><li class=”arbitrary”><a href=”#”>List
Item 2</a></li ><li><a href=”#”>Very Long Link</a></li ><li><a href=”#”>Short</a></li> </ul>
</div>

And finally, how it looks in practice:


• List Item 1
• List Item 2
• Very Long Link
• Short

This can be a means of tagging the page the visitor is currently visiting. You’re styling one specific LI
element and adding, in this case, border properties to it. Note how much larger the top, and the bottom
borders had to be made, however. This, again, relates to all of these elements being inline. The A
elements, even though they were given border and padding to, one would think, ‘inflate’ the LI elements
that wrap them, they did so only horizontally, not vertically. Thus, in order to see the vertical border
applied to the LI elements, they have to surpass the A’s element box. Once you’ve done that though,
you’re in the clear, this will render properly in Firefox, Internet Explorer versions 7 and 6, and Opera.

The subject of images in lists will likely be covered in the next installment. You’d be surprized in what
ways lists can manipulate images, and do so with relatively few properties at that.

Anish Varghese Page 32 10/17/2008


CSS Selectors: Part 1
Knowing how to apply CSS to a document takes more than memorizing all of the CSS properties and
remembering how the document flow works. Of course, you could ‘make it work’ by making a new class
for every element on your page and having a 40Bk .css file that loads along with it, but that’s not
practical, on many levels. To properly implement CSS, you need to know how to use selectors. Selectors
define type(s) of HTML element(s) the styling (whatever’s between the { }) applies to. They’re the “other
side” of a CSS style rule definition.

But First!

A prerequisite to properly implementing selectors is understanding the Document Tree. If you haven’t
already, it’s recommended you go over the Document Tree article which details how the document tree is
applied to HTML/XHTML documents.

CSS Selectors and Browser Support


The CSS Selector tells the renderer of the document (usually the browser) to which elements to apply
each CSS style rule to. There are many kinds of CSS Selectors, and unfortunately quite a few of them are
not properly supported by modern browsers.
Generally speaking, The Opera browser supports the vast majority of CSS selectors. If your CSS validates,
but it doesn’t seems to display properly on the browser you’re currently using, you can always launch
Opera and there’s a good chance you’ll see into “CSS Future”.
Next comes Firefox, and the rest of the Mozilla-based browsers. In terms of Firefox versions, since version
1.5 it’s supported most of the W3C’s recommendations of current CSS implementations (remember that
many of the specs are “recommendations”, so you can’t fault software developers for not implementing
each and every feature if it might change in the next draft), but strictly speaking, not all.
Next on the list, is Internet Explorer 7. in IE7, the IE development team had made great efforts to achieve
CSS and other standard compliance, and the results aren’t bad (this is coming from someone who’s
followed the development of IE7 through most of the Beta releases, and wasn’t expecting much from the
final version, but overall, it was better than I had anticipated, in terms of standards compliance). While
you should still check IE7 along with Firefox, for the most part, you won’t see many differences, and the
ones you do see will be relatively easy to fix, if you spot the propety that’s ‘causing the glitch’. As far as
selector support, IE7 is behind Firefox, but that’s really not the major problem.
The major problem is Internet Explorer 6. Of course, Internet Explorer 6 is the major problem for
standards compliance in general, but it didn’t skip selectors. As I describe selectors by type, I’ll note which
ones are supported by which browsers. You’ll see that IE6 is the most significant cap for most of them. We
have to take into consideration that IE6 is still in very widespread use, and will continue to be so for at
least the end of 2007 (or so the estimates tell us).
In Part 1 of CSS Selectors, we’ll only cover selectors which are supported by all of the above mentioned
browsers. Part 2 will tackle the ones with which you’ll start running into problems in.

But enough gloom and setbacks. On to selector types.

Choose how to Choose


There are multiple ways to select elements to style on the document. You have to choose how to select
the elements which you want to style, and remember that multiple style rules overlap. What this means
is, if one element is covered by more than one rule, then all of the rules that apply to it, will apply to it.
This is a very good thing, you will come to discover. The simplest example would be that you want all of
the fonts on your page to be uniform (say, Verdana), but you want different elements within the page to
have different font-sizes and font-weights. Another familiar scenario is that you’d like the text on your
page to be white, and the background to be black, but apart from that, you’re going to be using different
fonts of different sizes. This, again, is easy to achieve with selectors that select ‘overlapping’ elements.
We’ll cover more of this when we get to Selector Structuring.

Anish Varghese Page 33 10/17/2008


The Type Selector

The Type Selector is the easiest to understand, and easiest to implement selector. It applies a CSS Style
Rule to an HTML/XHTML element. For example:
body { margin: 0; padding: 0; background-color: #FFF; }

The above Style Rule applies solely to “elements” of type BODY. Incidentally, there’s only one. This is a
common way to rid the page of its variable, and browser-dependant margins (and in some browsers,
padding), and to set the background color while you’re at it. Let’s look at another type selector
implementation:
p { font-size: 0.9em; text-indent: 0.5em; padding: 2px; }

This is a common styling of a paragraph (the P element). The font-size has been set to 0.9em (or 90%)
of the parent element, a padding of 2px has been added, and a text-indent of 0.5em has been added,
which will only effect the first line of text within the block. Do you see the advantage of composing a style
rule this way? It makes no assumptions at to the font-family, or to the absolute font-size of the parent
element. It doesn’t care what the color scheme is. It applies its rules of styling to what’s relevant to it,
and it alone. This, again, touches on the subject of Selector Structuring, but why not sneak in some extra
information here an there if I can (call it standards propaganda...). Of course, this, by itself, isn’t very
useful, since it will target every single P element on the page, which is a bit unrestrained. We’ll need to
get to Descendant Selectors and Classes before we can properly select just what we want, within the
contained areas we want it.

Something which should be covered early on is multiple selection. This allows you to place multiple
selectors before a single style rule, simply be dividing them by commas:
h1, h2, h3, h4 { color: #444; }

This does exactly what you’d expect it to do. It applies color: #444; to all H1, H2, H3, and H4
elements in the document.

Universal Selector
When used by itself, the Universal Selector only appears in one way (usually, when it’s a document that’s
intended for the web), and is rather limited in use:

* { font-family: Trebuchet MS, sans-serif, Arial,


Helvetica; }
It literally selects every element in the document, so used by its own, it’s either used for very short
documents, or for Print Media CSS Documents. It does have use when used in conjunction with other
selectors, like Adjacent Selectors, but this is hindered by the old IE6 (we’ll get to that in Adjacent
Selectors, in Part 2).

Descendant Selectors
With Descendant Selectors you’re getting more specific about which elements you’re going to style.
Descendant Selectors can actually refer to Types, Universals, IDs, Classes, and Attribute Selectors, it just
means that you’re selecting by addressing the elements you want using their parents to guide the Style
Rule to its targets. Visually, this is easier to understand. We’ll start with some HTML code:
<div> <h3>Post Title</h3> <em>Post Date</em> <p>Post Contents <i>Author</i></p> </div>

The above code produces this Document Tree:

Now we’ll use Descendant Selectors to select the element types, and then their descendants, which we
want to style:
div h3 { text-decoration: underline; } div i { color: #0000CC; }

Anish Varghese Page 34 10/17/2008


H3 elements which are descendants of any DIV elements in the
The first rule is looking for any
document. The second rule is looking for any I elements which are descendants of, again, any DIV
elements in the document. Remember that they don’t have to be direct-descendants, any descendant
element that matches will be the target of that rule. In the above document, here’s what it matched:

Both the H3 element and the I element were descendants of the DIV element, and so each respective
Style Rule was applied to each element. This is getting more specific, but it’s still somewhat broad. You’ll
still need Classes and IDs to properly target (select) just the elements you want and not catch something
else in the document that happened to have the same relationship structure.

Class Selectors
The Class Selectors are the most often-used, and over-used type of selector. They’re usually the first
selector that people who are learning CSS are introduced to, and thus it becomes the one they rely on the
most. This is not without reason, however. You’re telling the renderer of the document to specifically select
an element with a specific name. No ambiguity whatsoever. However, as the person who’s designing both
the style and the structure, you can make sure that there’s no ambiguity by combining Class (and ID)
Selectors with Type and Descendant Selectors, and creating both less Markup and less Style Rules (once
again, this has to do with Selector Structuring, which will be properly covered in a separate article).

Let’s take the HTML from above and tweak it a bit:


<div class=”posting”> <h3>Post Title</h3> <em>Post Date</em> <p>Post Contents
<i>Author</i></p> </div>

This time, I’ve added a class attribute to the DIV element. Now, by combining several types of selectors, I
can achieve different goals:
.posting { font-family:Georgia, “Times New Roman”, Times, serif; } .posting h3 { text-decoration:
underline; margin: 0; } .posting p { margin: 0.4em; } .posting em { font-size: 0.8em; } .posting p i
{ display:block; color: #0000CC; }

Ok, so that might have been a bit too many Style Rules for one code block, but the big picture is
important in this case. The first rule sets the font-family of the posting class. Remember that the font-
family property is inherited, so I don’t have to worry about the rest of the elements within the DIV
element which I’ve styled with the posting class.
The next rule is a Class/Descendant rule. I’m selecting an element type which is a descendant of any
element that was styled using that specific class. In this case, I’m selecting any H3 element which is a
descendant of any element which was styled by the posting class. Any element matching this description
will be assigned a text-decoration property, and a margin property.

The third and fourth rules are just like the second. This time, they’re selecting P and EM elements, and
assigning them margin, and font-size properties, respectively.
The last rule is technically the same as the previous three rules, except I’m being very specific about
which element I want to style. I’m looking for an I element, which is a descendant of a P element, which
is a descendant of any element which was styled by the posting class. In many programming languages
this would be considered object-orientation, but here it’s more like navigating the Document Tree. You’re
basically zooming-in on your target, and making sure that nothing else gets “accidentally styled” along the
way. If there was an I element within the DIV element, but not within the P element, it would not have
been effected.

Another thing to mention about Class Selectors, is that a single element can be styled using more than
one class. It’s easier than it sounds:
.greenish { color:#009966; } .biggie { font-size: 1.2em; font-weight: bold; } <span class=”greenish
biggie”>Some Text</span>

This normally finds its uses in very large style sheets, with dozens of rules, where you have many
overlapping qualities and you can narrow things down by assigning more than one class to a single
element. This also finds use in style-sheet-switching, where you’d like to switch a color scheme, for
example. You have one .css file that sets everything but the colors for your pages. Then you have another
one that “houses” the color scheme. In that file, you don’t name color classes like “Maroon” or “Hazel”—
instead, you assign names for the various elements that will be colored by the different hues of the color

Anish Varghese Page 35 10/17/2008


schemes around the page, like “heading_color”, or “darker_comment”. Beware, however, that this leads to
bloated Markup and confusing fixes later on. You’re going to have to find a balance if you’re going to use
multiple class assignments, since it can make the whole point of CSS (separating style from structure) go
out the window if you’re not careful.

ID Selectors
ID Selectors are similar to the Class Selectors in how they operate, except that they look for the common
HTML/XHTML ID attribute. This attribute is used for other things, unlike the class attribute which is
designed for CSS use. Forms use IDs to identify value containers, and JavaScript uses them as direct
handles to elements on the document. Also, there can only be one ID of each name assigned to one
element within a document. This is simply the nature of the web standards, and isn’t CSS-specific. Using
IDs to style elements has several advantages: First, if you’re using JavaScript on elements you’re going to
style, then you’re already using IDs, so why identify an element twice? Second, if you really only have one
“thing” (that’s a technical term) of its kind on a page (let’s say, a right column), this will make sure you
don’t assign the same handle/identification to more than one element on the document.

Here’s how ID Selectors are implemented:

#sign_post_a { color: #800; } <span id=”sign_post_a”>Some Text</span>

It’s the same as Class Selectors, except with a # instead of a .. You can also use descendant selection
just like the class/type selection example above. It should be noted that IDs are commonly reserved by
designers for DIV elements and SPAN elements, although this isn’t written in stone, it’s just what you’ll
usually find when you’re looking over the source of pages with interesting CSS implementations (which, by
the way, is a highly recommended method of education).

Half-Time
That’s it for CSS Selectors Part 1. In Part 2 we’ll get into the cool pseudo-classes (a:hover!), and the
more gritty Selector Types, which aren’t really gritty, they’re simply not supported properly by enough
browsers.

CSS: Units of Measurement


When the CSS standard defines a property type as length, size, width, or height, it means a unit of
measurement. CSS Provides you with, normally, six units with which to define the size of properties (I’ll
use ‘size’ to a general definition of measurement, although you might see a property define a value type
as width, height, length, etc.). You’ll usually encounter one of four types: Pixels(px), Points(pt),
Percentages(%), and Ems(em). Additionally, there are the less-used Picas(pc), and Exes(ex). Before going
over the units one by one, please note that you can use each of these units to define the size of anything,
even if the unit itself is derived from a font’s size. You’ll have to decide for yourself which elements should
be sized using which units, but there is nothing preventing you from sizing elements using whatever you
choose.

Unit: Pixels
Pixels define an element’s size using a specific humber of pixels. This is very convenient when designing
for digital displays, since it gives you exact control over the size of the element, allowing you to make
exact calculations of width and height for your design. However, there are several downsides to using
pixels you should be aware of: First, setting a font’s size using pixel units does not allow the user to resize
that font using their browser settings. When you set a font’s size to 12 pixels, it will always have a height
of 12 pixels, regardless of what the user has set the default font size in their browser to. This is an
accessibility issue that, if you choose to use pixels to set your font sizes with, should be dealt with using
other means (for example, allowing the user to choose from two or more different style sheets). Secondly,
when it comes to print media, pixels have no real value. If you design a document for print, it’s up to the

Anish Varghese Page 36 10/17/2008


device to guess what you meant in terms of physical size. Although you can usually preview a document
and make changes before printing, if your document is primarily designed for print, then you may want to
look at one of the other unit options.

Unit: Ems
Ems are a relative measurement unit. One ‘Em’(1em) is equal to the height of the capital letter “M” in the
default font size. When applied in CSS, the Em represents either the user’s default font size, or the size of
the parent element’s font size, if one is available. When using Ems for sizing fonts, the fonts will resize
according to the browser’s default font size setting. That is, if the upper-most definition of the font size is
defined by Ems (or any other relativee unit of measurement), and every successive unit set in every
descendent element is also defined using a relative unit, then the text on the entire page will be user-
resizeable. If the parent of the element using Ems to size its fonts defines its own font size using absolute
units (such as Pixels or Points), then the font of that element will ‘snap’ to that parent’s font’s size,
instead. This means that setting descending element font sizes to Ems does not mean they will be user-
resizeable if their parent element’s font isn’t resizeable. Ems are set to decimal units, like 1em, 0.9em,
and 1.1em. These units can be thought of as percentages of the parent element, where the top-most
level is set to the browse default font size. For example, if the browser’s font size is set to ‘Normal’, then
setting the font-size of the BODY element to 1.1em will mean that the font size inside the BODY
element will be 110% the size of the browser’s ‘Normal’ font size. If the user then set their browser’s font
setting to ‘Large’, then the font size inside the BODY element will be 110% the size of the browser’s
‘Large’ font size. Now suppose that the BODY element’s font-size was set to 10px, and the P element’s
font-size was set to 0.9em. This means that any text within P elements will be 9px, regardless of what
the user set their browser’s font setting to.

Here are some examples of Ems in action. First, look at the following code:
<style type=”text/css”> <!-- .parent_elem { font-size: 28px; font-family: “Times New Roman”, Times,
serif; } .parent_elem p { font-size: 0.7em; line-height: 1.5em; width: 12em; background-color:#FFCC00;
} --> </style> <div class=”parent_elem”> The letter ‘M’. <p>Text within the P element.</p> </div>

Now, here’s the result in the browser:

The letter ‘M’.

Text within the P element.


The parent_elem class acts as a size dictating class. It sets the size of its own text in pixels, namely,
28px. The P element within it is selected and only given Em values. Note that not only the font-size and
line-height values are Ems, but also the width of the P element is set to an Em value, in this case, 15em.
Now, let’s view the same HTML, only with the parent_elem’s font-size value set to 20px:

The letter ‘M’.

Text within the P element.

As you can see, the entire P element has been resized. It was scaled down to fit the newly assigned font-
size value of 24px to the parent_elem class. By mixing Ems and Percentage values you can create a
completely scaling design, that is either defined by you, or the user’s browser settings. Remember though,
that if you want the user to be able to scale the fonts themselves, you have to allow them to control the

Anish Varghese Page 37 10/17/2008


upper-most font value, which means that every font value on the page must be relative (either an Em
value or a Percentage one).
A note about Mozilla-based browsers: Browsers like FireFox allow you to increase/decrease the text size in
a manner which will effect non-relative values. While this is arguably a convenient feature, it’s actually not
part of the standard, and should not be relied upon. Other browsers, including version 7 of Internet
Explorer, will not change the size of absolute values when you change the text size within it.

Unit: Exes
Exes are similar to Ems, in that they are a relative unit of measurement that defines 1 unit to be equal to
the size of the letter “x” in the default font size. Most other properties that apply to the Em unit of
measurement apply to the Ex unit of measurement. However, most browsers do not support this unit of
measurement properly, and it is not recommended for use in documents intended for browsers.

Units: Points and Picas


These units are print media units of measurments. A point (1pt) equals 1/72 of an inch, while a pica
(1pc) equals 1/6 of an inch. Documents intended for printed media will be able to tell the device exactly
what the intended size is for these units. Digital displays, however, will have to guess, somewhat
arbitrarily, how to convert these units into pixels, and there is no real uniform way of doing so. Since
points were used since the early days of the web, most browsers have a set relation between pixels and
points, but this is inherently wrong. Remember that small displays today can have high resolutions, so
determining how large an ‘inch on the display’ would be is almost impossible across devices. Documents
designed to be displayed primarily on the web should avoid using these units.

Unit: Percentages
When assigning percentage units (%) to a property that isn’t font-size or line-height, that value always
relates to the parent block of that element. When assigning percentage units to the font-size or line-height
properties, they act like the Em unit, where 100% equals 1em. If you set the font-size property of an
element to 100%, and that element’s parent block is the BODY element, the result will be the same as
setting the font-size to 1em—namely, the size of the text will become the browser’s default font size. It’s
important to remember that percentage values mean different actual absolute values when assigned to
the font-size and line-height properties, and when assigned to everything else. Assigning 100% to the
width property of an element is completely different than assigning 1em to it, for example.
Here’s an example of Ems and Percentage values mixed within the same elements:
<style type=”text/css”> <!-- .parent_elem { font-size: 18px; font-family: “Times New Roman”, Times,
serif; } .parent_elem p { font-size: 120%; line-height: 150%; width: 80%; background-color:#FFCC00; }
.child_elem { font-size: 0.7em; line-height: 1em; } --> </style> <div class=”parent_elem”> The letter
‘M’.<br /> <span class=”child_elem”> Text within a SPAN set to the child_elem class. </span> <p> Text
within the P element.<br /> <span class=”child_elem”> Text within the P element, within a SPAN set to
the child_elem class. </span> </p> </div>

Here’s the result in the browser:

The letter ‘M’.


Text within a SPAN set to the child_elem class.

Text within the P element.


Text within the P element, within a SPAN set to the child_elem class.

Note how the percentage values have a different effect when assigned to the width property, and when

Anish Varghese Page 38 10/17/2008


assigned to the font-size and line-height properties. Also note how the child_elem class renders differently
when it has different parent elements.

Decisions...
It will be up to you to decide which units to assign to which properties, and to take into consideration
accessibility, media type, different display resolutions, and compatibility, among other things. As a general
rule, if you don’t assign relative-only values to all of your fonts, you should provide a means to change the
style sheet for your pages, so that the font size may be changed by the user. Also remember that when
designing a page that will fit the entire browser window, to mind each element’s size in terms of whether
it’s relative or not, since stretchable designs can ‘break’ in certain resolutions if their elements weren’t
matched properly along the way.

Floating Elements
A commonly misunderstood, and highly underrated property of CSS is the float property. The ability to
float elements has been around since earlier in HTML’s life, but has been cemented in CSS in terms of
rules of implementation, even if not all browsers implement floated elements properly when they’re
presented with an overly complicated scenario.
The broad definition of “float-ing” an element is that you assign that element a certain amount of the
horizontal space (width) within its containing block, and tell it to allow other content to flow down the right
or left edge of it, instead of it taking up all of the horizontal space that it would usually take up. The most
common example is the IMG element: If you were to place text within a document, followed by a BR,
followed by an image, followed by another BR, and then followed by additional text, the image would take
up however much vertical space it needs, and all of the horizontal space to its right (assuming the
document is left-aligned) will be wasted. If you were “to float” that image to the left, it would allow
content to flow along its right edge, and the browser (or whatever happens to render the document) will
take care of spacing this text for you so that it will align, wrap, and fill the area properly. But this is just
one very common, very simple scenario. The float property allows you to structure many elements around
the document, and is much more powerful that most people give it credit for.

The Browser Compatibility Anthem

I’ll get browser compatibility out of the way before I delve into the subject, to solve the “should I even be
reading this if it’s not properly suppoorted across every browser ever?” question thing. Floating elements
is an old trick, it’s just being applied to new elements as designers/developers realize that the majority of
browsers support this. It used to apply almost exclusively to images, at least in practice, and you’d see a
mention every now and again that you can float “any block” (followed by sarcastic comments like “Yes!
It’s the World of Tomorrow!”). Today, you really can float any block, and even Internet Explorer 6 will
accomodate most scenarios. If you round up IE6, IE7, Firefox, Opera, and Safari, you get around 99.8%
of the browsers out there (according to current statistics). Even if there’s a shift in browser usage, it’s not
going to be in favor of an older, less compliant browser. Whatever your views are in terms of “who’s
gaining” in the browser wars, it doesn’t matter—all of the latest versions of the aforementioned browsers
have better support for Web Standards and it’s not like one of them is going to start ‘removing support’ as
part of its roadmap.
That said, there are always some creases, since it wouldn’t be fun if things ‘just worked’... However, they
aren’t broad enough for me to round them up in a paragraph, but rather they’re scenatio-specific, which is
why whenever something doesn’t work along the way, in whichever browser, I’ll alert the bells. You’ll
notice, however, that these scenarios are rather specific, easily avoidable, and hardly make floating
elements any less of a powerful tool even if you were to steer clear of them completely.

Floating (verb.) elements


Let’s start by clearing up what applying the float property does to the element itself. The first thing you’ll
notice when floating an element is that it becomes a block-level element. This isn’t completely clear in the
CSS 2.1 spec, but you will find that when you apply the float property to an element, all browsers, with
vitrually no exceptions, will turn them into blocks. You can test this by applying properties that effect
block-level elements diffently than they effect inline elements.

Anish Varghese Page 39 10/17/2008


Here’s some markup along with CSS to test this with:
<style type=”text/css”> .test_properties { width:150px; background-color:#99CCFF; padding: 5px 10px
5px 10px; border: 1px solid #3E95EC; } .make_it_float { float:left; } </style> <span
class=”test_properties”> Magnesium is the chemical element in the periodic table that has the symbol Mg,
the atomic number 12, and an atomic mass of 24.31. </span> <br /><br /> <span
class=”test_properties make_it_float”> Magnesium is the chemical element in the periodic table that has
the symbol Mg, the atomic number 12, and an atomic mass of 24.31. </span>

Two style rules were created: test_properties was given four properties, three of which appear
differently when applied to inline elements than they do when they’re applied to block-level elements
(these would be the background-color, padding, and border properties), and also the width property which
is ignored by inline elements. The second rule, make_it_float, just applies the float property value of
left to an element. Then, there are two paragraphs, one which is styled by just the test_properties
class, and the other which is styled by both. Actually, when I say “paragraph”, I don’t mean the P
element, since that element is inherently a block-level element—I mean SPAN elements with “a
paragraph of text” in them.

Now to see how the two ‘paragraphs’ render:

Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12,
and an atomic mass of 24.31.

Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12,
and an atomic mass of 24.31.

There would have been no difference if the second SPAN element had its display property value set to
block, instead of being applied a float property. The reason for the element becoming a block when being
floated has to do partially with its need to have a set width property (in fact, this is the primary reason).
This, again, isn’t made completely clear in the CSS 2.1 specification, but it is, this time, made clear in
code implementation, rather than browser/renderer implementation. While you can apply a float property
to an element without that element having a set width value, you’ll simply get no consistent results. The
element can have a width value either inherently as part of the element’s definition, like IMG elements,
some elements may have the width HTML/XHTML attribute set, or you can set the CSS width property
value. Any one of these will tell the document renderer that there’s either an absolute width value, or a
relative width value to be calculated, but in both cases there’s a value to work with in terms of absolute
units after all of the calculations are done (units is a generic term here, since pixels are relevant to a
display device, whereas a printing device might use dots or other types of units of measurement).
What else does applying the float property to an element do to the element itself? It aligns it either to the
left, or to the right, within its containing block, depending on the value you’ve set. This isn’t exactly like
aligning elements, since it will react differently to other floating elements, for one thing, but in many
cases, it will, in most respects, have the same effect.

Here’s a simple example:


Containing Block: a DIV with a border and a set height.

Float A Floated: Right


To start to actually see how floating an element works with other elements, it’s practical to test how it
works with other floating elements of the same type. Here’s what happens if you take that last element
and append elements of the exact same type right after it:
Containing Block: a DIV with a border and a set height.

Float A Floated: Right Float B Floated:


Right Float C Floated: Right

Anish Varghese Page 40 10/17/2008


Note that the elements appear in the markup as Float A though Float C (Float A precedes Float B, which
precedes Float C), meaning that they actually stack to the right. We’ll get to the markup in a bit, right now
we’ll stick to the abstract so that code doesn’t clutter the concepts (This would be a complete oxymoron in
a programming language, to say that code “clutters” the relating of ideas, but we’re talking about how a
browser/renderer interprets visual definitions, which is why if I were to place markup after each example
at this point in the document, it would just distract from the goal. There’ll be plenty of code to work with
later).

Floating objects will continue to stack until there’s ‘no more width’ to contain them. That is, they’ll keep
trying to appear horizontally, aligning to whichever side they’re floated to, until the containing block can
no longer contain any more of them in its calculated final width. At that point, they’ll go to a new line and
begin again:
Containing Block: a DIV with a border and a set height.

Float A Floated: Right Float B Floated:


Right Float C Floated: Right
I should note at this point, that I’m giving the example of multiple floating blocks because it is
instrumental in explaining how floating elements behave. This doesn’t at all mean that in order for you to
have one block-level element appear horizontally after the other, that both need to be floated—only one
does. If you want to stack them horizontally, however, then you would need to, depending on how you
want to arrange them, float more than one of them.

Rules of Engagement
Now let’s talk implementation. You want to float an element, meaning that you want a block of content to
have other element/s to flow to the left, or to the right of it, instead of it monopolizing the entire
horizontal space to its right/left. There are several things that you need to consider in your
implementation.

The first rule of FloatClub is...

Floating elements must have a set width. Their width may be set inherently, like in IMG elements, they
could be set by the width HTML/XHTML attribute, or it may be set using the CSS width property—but in
some way, the element that’s being floated must have a width to ‘report’ to the browser/renderer. This is
the way the browser knows how much width to allocate to this element, and how much width is ‘left over’
for the other elements to flow through.

Above, Below, and Beyond

Floating elements allow elements that follow them (elements that come after them in the document) to
flow beside them. They do not effect preceding elements (anything that came before the floating element
within the document). There are actually a few exceptions to this, but they are limited, and I’ll make note
when they’re encountered.

Ducks in a Row

Before delving into a maelstrom of examples, let’s have a look at the plan of attack:
So we have a simple enough set of guidelines:
• The floating element will be ‘aligned’ either to the left or the right edge of the containing block.
• Elements that follow the floating element will ‘measure’ the remaining horizontal space from the
floating element’s available edge to the containing block’s other edge.

Anish Varghese Page 41 10/17/2008


• If the following elements fit within this space, they will be moved upwards in the document to
occupy this space. This applies to all elements that will fit within this horizontal space, until the
vertical space that is equal to the floating element’s height is filled.
• At this point, elements will continue to flow as usual within the document.

Less Talk, More Markup


Let’s first make up a block-level element we can play around with easily:
<style type=”text/css”> .square { display:block; width:65px; height:65px; background-color:#FFCC33;
border: 2px solid #FF9933; margin:5px; padding: 5px; } .float_left { float:left; } .float_right
{ float:right; } </style> <span class=”square float_left”></span> <span class=”square”></span>

The square class makes a 65px wide by 65px high square with background-color, border, margin, and
padding properties out of a SPAN element easily so we can throw them around and experiment. They’re
assigned a display property value of block because they won’t always be floating, sometimes they’ll just
be plain old blocks laying around.

Remember that the idea here is that this floating SPAN (you can use a DIV, it depends on what you
want it to contain) can be an image, it could be holding a paragraph of text, it could contain a list, or a
table, or just about any combination of elements. Obviously, it wouldn’t be this size, but the idea is that
you take a block-level element and float it to achieve a structural goal.

We’ll also define a containing block class so we can more easily see the borders that wrap what we’re
containing:
.containing_block { border: 2px solid #FF9933; padding: 5px; font-size: 12px; line-height: 1.2em; width:
250px; }

Floating block followed by text

Thist is most commonly used when floating an image, but this time we’re floating a generic block, so you
can really replace its contents with anything:

Copper is a chemical element in the periodic table that has the symbol
Cu and atomic number 29. It is a ductile metal with excellent electrical
conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of
various alloys.

The marup for this is very simple:


<p class=”containing_block”> <span class=”square float_left”></span> Copper is a chemical element in
the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal with excellent
electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building
material, and as a component of various alloys. </p>

If you were to apply the float_right class to the square instead, you’d get the following:

Copper is a chemical element in the periodic table that has the symbol
Cu and atomic number 29. It is a ductile metal with excellent electrical
conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of
various alloys.

Anish Varghese Page 42 10/17/2008


You can also float a block within a paragraph. Here’s an example:

Copper is a chemical element in the periodic table that has the symbol
Cu and atomic number 29. It is a ductile metal with excellent electrical
conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of
various alloys.

Tin is a chemical element in the periodic table that has the symbol Sn
(Latin: stannum) and atomic number 50.

Here, the square is nested within not only the P element, but it’s within the text itself. The Marpup for this
is very simple, the square was just moved within the text itself:
<p class=”containing_block”> Copper is a chemical element in the periodic table that has the symbol Cu
and atomic number 29. It is a ductile metal <span class=”square float_left”></span> with excellent
electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building
material, and as a component of various alloys. <br /><br /> Tin is a chemical element in the periodic
table that has the symbol Sn (Latin: stannum) and atomic number 50. </p>

Now suppose you have something like a list of objects, each with its own icon or thumbnail, and a short
line of text under it. This is a common scenario when you’re designing a control-panel-like design, or
simply a list of thumbnails. Now suppose that you don’t know how wide the area containing these
elements will be, and in fact, that the size of these elements might change (if they’re image thumbnails,
you may want to give the user the ability to change their size).

That’s perfect for “float-stacking”:


I’m going to place some text in here that will flow, or rather ‘spill’, along the right side of the squares...

Now that wasn’t expected... Actually, it was expected, but it wasn’t what we wanted. At this point, it’s
time to introduce float’s partner-in-crime: clear.

Clear for Takeoff


At some points, you’ll want some way to tell the document renderer to stop letter content flow around a
floated element. There are many reasons for this, and you’ll see more of them in the following examples.
You do this by using the clear property. When you apply the clear property to an element, you can choose
to give it a value of left, right, or both. This tells the element not to allow content to flow around a
floating object that appears previously in the document. For example, clear: left; means that if this
element sees a floating element preceding it that was floated to the left, it will ‘resist’ flowing alongside
that element, even if it does fit within the flowing space. You can imagine, then, that float: both; means
that the element will stop flowing from any direction, in practice becoming a “floating stops here” element
within the area of the document where it appears (because any element that follows it will follow the
element with the clear property, which means that it will no longer have a floating element preceding it).

Combining float and clear will allow you to create amazing structures with ease, but let’s start with the
basics:
Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29.

//Stop Floating//
It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical
conductor, thermal conductor, as a building material, and as a component of various alloys.

Anish Varghese Page 43 10/17/2008


This was a simple example of how you would use clear to stop the flow of content around a floating
element. Here’s the markup:
<div class=”containing_block”> <span class=”square float_right”></span> Copper is a chemical element
in the periodic table that has the symbol Cu and atomic number 29. <div style=”clear:both;”>
<b><i>//Stop Floating//</i></b> </div> It is a ductile metal with excellent electrical conductivity, and
finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a
component of various alloys. </div>

The DIV up there was styled inline, rather than having a class applied to it, which is typical if you only
have just one property you want to apply. Actually, that DIV (without the text in it, of course) is
something you’ll see quite a bit if you go around looking through source markup of pages that float
elements. This is because while you can apply a clear property to any element, it’s very convenient to just
have an empty DIV that ‘clears floating’ from a certain point onward. In other words, you could apply the
clear property to the element that follows the floating element, but you never know what element that will
be, and if you’d need to modify it further because of other properties it may already have.
By placing <div style=”clear:both;”></div> at a location in the document, you know when you
look at it what it’s there for, and it’s easy to maintain later if you want to make modification to your
structure. You have to remember, though, that it’s a DIV, which means that you’re going to want to make
sure you’re within another DIV element to begin with (there’s a simple solution to non-DIVs, I’ll get to it
in a moment).

Let’s fix that floating stack example from earlier:


No float for you!

In the above example, the clearing DIV was placed after the last floating element, after which there’s no
need to worry about the floating effecting any other elements.
But what about when you’re not floating an element within a DIV? A DIV is ‘high up’ in the element
hierarchy, and without going into too much detail about how browsers render pages, we already know we
can’t just throw DIVs within P elements without expecting trouble, even though they’re both block-level
elements. No worries—all we need is an element that’s block-level, and clears both sides, so we’ll make it:

<span style=”clear:both; display:block;”></span>

That was the ‘clearing SPAN’. You can place it within P elements, within other block-level SPAN
elements, and within DIVs. So the question is, when to use a clearing SPAN and when to use a clearing
DIV?... Technically, you can use the clearing SPAN anywhere and it should perform just like any of the
two. However, browsers will be browsers, and so there’s a simple rule you may want to follow: If you’re
directly within a DIV, use the clearing DIV. Otherwise, use the clearing SPAN. The reasoning is simple:
If you’re already within anotherDIV—and by this I mean you’re directly under it, not within an element
that is nested within a DIV—you know that placing a DIV won’t disrupt the styling of the parent DIV.

Clearing Above

Clearing will also get you out of some interesting browser incompatibilities. Let’s look at the following
markup:
<p class=”containing_block”> Alpha <span style=”float:right;”>Beta</span> <br /><br /> </p>

Here’s how this renders:

Alpha Beta

If you’re using anything but Opera to view this page, then the word ‘Alpha’ appears above the word ‘Beta’.
According to the CSS 2.1 Specification, the two words should appear on the same line. This is subtle, and
in fact technically makes the floating element effect the element above it. According to the specification,
this will only go as far as one box level above the floating element, or any of that elements descendants.
That makes it very subtle, but it’s still valid within the specification, and the Opera Browser implements it

Anish Varghese Page 44 10/17/2008


correctly.
This is actually unlikely to appear in upcoming browser implementations other than Firefox (Internet
Explorer has a lot to go before it reaches this point of compliance accuracy), so you may think you should
just let it go. But there’s no reason to penalize Opera users because their browser sticks to the rules this
well, especially if fixing the problem is as easy as it is: Just clear above the floating element. Yes, it’s that
simple—if you clear above the floating element, you’re telling any and all browsers: “I don’t care about
how compliant you are, I know what I want, and I especially want my page to show up the same way
across all browsers!”. Ok, so that was a bit broad for this specific fix... Let’s rephrase—You’re telling the
Opera Browser: “Don’t look up.”. Remember though, other browsers may implement this feature sooner
than you think, so clearing above floating elements will make sure your design is future-proof in this
particular respect.

Basically, you’d do this:


<p class=”containing_block”> Alpha <span style=”clear:both; display:block;”></span> <span
style=”float:right;”>Beta</span> <br /><br /> </p>

It looks like this:

Alpha Beta

If you’re not using Opera, you shouldn’t see any difference. If you view this page using the Opera browser,
the word ‘Alpha’ now appears above the word ‘Beta’, just like it does in other browsers. I should mention:
If you haven’t yet, Opera is free and cross-platform, so there’s no reason not to go and download it for
checking your pages using an additional browser. If you’re designing pages and care about cross-browser
compatibility, then there’s no reason not to have both Firefox and Opera installed on any computer so that
you can check your pages as you’re designing them. Both browsers are a free download, and they both
work on Windows, Mac, and Linux (and BSD, etc.). I’ll even save you the typing: Firefox and Opera.

Bigger Picture
Let’s wrap up by applying float and clear to a mini-document.
We’ll start with the HTML/XHTML:
<div class=”mini_doc”> <h3>Mini Title</h3> <p> ... A whole bunch of text... </p> <br /> <ul>
<li>Copper</li> <li>Tin</li> <li>Zinc</li> <li>Antimony</li> <li>Magnesium</li> </ul> <span
style=”clear:both; display:block;”></span> <span>This is a Footer</span> </div>

Next, we’ll setup some CSS style rules:


.mini_doc h3 { padding: 2px; border-bottom: 1px solid #888; } .mini_doc p { margin: 10px; width:
300px; float: left; padding-right: 15px; } .mini_doc span { display:block; text-indent: 2em; background-
color:#CCCCCC; padding: 2px; }

Here’s what we get:

Mini Title
Tin is a chemical element in the periodic table that has the symbol Sn (Latin: stannum) and atomic
number 50. This silvery, malleable poor metal that is not easily oxidized in air and resists corrosion, is
found in many alloys and is used to coat other metals to prevent corrosion.

Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a
ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of various alloys.

Anish Varghese Page 45 10/17/2008


• Copper
• Tin
• Zinc
• Antimony
• Magnesium

This is a Footer

That was actually one of many ways to create a table-less layout, but that’s another topic altogether. The
main paragraph was given a width and floated to the left, making room on its right for content to flow.
The list found that room to be sufficient and flowed in, but the footer was something that needed to be
kept under the whole thing, so a clearing SPAN was placed under the list. Apart from that, the heading
was given a border and padding, the footer was given a background-color, padding, and text-indent. The
main paragraph also had its margins overridden (a P element usually generates margins above and below,
and none to the sides).

Believe it or not, this was actually tame coverage of the floating feature. There are countless ways to
‘hack’ the float property to achieve all sorts of amazing things, if you’re willing to create different style
sheets for different browsers. The information in this article should give you plenty of new structuring
ideas to play with though, without having to go into grey areas. There’s a lot of experimentation to be
done with the float property, and checking your results in different browsers is a must in this case.

Happy Floating!

Styling Forms
Form and Function
Forms are notoriously rebellious when the time comes to dress them up in eveningwear. Usually, when
you’re both the server-side programmer, and the client-side designer, by the time you get your PHP to play
nice with your MySQL, and your JavaScript to properly validate the form using Regular Expressions, you
haven’t got a single drop of sweat left to spare for making things pretty. But then, what does your user
see? Your user expects you to at least be competent enough for everything to work flawlessly, that’s a
given, it’s not like they’re going to go over your code and say “now there’s some elegant problem-
solving”... No, they judge your pages by what they see, and you bet that even a visitor that doesn’t know
what HTML stands for will be able to tell you if a form looks, feels, and behaves, like what they’d expect
from a modern website. They may not know the first thing about web development, but any user that’s
been online for more than 2 months—is an expert at filling forms.
Let’s face it, until personal data is properly standardized in such a way that with a few clicks we can
choose, on a sliding scale, exactly how much data, and which type of data, we let the website we’re
visiting have, we’re going to be building, and filling, a lot of forms.

And once again, CSS to the rescue!


In the case of form elements, using tables seems almost inescapable. How else are you you supposed to
line up what is clearly tabular-esque data? Actually, XHTML does provide you the tools to arrange text and
fields properly, but you need the right combination of tags and CSS to create a good-looking form with no
tables, and only a single DIV.

First, let’s look at the initial form we’re going to be working with:
Customize your Avatar

Eye Color:

Anish Varghese Page 46 10/17/2008


Hair Color:

Gender: Male Female

Avatar Class:

As you can see, it includes textboxes, radio options, and a select box. It also has an outline, which isn’t
the cause of any styling, but rather the effect of the FIELDSET tag (explained below). The gender option
selection area is italic, and that too isn’t the result of styling, but rather another tag—the EM tag this
time.

Let’s clear the whole thing up by going over the XHTML that makes up the form:
<div id=”theform”> <form action=”#” id=”form_nameb”> <fieldset> <legend>Customize your
Avatar</legend> <p><label for=”random_field_one”>Eye Color:</label> <input type=”text”
id=”random_field_one” name=”random_field_one” /></p> <p><label for=”random_field_two”>Hair
Color:</label> <input type=”text” id=”random_field_two” name=”random_field_two” /></p>
<p><span><em>Gender:</em> <input type=”radio” name=”gender” value=”male” checked=”checked”
/> Male <input type=”radio” name=”gender” value=”female” /> Female</span></p> <p> <label
for=”avatar_class”>Avatar Class:</label> <select name=”avatar_class”> <option>JavaScript
Juggler</option> <option>CSS Sorcerer</option> <option>PHP Phantom</option> <option>Perl
Prowler</option> </select> </p> <strong> <input type=”submit” value=”Submit Form” /> <input
type=”reset” value=”Reset Fields” /> </strong> </fieldset> </form> </div>

Before moving along, there are 3 tags in there that aren’t that widespread, so here’s a quick refresher of
what they do:
• <LABEL>: The LABEL normally encases plain text. Its for attribute associates it with either
an INPUT, a SELECT, or a TEXTFIELD’s id. Browsers react differently to LABELs, but the
id that matches the
desired effect is that when the labeled area is clicked, the form field with the
for attribute’s value will gain focus. This works in modern browsers, but the feature should not
be counted upon for any scripting purposes. We’re using the tag here mainly for its compliance
with the standard structure of a form, and, of course, to shower it with CSS properties.
• <FIELDSET>: The FIELDSET simply groups form items. Unstyled, it has the very basic
LEGEND.
visual effect of a single-pixel black border. It also “has” the directly-related tag:
• <LEGEND>: The LEGEND is quite odd for XHTML. It must appear right after the opening
FIELDSET tag, and though it’s supposed to contain only text, it encases it instead of having it
as an attribute value. One wonders why the FIELDSET doesn’t simply have a LEGEND
attribute—possibly to allow us to style them separately, and we certainly will.

Now that we’re up to date, look over the structure of the above form. There may not be tables, but there
sure are a lot of wrappers up there. The form itself is encased with the DIV we’ll be styling. It also
contains, right within it, the FIELDSET and LEGEND elements, so you can mentally put those aside for
now. What you’re left with is the section for each input element/group: two separate textboxes, the dual-
radio buttons, and the SELECT box. There’s also the submit and reset buttons which are encased with
STRONG elements.
The textboxes each have a LABEL next to them (actually, preceding them), and associated with them.
Each textbox and its LABEL is then encased with a P element.
The radio buttons are a bit more involved, because the text next to them, as well as the text denoting
their category, is in “free space”. You can’t associate a LABEL with a radio button group, even though
there’s nothing really preventing you from placing one next to them. However, if it’s not going to have a
specific active function, there’s no need to suggest to any browser that there’s another active element to
worry about. The area in this case, within the P element, that is, is encased with a SPAN. SPAN is CSS’s
favorite tag: it does nothing at all. It just sits there, waiting to be flavoured - like tofu. In this case, it
doesn’t even need a class property, it’s nested enough so that selecting it with a style rule it will be easy
and specific. Within the SPAN, there’s an EM element encasing the word “Gender”. Why EM? because
it’s a passive tag—when it’s unstyled it emphasises the encased text, usually by making it italic, though
that’s not strictly in the standard. It’s there to be styled, so we can use another type selector instead of
using a class. But then, what’s with the form_font class? Unfortunately, Explorer 6 won’t apply fonts to

Anish Varghese Page 47 10/17/2008


input elements unless you apply a class to them. Technically, this shouldn’t be needed, Explorer 7 already
complies with this part of the standard, which means that it, along with Firefox, don’t need any classes
applied to this form at all.
The SELECT box has the same surrounding elements as the textboxes, while the Submit and Reset
buttons are encased in a STRONG. The STRONG is there for the same reason as the EM tags, a static
target. It’s a strong-emphasis tag, and it normally emboldens the text it encases. Note that at times the
lower Headings elements (H6, H5) can also be used, since search engines rarely pay attention to them if
there isn’t a proper structure of descending Headings elements present.

That about covers the structure of the form. Once you understand the concepts of CSS selectors and
how/when to use classes and tags, you’ll be able to easily create your own table-less structures. In the
meantime, these are building blocks you can mold using CSS to any style you require.

The Styling Begins


We’ll start off with the theform id selector, along with the FIELDSET, and LEGEND.
#theform { font-family: Trebuchet MS, sans-serif, Arial, Helvetica; font-size: 14px; line-height: 1.2em;
color: #444; width: 400px; } #theform fieldset { background:#FFF; border: 1px dashed #AAA; }
#theform legend { background:#DDD; border: 2px solid #CCC; padding-top: 2px; padding-bottom: 2px;
padding-left: 15px; padding-right: 15px; margin-left: 25px; font-weight: bold; font-size: 16px; }

The first properties that were set were the font-family, font-size, line-height, color (for the text) and width
of the theform id style rule. This is a typical property group for a DIV that doesn’t include positioning
elements, so there’s no need to expand here. The second style rule selects the FIELDSET, and sets the
background, and the border. As you can probably deduce from looking at how the form looks unstyled, the
border refers to exactly what you’d imagine—the visible 1px black border that normally appears with the
unstyled FIELDSET. Setting the border here will address that specific border, which is very convenient,
since it happens to perform a neat trick: it goes right through, and underneath, the LEGEND’s element’s
area. Sure, you could create that effect artificially using CSS, but you get it for free here, and it’s quite
simple to get rid of the effect, or alter it, if you wish. Now we laden the LEGEND style rule with a whole
lot of properties, though really, most are Box Model properties: border, padding, and margin. The others
are the background, and the font.

Now let’s stop for a moment and see what this looks like independently from the rest of the form:
Customize your Avatar
Some text inside the fieldset area.

Pretty fancy for 3 elements (we don’t style the form, it’s invisible here). You can now see why it was
important to separate the vertical and horizontal padding for the LEGEND—it gives an overall better
effect than a uniform padding, though you might want to use the shorthand version in your
implementations. The LEGEND was also shifted to the right using margin-left, and its border was set to
2px. As you can see, the LEGEND is inherently a block-level element, what with it wrapping a block of
HTML, again making it very convenient for us to style.
LEGEND and design it to attach to the
Don’t like rectangles? Place an background-image in the
FIELDSET border. CSS gives you many ways to misbehave.
Next up, the textboxes:
#theform p { margin-bottom: 4px; margin-top: 4px; } #theform p input { background: #DDD; border:
1px solid #444; } #theform label { display: block; width: 120px; float: left; text-align: right; padding-
right: 10px; }

This achieves several things. First, we’re separating theINPUT fields from each other, using margins
(technically, it’s theP elements we’re separating). Mind you, margin-collapse does take place here. Next,
we’re getting rid of the bevel (on some platforms) on the textboxes in favor of a 1px black border, and a
grey background.
The interesting part, though, is the LABEL style rule. First, it’s turned into a block-level element using the

Anish Varghese Page 48 10/17/2008


display property. Then, it’s given a width, and floated left so that it appears to the left, and not below the
form fields. The text-align is there so that the text “sticks” to the form elements, and the padding-right is
there so that is doesn’t “stick” too close to them.

There’s a few more things to take care of:


#theform strong { margin-left: 100px; } #theform strong input { background: #DDD; border: 1px solid
#444; font-weight: bold; color: #444; margin-top: 10px; } #theform p span em { display: block; width:
120px; float: left; text-align: right; padding-right: 10px; font-style: normal; } #theform p span input
{ vertical-align: middle; border: none; background: none; }

The first two rules up there are obvious—we’re styling the buttons to match the textfields. The second two
rules are the interesting bit. This time, it’s the EM that is becoming a block-level element, and is floated
left. This is exactly what was done with the LABELs previously. This time around, there’s no LABEL, but
there’s an EM within a SPAN, so it’ll do.
The resulting form:
Customize your Avatar

Eye Color:

Hair Color:

Gender: Male Female

Avatar Class:

And the many CSS style rules that come with it:
#theform { font-family: Trebuchet MS, sans-serif, Arial, Helvetica; font-size: 14px; line-height: 1.2em;
color: #444; width: 400px; } #theform fieldset { background:#FFF; border: 1px dashed #AAA; }
#theform legend { background:#DDD; border: 2px solid #CCC; padding-top: 2px; padding-bottom: 2px;
padding-left: 15px; padding-right: 15px; margin-left: 25px; font-weight: bold; font-size: 16px; }
#theform p { margin-bottom: 4px; margin-top: 4px; } #theform p input { background: #DDD; border:
1px solid #444; } #theform label { display: block; width: 120px; float: left; text-align: right; padding-
right: 10px; } #theform p span em { display: block; width: 120px; float: left; text-align: right; padding-
right: 10px; font-style: normal; } #theform p span input { vertical-align: middle; border: none;
background: none; } #theform strong { margin-left: 100px; } #theform strong input { background:
#DDD; border: 1px solid #444; font-weight: bold; color: #444; margin-top: 10px; }

If you’re wondering about the overall size of the CSS here, create the same form using tables, and
compare the two. Then, create a form with 3 times the input fields, using tables. See where I’m going
with this?...

There was a single DIV, one id selector, and no tables used. This is what happens when people don’t
bother going over the W3C specs properly. It’d help if they weren’t miles long, but still, you see what I
mean.

Anish Varghese Page 49 10/17/2008

S-ar putea să vă placă și