CSScomplete PDF

You might also like

You are on page 1of 108

1

Cascading Style Sheets


I recently had the opportunity to present at two Web design industry conferences: Web97
Design and Development in Washington, D.C. and Seybold San Francisco 98 in San
Francisco, California. The session at Web97, entitled Cascading Style Sheets: Layout and
Design, provided an overview of Cascading Style Sheets (CSS) and Dynamic HTML
(DHTML). The four-hour Seybold session, Designing with Dynamic HTML and
Cascading Style Sheets, provided an in-depth tutorial covering DHTML, CSS, CSS
positioning, and font embedding. I send thanks to everyone who attended these sessions.
It was a pleasure to meet you, and to see all the interest and excitement about Web design
possibilities using Cascading Style Sheets and Dynamic HTML.
This Site Lights column is dedicated to bringing those of you who attended the sessions, and other curious minds, the
HTML content and samples I presented and discussed. Please note that these samples require Internet Explorer 4.0, and
may not demonstrate properly in other browsers.

Kicking off the Sessions


To start off the sessions, I showed a simple splash page, which includes an enlarged GIF
of one of my sister's paintings and an animated GIF composed of various Webdings
characters.

The large TV monitor graphic also comes from the Webdings font. Webdings is a free
TrueType font that is installed with Internet Explorer 4.0, and it can be downloaded for
free from the Microsoft Typography Web site. To achieve the layout of this page, I
used basic CSS positioning.
The next page provides the title of the session, my name, and my e-mail address. This
page looks similar to what you might see in a traditional slide show presentation, but it is
composed entirely of HTML. By applying CSS filters, I created the typographic effects
(the drop shadows and blurred edges). This page also uses an embedded style sheet to set
type size and colors.
The main menu for both presentations uses a linked Cascading Style Sheet and demonstrates various negative-margin
effects.

What are Cascading Style Sheets?


Cascading Style Sheets are design templates that provide augmented control over
presentation and layout of HTML elements. They allow you to separate the way you
design information from the HTML content.

What are the Benefits?


Using style sheets, you can create Web pages with minimal graphics, and therefore much
smaller downloads. Style sheets also provide you with a higher level of typographic
control, and they enable you to make changes to an entire site through the use of linked
style sheets.

Where are Good References?


I urge you to visit the World Wide Web Consortium (W3C) to learn about the CSS
standard and the new CSS Positioning draft. Print out the specifications and drafts as

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


2

resources, and use them as your springboard for learning about CSS. The site also has a
wonderful set of references, ranging from books about CSS to other Web sites that use
and teach CSS. (You'll also find references listed at the end of this article.)
Dynamic Styles
Creating dynamic styles is very easy! Once you understand CSS basics, all you need to
know is a few lines of script -- and you can have any HTML tag change dynamically by
applying CSS attributes to it. For example, inline script events allow you to dynamically
change the style attributes of any HTML element when you touch it with the mouse
(onmouseover) or move the mouse off of it (onmouseout).
For example, the following headline code:
<H4 onmouseover="javascript:this.style.color='#6633FF'"
onmouseout="javascript:this.style.color='#000000'">
This headline will change to purple
when the mouse touches it,
and back to black when the mouse moves off of it</H4>
creates this headline:
This headline will change to purple when the mouse touches it,
and back to black when the mouse moves off of it
You can find information in the styles section. Several of the samples that I demonstrated
in the classes come directly from two previous Site Lights articles about Dynamic HTML
(Filter It, Scale It, Move It, Hide It with Internet Explorer 4.0) and Dynamic Cascading
Style Sheets (Is Your Site Made with Style?). For example, the swimming fish sample
illustrates Cascading Style Sheet positioning, Dynamic HTML, and Structured Graphics
plants. The DirectAnimation SDK provides documentation, samples, and tutorials to
help users get up and running with DirectAnimation and the new multimedia controls
included in Internet Explorer 4.0.
In my presentations, I used the Epicurious Food channel to illustrate dynamic movement
of HTML elements. Part of the navigation for this channel is provided by a series of
cafeteria trays sliding across the page. Dynamic HTML is used to activate the movement
of the cafeteria tray GIF files, and for all the click events. Various CSS attributes are
dynamically influenced via JavaScript. The position attributes of the cafeteria trays are
manipulated via scripting. Also, when each tray is clicked, the static GIF is hidden, and
an animated GIF is made visible. Download the Epicurious Food channel from the new
Microsoft Active Channel Guide .
Here are two additional samples demonstrating CSS.
Using more than one linked style sheet: This sample illustrates using more than one
linked style sheet on the page. As you click on the arrow, the sample cycles through 10
different linked Cascading Style Sheets.

JavaScript functions working with an embedded style block: This sample illustrates
how you can use JavaScript functions to call various parts of an embedded style block.
This changes the design of the content without having to leave or refresh the page.

Font Embedding

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3

Two differing technologies and solutions are currently used to deliver fonts with Web
pages. Netscape Navigator 4.0 supports Bitstream's TrueDoc technology, and
Internet Explorer 4.0 supports OpenType Font Embedding. Bitstream's TrueDoc
technology is based on delivering outlines of font characters, which are then converted
into bitmap versions of those characters. The OpenType Font Embedding technology
enables you to deliver font subsets or a full font family with your Web content.
The goal of my presentation was to provide a good understanding of how Internet
Explorer's OpenType Font Embedding works. Here are three easy steps to help you start
embedding fonts in Internet Explorer 4.0.
1. Take a look at some of Simon Daniel's samples in the Microsoft Typography team's demos .

2. Spend some time at the Microsoft Typography Web site. It has a great CSS gallery . Download the free
Web fonts , including the cool Webdings font that I demonstrated and used in various samples.

3. At the Typography site, download the beta version of the Web Embedding Fonts Tool (WEFT) , and learn
more about how to use this tool . WEFT analyzes Web pages for you, creates the Embedded OpenType
(EOT) font object for you, then adds the proper CSS font-embedding information to the page.
Font embedding in Internet Explorer 4.0 is enabled via CSS using the @font-face definition. Below is an example of a
style block that was created using WEFT. The tool also creates a font object, which is a subset of the font. The font
object is called an EOT file.
<STYLE>
<!--
@font-face {
font-family: Mistral;
font-style: normal;
font-weight: 700;
src: url(MISTRAL.eot); }
-->
</STYLE>

Using Cascading Style Sheets


What is CSS?
HTML was originally designed to describe the informational structure of a document. Its
tags and attributes were used to identify what was a header, list, and other structural
aspects of a document. This didn't give the author true control of what a document would
look like when rendered by the browser.
Then people started adding all sorts of tags to HTML that enabled it to describe some
visual aspects of documents. It was soon evident that trying to describe both a document's
structure and its layout using the same language would become a pretty big mess,
because the associated concepts and needs are entirely different.
Cascading Style Sheets, Level 1 is a specification from the World Wide Web Consortium
(W3C) that describes how to specify the visual layout features of a document. CSS
enables you to control the margins, coloring, background images, fonts, and a whole
range of elements for virtually every individual element that an HTML file describes

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


4

(<BODY>, <HEAD> (header), <P> (paragraph), <UL> or <OL> (lists), <TABLE>, and
so on).
For a quick illustration of some of the possibilities, check out the image that stretches
across the top of this page. Essentially, it is just a tiled image, but it is tiled only
horizontally (not vertically). The code I used to tile the image:
BODY {background:ivory url(torn.gif) repeat-x;}
This code sets the background property for the <BODY> tag. If I replaced the word
BODY in that code above with P, then every paragraph in my document would have the
torn-paper background across its top.

Implementation Limitations
The CSS specification covers a lot of features: In addition to control over margins,
coloring, background images, and fonts, the specification also describes how to control
borders, white space, letter spacing, padding, and even compound properties such as first-
letter and first-line formatting. Unfortunately, Internet Explorer 3.0 was not able to
implement every CSS feature in the first release; some of the more advanced features will
be supported in an upcoming release.
A User's Guide to Style Sheets provides a good overview of features implemented in the
current release of Internet Explorer and the technical aspects of adding CSS support to
your pages.

Marginal Issues
Cascading style sheets allow you to specify individual margins for all HTML elements.
For example, this code sets a one-inch margin for the left side of the document:
BODY {margin-left:1in;}
This code creates proper paragraph indentation:
P {margin-top:-10pt; font-size:12pt;
text-indent:.25in}

P.first {text-indent:0}
It sets paragraphs to be -- by default -- raised toward the top of the page 10pt (almost one
full font-size), which removes the blank line of padding normally used to separate
paragraphs; and indents the first line of each paragraph by .25 inches. Changing the
margin-top works only because I have specified the font-size to which the margin is
relative. I also define a paragraph class named "first" because I don't want to indent the
first paragraph of each section. For example, I use the paragraph style in the first
paragraph under "Pixels, Points, and Inches" below.
When you set margins, be careful to address the difference between how Internet
Explorer 3.0 and 3.01 render margins. I've prepared another article, Updated Margin
Usage in Style Sheets, that describes this difference and how to code your pages to
display properly in both versions of the browser. Breifly, in Internet Explorer 3.0 margins
weren't quite properly inherited between a parent element and a child element, and this

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


5

was fixed in the 3.01 update. You can determine which version of the browser you are
running by choosing About from the Help menu. Internet Explorer 3.01 reports itself as
IE 3.0 (4.70.1215). (The trailing "1215" in that string is the build number; the higher that
number, the later the version.)

Pixels, Points, and Inches


You can specify sizes and spacing of your text and graphics in many ways. Let's take a
look at an example:
H1 {margin-left:1in;font-size:28pt;
line-height:75%;}
In this example, I specify the sizing to associate with a level 1 header in three ways:
inches, points, and percentage. Although I could have written this code in other ways, the
methods I use here are appropriate for what I want to accomplish. To describe distances
or other forms of spatial relationships, it is best to use a standard ruler measurement, such
as in (inches) or cm (centimeters). Although I could have done the same thing with
margin-left:72pt, it is usually best to use pt (points) only when dealing with measurements
of fonts or line spacing. Specifying point size is a tricky business, and not fully
understood by many people. For example, assuming there are 72 points in an inch, if you
were to select a 72-point font, how tall (in inches) would an "M" be?
Note that I specify the line-height property as a percentage. When using percentages, the
question "Percentage of what?" arises. Sometimes the percentage is of the current font
size, sometimes the current page size, and there are times when it is a percentage of
something else. In this case, I know that the length unit associated with line-height is the
current font size, so I will compress the line height associated with headers by 75%
relative to the currently selected font size (28pt).
If you look at many pages that use CSS, you may also notice the use of px (pixels) for a
measurement unit. In most cases, avoid specifying your measurements in pixels, because
a pixel can be different sizes on different screen displays (not to mention printers). The
CSS specification tries to adjust for this:
[Cascading Style Sheet Specification: 6.1 Length Units]
If the pixel density of the output device is very different from that of a typical computer display, the
[browser application] should rescale pixel values. The suggested "reference pixel" is the visual
angle of one pixel on a device with a pixel density of 90dpi and a distance from the reader of an
arm's length.
You can see that what a pixel measurement really means can vary and lead to some
confusion. Therefore, avoid using it unless you are certain it's what you want.

Line-Height Spacing
If you've looked at the code for this page, you've noticed that I use the line-height
property to make the paragraph layout on this page expand a bit. This handy capability
helps the Web page designer control the readability and flow of the document.
To understand what the line-height property does for you, find a piece of ruled paper.
You know—that white paper with the light blue rules, with perhaps a red line showing
you where the margins are.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


6

This is just
a simple example
of text on ruled paper.

The line-height property defines the vertical distance between two blue lines (rules). In
the example above, to get the text to properly draw over the ruled paper bitmap, I set the
line-height to 20px because the bitmap is 20 pixels tall. By default, the line-height is the
same as the current font-size, because in typographical notation, font size refers to the
recommended baseline-to-baseline distance for the given font. If your current font-size is
set to 12pt, you will get the effect of double-spaced text by setting the line-height to 24
pt. An easier method is to specify the line-height as 200%; then you don't have to worry
about the current setting of the font-size.
Be careful when using line-height; you can easily get your line spacing set incorrectly.
For example, because Internet Explorer uses the line-height setting to define the height
of the entire table, chances are very good that your tables will not render correctly if you
set a line-height for the <BODY> element. It is best to keep your line-height
specification down in the lower-level elements such as paragraphs, or within individual
<SPAN> or <DIV> specifications. If you see a bunch of your text written over itself,
chances are good that the line-height is set incorrectly.

Backward Compatibility
Many people feel that they can't use cascading style sheets if they want their pages to be
visible to people using non-CSS-aware browsers. Although you may find CSS-based
pages that look bad when viewed on a non-CSS-aware browser, with just a little work
you can make your pages look great in CSS and fine in other browsers. For example, on
this page I am using CSS to add the torn-paper image at the top, and to control font
selection and line spacing. If you view this page in a non-CSS-aware browser, the
information will be intact and perfectly readable. If I specify the BACKGROUND
attribute in the <BODY> tag, I could supply a tiled background image that would display
only in a non-CSS-aware browser.
Another effect that CSS allows you to implement, and which you can make backward-
compatible, is
Shadowed Text.
Shadowed Text.
This is accomplished by using two copies of the text in the document: one in a dark color
(black) and one in a light color (#CCCC99). Simply adjust the left and top margins,
forcing the second instance of text to draw almost directly over the first instance of the
text. Unfortunately, a non-CSS-aware browser will display this as text listed multiple
times. To avoid this, use Visual Basic® Scripting Edition (VBScript) to provide the code
for all but one of the layers. Take a look at the source code for this page to see how I do
this.
If you find other features of CSS that you'd like to use but are concerned about backward
compatibility, try using VBScript. Because Internet Explorer is currently the only

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


7

browser that supports both CSS and VBScript, it provides authors the quickest and easiest
method for controlling how their Web pages display.

Layered Elements
By carefully manipulating the margins of elements, you can create interesting layering
effects. If you've experimented with this, you may have run into the problem of one layer
appearing to erase the layer it is being drawn over. I had this problem with several pages
I've created, and after a lot of head scratching I figured out how to fix it.
It appears that there is a minor bug in how the <BODY> element is being rendered. Try
starting the page with code similar to this:
<BODY>

<TABLE WIDTH=100% HEIGHT=100% CELLPADDING=0


CELLSPACING=0
CLASS="BODY"><TR><TD>

...your page code would then go here....

</TD></TR></TABLE>

</BODY>
This will (usually) fix the problem because it is moving the rendering into the <TABLE>
element. Note also the use of CLASS="BODY". This doesn't have anything to do with the
layering problem, but is a work-around for a different <BODY> tag rendering problem:
If you use a linked style sheet, you can't set the background color for the <BODY> tag.
To fix this, use the above code and assign the styles to the .BODY class. This slight
rendering problem will be fixed in an upcoming release of Internet Explorer, but the
above code will continue to work fine.

Controlling Presentation w i th Measurement a nd


Location Properties
Dynamic HTML (DHTML) exposes measurement and location properties that you can
use to change the size and position of HTML elements on your Web pages. When you
understand what these properties are and how they affect elements on a Web page, you
can achieve greater control over the appearance of your Web pages. For example, you
can use these properties to design Web pages that are similar to documents in other
applications, such as Microsoft® PowerPoint® or Microsoft® Word. This article

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


8

includes the following sections, which explain how to use measurement and location
properties to control the appearance of a Web page.

Requirements
This documentation assumes that you are familiar with a client-side scripting language,
such as Microsoft® JScript® (compatible with ECMA 262 language specification) or
Microsoft® Visual Basic® Scripting Edition. You should also be familiar with the
DHTML Object Model and cascading style sheets (CSS).

Layout Fundamentals
Measurement and location properties are available through the DHTML Object Model
and as CSS attributes. You can use DHTML Object Model properties to
programmatically set CSS attributes. Properties exposed through the DHTML Object
Model return values based on how an element renders in the document. CSS attributes
return values based on the preset values of other CSS attributes.
All CSS properties are exposed through the style object as of Microsoft Internet Explorer
4.0, and the runtimeStyle object as of Internet Explorer 5. You can use the currentStyle
object, available as of Internet Explorer 5, to query the current value of a property.

The Element Rectangle


Every visible element on a Web page occupies an absolute amount of space in the
document. The amount of space occupied by an element is defined by the element
rectangle or box. An element rectangle includes all of the layout and display properties
plus any content. The following graphic represents the element rectangle for a generic
element.

In the preceding graphic, the margin, border, and padding properties are shown
surrounding the content of a generic element. "Element Width" represents the width of
the element's content, and "Rectangle Width" represents the width of the content plus the
additional space occupied by the layout properties. The height of an element and its
layout properties can be represented similarly.

Block Versus Inline Elements


All visible HTML elements are either block or inline. A block element, such as the DIV
element, typically starts a new line and is sized according to the width of the parent
container. An inline element, such as the SPAN element, typically does not start a new
line and is sized according to the height and width of its own content.

Size, Layout, and Location of Elements


The size of an element, such as its height and width, comprises its measurements.
An element has layout when it is absolutely positioned, is a block element, or is an inline
element with a specified height or width. The following table shows that nearly all inline
and block elements have layout. The exception is an inline element that is neither
absolutely positioned nor has its height or width specified.
Block Element Inline Element

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


9

Absolutely positioned Not positioned Absolutely positioned Not positioned


Height only is specified Has layout Has layout Has layout Has layout
Width only is specified Has layout Has layout Has layout Has layout
Height and width are specified Has layout Has layout Has layout Has layout
Neither height nor width is specified Has layout Has layout Has layout No layout
An element with layout has specific measurements and can render the CSS layout
attributes. Element measurements are useful when setting the location of other elements
or creating specific document styles.
An element's location is the distance between the element and its parent, such as the top
and left coordinates. An element's location is useful when moving one or more elements
to relative or absolute coordinates within the document.

Measurement Fundamentals
Height and width are the measurements used most frequently. Use the offsetHeight and
offsetWidth properties to retrieve these measurements from any rendered inline or block
element. To set these measurements, use the height and width attributes (or related
properties). For a CSS attribute to be useful, you must set the attribute's value before
retrieving it.
With Microsoft® Internet Explorer 4.0 and later, inline elements gain layout when the
height or width are set. Inline elements with layout expose the same layout properties,
such as border, margin, and padding, as block elements. The following example shows
how layout attributes affect the appearance of a Web page when the height attribute is set
on an element.
<!-- Styles render because this link has layout. -->
<A
HREF="http://msdn.microsoft.com/"
STYLE="width: 150; border: 1 solid; padding: 10px; margin: 5px;">
MSDN Online
</A>

<!-- Styles do not render because this link has no layout. -->
<A
HREF="http://msdn.microsoft.com/"
STYLE="border: 1 solid; padding: 10px; margin: 5px;">
MSDN Online
</A>
Absolute and Relative Length Units
When setting or retrieving an element's measurement and location values, you can use
different length units to achieve a particular style. However, use length units consistently;
otherwise, you will have to programmatically determine the value of an absolute length
unit based on a relative length unit for every system. For example, you would have to
convert inches to pixels on every machine that renders the document.
Layout properties contribute to the dimensions of an element and should be considered
when determining the dimensions of the content. The content of an element is sized to
any specified measurements minus the border and padding measurements. Because the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


10

DHTML and CSS properties do not provide a measurement of the content without its
padding, the padding properties must be specifically queried to retrieve an accurate
measurement. While you can use the offset and client properties to determine the size of
the content, it is easier to subtract the size of the border and padding properties from the
width of the element.
Consider the following DIV element:
<DIV ID="oDiv"
STYLE="padding: 10; width: 250; height: 250;
border: 2 outset; background-color: #CFCFCF;"
>
</DIV>
The specified height and width of the preceding DIV is 250 pixels. You can formulate the
width of the content as follows:
oDiv.style.width - oDiv.style.borderWidth - oDiv.style.padding
However, since all three properties return variant data types, you must either convert the
values to integers or use properties that return integer values. For example, to obtain the
width of the element in pixels, you can use one of the following techniques in JScript:
var iWidth = oDiv.style.pixelWidth
var iWidth = parseInt(oDiv.style.width) (width is specified in pixels)
var iWidth = oDiv.offsetWidth
If the values of the border and padding properties are set in the same length units as the
width property, you can convert the variant value to an integer. To determine the content
dimensions, use the border and padding properties, or the client and padding properties,
and the element dimensions. When retrieving border and padding values, use the
borderWidth and padding properties, if the values are uniform on all sides of the element.
Otherwise, you must specifically query the borderLeftWidth, borderRightWidth,
paddingLeft, and paddingRight properties to obtain an accurate measurement.
For example, to obtain the width of the content in pixels, you can use one of the
following techniques in JScript, where iWidth is based on one of the previous example
techniques.
• Use this formula if the border and padding sizes are not uniform on all sides.

• var iCntWidth = (iWidth - parseInt(oDiv.style.borderLeftWidth)


• - parseInt(oDiv.style.borderRightWidth)
• - parseInt(oDiv.style.paddingLeft)
• - parseInt(oDiv.style.paddingRight)
• )
• Use this formula if the border and padding sizes are uniform on all sides.

• var iCntWidth = (iWidth - parseInt(oDiv.style.borderWidth)


• - parseInt(oDiv.style.padding)
• )
• Use this formula instead of using the border properties.

• var iCntWidth = (iWidth - (oDiv.offsetWidth - oDiv.clientWidth)


• - parseInt(oDiv.style.padding)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


11

• )
Measurement Example
The following example uses the first formula from the preceding section to move and
resize a positioned element based on the content of another element.
<SCRIPT>
window.onload=fnInit;
function fnInit(){
var iWidth=oDiv.style.pixelWidth;
var iHeight=oDiv.style.pixelHeight;
var iCntWidth=(iWidth - parseInt(oDiv.style.borderLeftWidth)
- parseInt(oDiv.style.borderRightWidth)
- parseInt(oDiv.style.paddingLeft)
- parseInt(oDiv.style.paddingRight));
var iCntHeight=(iHeight - parseInt(oDiv.style.borderTopWidth)
- parseInt(oDiv.style.borderBottomWidth)
- parseInt(oDiv.style.paddingTop)
- parseInt(oDiv.style.paddingBottom));
var iTop=oDiv.offsetTop + parseInt(oDiv.style.borderTop)
+ parseInt(oDiv.style.paddingTop);
var iLeft=oDiv.offsetLeft + parseInt(oDiv.style.borderLeft)
+ parseInt(oDiv.style.paddingLeft);
oDiv2.style.width=iCntWidth;
oDiv2.style.height=iCntHeight;
oDiv2.style.top=iTop;
oDiv2.style.left=iLeft;
}
</SCRIPT>
<DIV ID="oDiv"
STYLE="padding: 20 5 10 10; width: 250; height: 250;
border: 10px outset; background-color: #CFCFCF;"
>
</DIV>
<DIV ID="oDiv2" STYLE="position: absolute; border: 2 inset;
background-color: #000099;"
>
</DIV>
Location Fundamentals
The portion of Internet Explorer that displays the document is referred to as the client
area. The location of the upper left-hand corner of the client area is 0 on the x-axis and 0
on the y-axis, or top and left, respectively. The BODY element is the first visible

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


12

container in the document and is also the top-most offset parent. Therefore, the top and
left coordinates of the BODY are both 0.
The distance between the element and its positioned or offset parent defines the element
location. Internet Explorer exposes the element location when the document renders or
when a change to the content forces the document to redraw. Understanding how
elements are located within the document is key to determining and changing the location
of an element.
Positioned elements render outside of the document flow. The document flow is the order
of the elements after their measurements are calculated. Changing the measurements or
location of positioned elements does not affect adjacent elements in the document flow,
but it might affect children elements.
Nonpositioned inline and block elements render together and are part of the document
flow. An element's location can change when the measurement of another element
appearing earlier in the document flow changes. The measurement of an element changes
when the content, layout, or font style of another element is updated after the document
renders. Changing the measurements of a nonpositioned element changes the location of
adjacent elements in the document flow. The location of a nonpositioned element also
changes if you change its margin.

Top and Left Locations


The following example shows how to retrieve the location of an inline element and how
the measurement of another element affects the location of that element.
<SCRIPT>
function getLocation(){
alert("Left: " + oSpan.offsetLeft);
oSpan1.innerHTML="Changed content.";
alert("Left: " + oSpan.offsetLeft);
oSpan1.innerHTML="This is some dynamic content.";
}
</SCRIPT>
<BODY>
<SPAN ID="oSpan1">This is some dynamic content.</SPAN>
<SPAN STYLE="background-color: #CFCFCF;" ID="oSpan">
This content won't change, but this element's location will change.
</SPAN>
<INPUT TYPE="button" VALUE="Locate Second Element"
onclick="getLocation()">
</BODY>
Offset Parents
Although you can retrieve the top or left location of any element that renders, the values
of these locations are relative to the positioned or offset parent. In many cases, the offset
parent of an element is the BODY element. The offsetParent property retrieves a
reference to the container object that defines the offsetLeft and offsetTop properties for
the element. The offset properties return values in pixels relative to the parent, and you

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


13

cannot always rely on a single value when determining the distance between two
elements.
The following image depicts the offsetLeft values of a SPAN element and a TABLE
element. The offset value for both elements is 50 pixels. However, if you query the offset
value of a table cell, the offsetLeft property returns only 3 pixels, because TABLE is the
offset parent of the TD element (Cell 1). To determine the distance from the table cell to
the edge of the screen, add the two values together.

Special Cases
Certain elements, such as the TABLE element, expose their own object model and a
specific set of properties, such as the cellPadding property and the cellSpacing property.
From the currentStyle object, you can retrieve the current value of the cellPadding
property through the padding property. You must retrieve the cellSpacing property
directly from the TABLE element.

Nested Elements
Determining the distance between any nested element and its offset parent, such as the
BODY element, might require you to include the location of the offset parent. For
example, the top and left locations of a TD element return the distance between the cell
and the offset parent, which is the TABLE element. To determine the distance between a
nested element and the BODY element, you must walk up the document hierarchy and
add the left location values of all the offset parents between the two elements.

Location Example
The following example shows how to programmatically retrieve the absolute distance
between a TD element and the BODY element.
<SCRIPT>
function getAbsoluteLeft(oNode){
var oCurrentNode=oNode;
var iLeft=0;
while(oCurrentNode.tagName!="BODY"){
iLeft+=oCurrentNode.offsetLeft;
oCurrentNode=oCurrentNode.offsetParent;
}
alert("Left: " + oNode.offsetLeft + "\nAbsolute Left: " + iLeft);
}
</SCRIPT>
<BODY>
<INPUT
TYPE="button"
VALUE="Get Absolute Left"
onclick="getAbsoluteLeft(oCell)">
<TABLE CELLSPACING="2">
<TR><TD ID="oCell">Cell 1</TD></TR>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


14

</TABLE>
</BODY>
Positioned Elements
An absolutely positioned element's measurements are first defined by any specified
measurement properties, such as height or width, and then by its content. This is true for
block and inline elements. However, a relatively positioned element retains its block or
inline measurements unless otherwise specified.
The following example shows that the measurements of a block element and an inline
element are the same when the position attribute is set to absolute.
<DIV
STYLE="background-color: #CFCFCF; position: relative; top: 10;">
Text
</DIV>
<SPAN
STYLE="background-color: #CFCFCF; position: absolute; top: 30;">
Text
</SPAN>
You can use the same procedure to set or retrieve the measurements of positioned
elements and nonpositioned elements.

How to Use Measurement and Location Properties


Measurement and location values do not have to be static integers. They can be scripted
values based on distances and dimensions of other elements, expressed lengths, as in
more traditional media, or equations. When working with several elements, you can use
the measurement of one element to set the location of another.
You can use the measurement and location properties discussed in this overview to
construct more complex creations. For example, to center an element within its container,
set its left coordinate to the sum of one-half the width of its container minus one-half the
width of the element. The following example shows this syntax.
<SCRIPT>
function center(oNode){
var oParent=oNode.parentElement;
oNode.style.left=oParent.offsetWidth/2 - oNode.offsetWidth/2;
}
</SCRIPT>
<DIV
ID="oDiv"
onclick="center(this)"
STYLE="position: absolute;">
Click Here To Center
</DIV>
Expressions are formula-derived values. You can use expressions to continually update
property values, as of Internet Explorer 5. In the preceding example, the element is

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


15

centered once, but does not remain centered if the browser window is resized. To
preserve a particular layout, use a formula rather than a static value.
Use the setExpression method to add expressions to CSS attributes and DHTML
properties. The following example shows how to center an element using an expression
rather than a static value.
<SCRIPT>
function center(oNode){
oNode.style.setExpression("left","getCenter(this)");
}
function getCenter(oNode){
var oParent=oNode.parentElement;
return (oParent.offsetWidth/2 - oNode.offsetWidth/2);
}
</SCRIPT>
<DIV
ID="oDiv"
onclick="center(this)"
STYLE="position: absolute;">
Click Here To Center
</DIV>
While the DHTML Object Model provides an easy way to obtain the current dimensions
and location of an element, you must use CSS to set these values for most elements.
Except for elements that expose height and width properties, such as IMG and TABLE,
you can use the various CSS attributes to set the size of an element. While many
properties return values in pixels, you can use some CSS properties with specific length
units, such as inches or centimeters.
For example, if an H1 element has top and left positions of 2 inches, the offsetTop and
offsetLeft properties return approximately 190 pixels, depending on the screen resolution.
Since the top and left properties return a string value of 1in, you can use the posTop and
posLeft properties to increment or decrement the location in inches rather than pixels.
The posTop and posLeft properties use the same length units as their counterpart CSS
properties, top and left.
The following example moves the H1 element 1 inch every time the user clicks the
element.
<SCRIPT>
function moveMe(){
// Move the object by one inch.
oHeader.style.posLeft+=1;
oHeader.style.posTop+=1;
}
</SCRIPT>
<H1 ID="oHeader"
STYLE="position: absolute; top: 1in; left: 1in;"
onclick="moveMe()">

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


16

Header
</H1>
When moving elements to specific locations in the document, it is sometimes necessary
to account for the different properties of the element rectangle. Height and width values
include border and padding measurements, so moving one element to the visible corner
of another element is relatively easy using the offset properties and techniques described
in the preceding example. However, when positioning an element at a specific point in
the content of another positioned element, you must include the size of the padding and
border. You can use either the client properties or the padding and border properties to
establish a location within the content of an element. You can also use a TextRectangle to
establish a location.
The following example shows three different ways to position an element within the
content of another element. First, CSS pixel, border, and padding properties are used to
move an element to the content within a positioned element. Next, DHTML offset and
client properties are used to move an element within the content of a positioned element
without accounting for the padding. And finally, a TextRectangle is used to establish the
position of the element.
Show Sample Code
<SCRIPT>
function fnMove1(){
// Method 1: Use only CSS properties
var iTop1=oDiv.style.pixelTop +
parseInt(oDiv.style.borderTopWidth) +
parseInt(oDiv.style.paddingTop);
var iLeft1=oDiv.style.pixelLeft +
parseInt(oDiv.style.borderLeftWidth) +
parseInt(oDiv.style.paddingLeft);
oMarker.style.top=iTop1;
oMarker.style.left=iLeft1;
}
function fnMove2(){
// Method 2: Use DHTML properties.
var iTop2=oDiv.offsetTop + oDiv.clientTop;
var iLeft2=oDiv.offsetLeft + oDiv.clientLeft;
oMarker.style.top=iTop2;
oMarker.style.left=iLeft2;
}
function fnMove3(){
// Method 3: Use DHTML, CSS, and a TextRectangle.
var aRects=oDiv.getClientRects();
var oRect=aRects[0];
var oBnd=oDiv.getBoundingClientRect();
oMarker.style.top=oBnd.top +
parseInt(oDiv.style.paddingTop) +

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


17

parseInt(oDiv.style.borderTop);
oMarker.style.left=oBnd.left +
parseInt(oDiv.style.paddingLeft) +
parseInt(oDiv.style.borderLeft);;
}
</SCRIPT>

<DIV ID="oDiv"
STYLE="position: absolute; top: 150; left: 50; border: 10 outset;
padding: 10; width: 250; height: 250; background-color: #EFEFEF;"
>
Move marker here.
</DIV>

<SPAN ID="oMarker"
STYLE="top: 200; left: 200; position: absolute;
border: 2 outset; background-color: #CFCFCF;"
>
Marker
</SPAN>

<INPUT TYPE="button" VALUE="CSS" onclick="fnMove1()">


<INPUT TYPE="button" VALUE="DHTML" onclick="fnMove2()">
<INPUT TYPE="button" VALUE="TextRectangle" onclick="fnMove3()">
Advanced Techniques
With Internet Explorer 5 and later, you can use DHTML expressions and the
runtimeStyle and currentStyle objects to create more advanced measurement and location
formulas. Expressions use formulas to return a possible value for any DHTML or CSS
read/write property. To query the current value of a property, use the currentStyle object
instead of the style object. To temporarily set a property value, use the runtimeStyle
object instead of the style object. When a property value is cleared from the
runtimeStyle object, the value reverts to the original property value set on the style
object.
Expressions, DHTML, and CSS provide a robust model for delivering information to
your audience. The following example uses these technologies to animate a list when the
document loads. The margin-left attribute includes an expression that returns a value
based on a variable.
Once the document loads, the setInterval method is invoked to increment the variable
until it reaches a target value. The amount is determined by the marginLeft property of a
particular list item's sibling, available from the previousSibling property. When the
variable increments, the recalc method is invoked with the true parameter, because the
margin-left attribute is not implicitly dependent on the variable. Adding the marginLeft
value of the sibling list item causes the entire list to cascade.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


18

Show Sample Code


<STYLE>
LI {margin: expression(fnTabIt(this));}
</STYLE>
<SCRIPT>
window.onload=fnInit;
// Starting marginLeft increment.
var iDML=0;
// Target marginLeft increment.
var iDMLTarg=30;
// Increment modifier.
var iDMLMod=.25;
// Animation speed in milliseconds.
var iDMLSpeed=50;
var oInterval;
function fnTabIt(oNode){
var oPSib=oNode.previousSibling;
if(oPSib!=null){
var iML=0;
if(oPSib.style.marginLeft!=""){
iML=parseInt(oPSib.style.marginLeft);
}
return ((iDML*iDMLMod) + iML);
}
else{
return 0;
}
}
function fnAdjustTab(){
if(iDML<iDMLTarg){
iDML++;
document.recalc(true);
}
else{
iDML=iDMLTarg;
window.clearInterval(oInterval);
}
}
function fnInit(){
oInterval=window.setInterval("fnAdjustTab()",iDMLSpeed);
}
</SCRIPT>
<UL>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


19

<LI>Item 1
<LI>Item 2
<LI>Item 3
<LI>Item 4
<LI>Item 5
<LI>Item 6
<LI>Item 7
<LI>Item 8
<LI>Item 9
<LI>Item 10
</UL>
Click the following Show Me button for an interactive demonstration of the measurement
and location properties. When you select a pair of properties, the dimensions and
distances are displayed using indicators created with the same techniques discussed in
this overview.
Show Me

A User's Guide to Style Sheets


Abstract
Style sheets, introduced in Microsoft Internet Explorer 3.0, are about to change the way
people build and maintain their Web pages. A style sheet may not be obvious to readers
of Web pages because it works behind the scenes to give Web authors and designers
more control and flexibility in their word- and design-smithing on the Web.
Style sheets deliver some of the formatting features and control authors and designers
have been enjoying for years in traditional desktop publishing--features that have been
sorely missed on the Web. With style sheets, you can finally specify point sizes, page
margins, and leading (spacing between lines). You can also create any number of
formatting variations for a single HTML tag.
In addition to this new functionality, a style sheet provides a convenient service: It
separates the formatting information from the actual content on your HTML pages, so it
becomes much easier to design and revise your pages.
This document provides an introduction to style sheets and explains usage and syntax, as
defined by the World Wide Web Consortium (W3C) and supported by Microsoft Internet
Explorer 3.0.

Introduction
A style sheet is a template that controls the formatting of HTML tags on your Web pages.
If you use Microsoft Word, you will find the concept of style sheets very similar to Word
templates: You can alter the appearance of a Word document by changing the formatting
assigned to styles in your document. Similarly, you can alter the appearance of a Web
page by changing the formatting assigned to HTML tags through a style sheet, and thus
override the browser's default specification for those tags.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


20

If you publish on the Web, you may want to take advantage of style sheets for three main
reasons: additional formatting, better control, and easier customization. Specifically, style
sheets allow you to:
• Use leading, margins, indents, point sizes, and text background colors on your
Web pages. Authors and designers take these formatting features for granted, but
HTML does not support these directly through its standard set of tags.
• Stop using awkward workarounds for basic formatting tasks (such as
<BLOCKQUOTE> for margins).

• Change the formatting of individual Web pages or your entire site without
touching every single line in your HTML files.
• Reduce the clutter of tags on your HTML pages (because you don't need to turn
tags on and off to change the design of a single element).
• Define design variations through classes (for example, if you need five different
paragraph styles, you can specify five classes for the <P> tag, e.g., P.normal,
P.indented, P.underlined, P.red, P.dblspaced).

Browser Support
Style sheets are fairly new to the Web. Internet Explorer 3.0 is the first Web browser to
support style sheets. The Internet Explorer 3.0 implementation of style sheets is based on
the W3C working draft called "Cascading Style Sheets, Level 1" (dated May 1996,
http://www.w3.org/pub/WWW/TR/WD-css1.html ). Spyglass and Netscape have
also indicated that they will support style sheets in future versions of their browsers.
Browsers that don't support style sheets display the pages using the browser's default
specs instead. (See "Tips & Tricks" for instructions on how to set up your style sheets so
they don't cause problems in other browsers.)

Cascading Style Sheets


The W3C draft refers to "cascading style sheets" because you can use multiple styles to
control the appearance of your page, and the browser follows rules (a "cascading order")
to determine precedence and to resolve conflicts. For example, the Web author can use
linked, embedded, and inline styles (described below) in one document, and Web readers
can have their own personal style sheets. If the linked style sheet defines a heading tag as
blue, the top-of-page style sheet defines it as red, and the reader wants to see purple, the
browser has to decide what to display. Cascading rules are discussed in "Mixing
Methods" later in this article.

Three Ways to Add Styles to Your Web Pages


You can use style sheets in three ways, depending on your design needs:
• By linking to a style sheet from your HTML file. This method allows you to change the appearance of
multiple Web pages by tweaking a single file.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


21

• By embedding a style sheet in your HTML file. This method allows you to change the appearance of a single
Web page by tweaking a few lines.

• By adding inline styles to your HTML file. This gives you a quick way to change the appearance of a single
tag, a group of tags, or a block of information on your page.
You can use one, two, or all three of these methods on your pages. The sections below discuss each method and syntax
in detail. For detailed information, see the W3C documents: HTML3 and Style Sheets and Cascading Style
Sheets, Level 1 .
Note: Internet Explorer 3.0 does not support imported style sheets.

Basic Syntax
Both linked and embedded style sheets include one or more style definitions. (The inline
style syntax is somewhat different, as we'll discuss later.) A style definition consists of an
HTML tag (any tag), followed by a listing of properties for that tag within curly braces.
Each property is identified by the property name, followed by a colon and the property
value. Multiple properties are separated by semicolons. For example, the following style
definition assigns the <H1> tag a specific font size (15 points) and font weight
(boldface):
H1 {font-size: 15pt;
font-weight: bold}
You can thus create style definitions for any number of HTML tags and either place them
in a separate file or embed them directly within your Web pages. For a list of properties,
see the "Style Reference Guide" section below.

Linking to a Style Sheet


To link to an external style sheet, you simply create a file with your style definitions (as
explained below for embedded styles), save it with a .CSS file extension, and link to it
from your Web page. This way, you can use the same style sheet for any number of pages
on your site.
For example, if your style sheet is called MYSTYLES.CSS and is located at the address
http://internet-name/mystyles.css, you would add the following to your Web page, within
the <HEAD> tag:
<HEAD>
<TITLE>Title of article</TITLE>
<LINK REL=STYLESHEET
HREF="http://internet-name/mystyles.css"
TYPE="text/css">
</HEAD>
Note: Internet Explorer 3.0 (final release) now registers the Internet Media (MIME) type
for style sheets, so you don't have to register the "text/css" type on the server yourself.
This version of the browser allows you to link to a single style sheet. The TYPE attribute
is ignored.

Embedding a STYLE Block

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


22

To embed a style sheet, you add a <STYLE> </STYLE> block at the top of your
document, between the <HTML> and <BODY> tags. This allows you to change the
appearance of a single Web page. The <STYLE> tag has one parameter, TYPE, which
specifies the Internet Media type as "text/css" (allowing browsers that do not support this
type to ignore style sheets). The <STYLE> tag is followed by any number of style
definitions and terminated with the </STYLE> tag.
The following example specifies styles for the <BODY>, <H1>, <H2>, and <P> tags:
<HTML>
<STYLE TYPE="text/css">
<!--
BODY {font: 10pt "Arial"}
H1 {font: 15pt/17pt "Arial";
font-weight: bold;
color: maroon}
H2 {font: 13pt/15pt "Arial";
font-weight: bold;
color: blue}
P {font: 10pt/12pt "Arial";
color: black}
-->
</STYLE>
<BODY>
...
</BODY>
</HTML>
See the "Tips & Tricks" section to find out why I've added HTML comments (<!-- and --
>) within the style block.

Using Inline Styles


If you want to take advantage of point sizes, indentation, or other styles in only a few
sections of your Web page, you can use inline styles.
Inline style definitions affect individual occurrences of a tag. These are embedded within
the tag itself using the STYLE parameter. The following HTML code indents a specific
<P> tag:
<P STYLE="margin-left: 0.5in; margin-right:
0.5in">
This line will be indented on the left and right.
<P>
This line will receive no indentation.
Here's the result (this display requires Internet Explorer 3.0):

This line will be indented on the left and right.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


23

This line will receive no indentation.

If the inline style conflicts with an embedded or linked style, the inline style overrides for
that particular occurrence. For example, if the line above appears on a Web page that
defines <P> with 1-inch margins through a linked style sheet, all paragraphs on the Web
page will get 1-inch margins except for the <P> above, which will get 0.5-inch margins.
If you want to change the appearance of an entire section, you can use the <DIV> tag to
define styles globally for that section. The following example changes the color and point
size of a block of text by using the <DIV> tag (this has the same effect as assigning these
styles separately for the <P>, <UL>, and <LI> tags):
<DIV
STYLE="font-size: 20pt; color: red">
<P>
The style specification affects everything on this page until the
DIV close tag.
<UL>
<LI>This is red and 20 pt.
<LI>So is this.
</UL>
</DIV>
Result (requires Internet Explorer 3.0):
The style specification affects everything on this page until the DIV close tag.
• This is red and 10 pt.

• So is this.
The following example uses the <DIV> tag for a block of text, but overrides it for a
specific <LI> tag:
<DIV STYLE="font-size: 10pt; color:
red">
<P>
The style specification affects everything on this page until the
DIV close tag, except for the second list item.
<UL>
<LI>This is red and 10 pt.
<LI STYLE="color: blue">This is blue and 10 pt.
</UL>
</DIV>
Result (requires Internet Explorer 3.0):
The style specification affects everything on this page until the DIV close tag, except for the second list
item.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


24

• This is red and 10 pt.

• This is blue and 10 pt.


Inline styles are simple to use if you're focusing on a few tags or sections on your Web
page (for example, you're highlighting a heading or indenting an abstract). However,
inline styles clutter up your HTML pages, and revisions require more detailed attention
(because you have to change multiple lines scattered throughout your HTML file). If you
want to make global changes to one or more Web pages, you'll find that using a
centralized STYLE block (either linked or embedded) is easier and more efficient.
The <SPAN> tag is very similar to the <DIV> tag, but is used for smaller page elements
(for example, words, even letters) instead of text blocks or containers. You can use
<SPAN> to change styles within a sentence or even within a word, or to create special
effects. See the Microsoft Typography group's demo pages for some interesting effects
created with <DIV> and <SPAN>.

Mixing Methods
If you're just starting out with style sheets, it's probably a good idea to stick to one
method that best addresses your needs. However, you may have complicated
requirements that can be met only by using two or all three methods. I’ve listed some
scenarios below. (Note: These are future scenarios; Internet Explorer 3.0 does not yet
support links to multiple style sheets, the use of linked and embedded styles within the
same document, or readers’ style sheets.)
• Storing your styles in separate style sheets (one storing the basic page layout for
simple documents, and others customizing the layout for different types of
documents), and linking to multiple .CSS files at the top of your page.
• Linking to your company-wide style sheet for consistency, but providing style
variations (through classes) with an embedded style sheet.

• Linking to your company-wide style sheet, but overriding several specific


elements using inline styles.
• When readers’ style sheets are supported, using style sheets to provide formatting
that is essential to your page design, and letting readers adjust the point size,
leading, and typeface to suit their personal preferences.
So what will happen if you use multiple style sheets that have conflicting style
information? That's where the "cascading order" will come into play. According to the
W3C working draft, the author's style sheets will override the reader's style sheet, which
in turn will override the browser's default values. If the author uses all three methods
listed above, the inline styles will take precedence over the embedded <STYLE> block,
which will override the linked style sheet.

Additional Options
Simplification through grouping

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


25

If you want to assign the same formatting to multiple tags, for example:
H1 {font-size: 15pt;
font-weight: bold;
color: maroon}
H2 {font-size: 15pt;
font-weight: bold;
color: maroon}
H3 {font-size: 15pt;
font-weight: bold;
color: maroon}
you can group them thus:
H1, H2, H3
{font-size: 15pt;
font-weight: bold;
color: maroon}
You can also group formatting specifications. Take:
H1 {font-size: 15pt;
line-height: 17pt;
font-weight: bold;
font-family: "Arial"
font-style: normal}
and simplify it this way:
H1 {font:
15pt/17pt bold "Arial" normal}
(See the "Style Reference Guide" section below for more information on grouping font
specs.)

Variations through classes


Use classes to create variations for a single HTML tag. For example, if you'd like to use
three colors for your H1 headings (say, depending on context), you'd define three classes
in your STYLE tag:
<STYLE>
H1.red {font: 15pt/17pt;
color: red}
H1.green {font: 15pt/17pt;
color: green}
H1.blue {font: 15pt/17pt;
color: blue}
</STYLE>
and use them as follows on your Web page:
<H1 CLASS=red>This is the red heading</H1>
...
<H1 CLASS=blue>This is the blue heading</H1>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


26

...
<H1 CLASS=green>You get the picture...</H1>

Links
The style sheet implementation also allows you to customize the appearance of links (text
that the user clicks to jump to another page) by assigning two predefined classes to the
<A> (anchor) tag:
• A:link represents a link that hasn't been visited (clicked).

• A:visited represents a link that the user has already clicked.


You can set any font or text formatting properties on these anchor classes, including color, font-size, font-weight, and
text-decoration. For example, to assign specific colors to the three types of links, you can specify:
A:link {color: red}
A:visited {color: blue}
A:active {color: orange}
Setting text-decoration to "none" allows you to remove the underlining from the link
text:
A:visited {color: blue; text-decoration: none}
Notes: Internet Explorer 3.0 does not support the A:active class, which represents a link
that is currently being visited (for example, if your Web page consists of two frames--a
contents frame and a viewer frame--and you click a link in the contents frame, the link
will be "active" while you're viewing that article). In Internet Explorer 3.0, you'll also
find that if you set a property on A:link, visited links inherit that property.

Comments
You can add comments to your style sheet to explain your design decisions. Comments
can appear on any line in the style specification, between the characters /* and */--for
example:
H1 {font: 20pt/22pt
bold; color=#00FF00} /* Green for heading 1 */

Style Reference Guide


This section provides a list of properties you can use in your style specifications with
Internet Explorer 3.0 Beta 1 or later. See the W3C "Cascading Style Sheets, Level 1"
working draft for a complete list of the standard properties.
Note that Internet Explorer 3.0 does not currently support all of the attribute types and
values documented in the W3C working draft. In the sections below, we've noted some of
the differences in supported values.

Quick Reference
Attribute Description Values Example
font-size Sets size of text. points (pt) {font-size: 12pt}
inches (in)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


27

centimeters (cm)
pixels (px)
font-family Sets typeface. typeface name {font-family: courier}
font family name
font-weight Sets thickness of type. extra-light {font-weight: bold}
light
demi-light
medium
demi-bold
bold
extra-bold
font-style Italicizes text. normal {font-style: italic}
italic
line-height Sets the distance between baselines. points (pt) {line-height: 24pt}
inches (in)
centimeters (cm)
pixels (px)
percentage (%)
color Sets color of text. color-name {color: blue}
RGB triplet
text-decoration Underlines or otherwise highlights none {text-decoration:
text. underline underline}
italic
line-through
margin-left Sets distance from left edge of page. points (pt) {margin-left: 1in}
inches (in)
centimeters (cm)
pixels (px)*
margin-right Sets distance from right edge of page. points (pt) {margin-right: 1in}
inches (in)
centimeters (cm)
pixels (px)*
margin-top Sets distance from top edge of page. points (pt) {margin-top: -20px}
inches (in)
centimeters (cm)
pixels (px)*
text-align Sets justification. left {text-align: right}
center
right
text-indent Sets distance from left margin. points (pt) {text-indent: 0.5in}
inches (in)
centimeters (cm)
pixels (px)*
background Sets background images or colors. URL, {background: #33CC00}
color-name
RGB triplet
Note: Internet Explorer 3.0 (final release) supports negative values for the margin-left, margin-right, margin-top, and
text-indent attributes.

Point size
The font-size attribute sets the size of the text in points, inches, centimeters, or pixels.
For example:
{font-size: 12pt}
{font-size: 1in}

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


28

{font-size: 5cm}
{font-size: 24px}
You can also use a percentage value, which will be evaluated based on the default point
size.

Typeface
The font-family attribute sets the typeface used for text. You can specify a single
typeface:
{font-family: Arial}
or alternatives, separated by commas:
{font-family: Arial, Helvetica}
The line above ensures that Helvetica is used on systems that don't support Arial.
Specifying a generic family name as a last alternative is good practice:
{font-family:
Arial, Helvetica, sans-serif}
The generic family names (serif, sans-serif, cursive, fantasy, or monospace) are mapped
to the fonts installed on the user's system.
If you're referencing a typeface that consists of multiple words, use quotation marks:
{font-family: "Courier New"}

Weight
The font-weight attribute sets the thickness of type.
{font-weight: medium}
{font-weight: bold}
The accepted values (extra-light, light, demi-light, medium, demi-bold, bold, and extra-
bold) depend on the fonts available on the user's system. (For example, the user's system
may only allow medium and bold for a given font.)

Style
The font-style attribute sets italic text:
{font-style:
italic}
(Note that the W3C working draft also references small caps, oblique, and a few other
styles. Internet Explorer 3.0 currently supports only normal and italic.)

Line height
The line-height attribute sets "leading" (the distance between the baselines of two lines).
You can specify leading in points, inches, centimeters, or pixels. For example:
{line-height: 20pt}
You can also specify a percentage value:
{line-height: 150%}

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


29

(Note that in Internet Explorer 3.0, the spacing is added before lines, not after lines. Also,
this attribute behaves inconsistently on text that uses different point sizes on the same
line.)

Grouping font attributes


The attributes listed above are ones that you will probably use frequently in your style
sheets, so the W3C specifies (and Internet Explorer supports) a shortcut notation. Instead
of setting the attributes separately, you can combine them into one attribute called font.
Thus, instead of:
P
{font-family: Times, serif;
font-size: 12pt;
line-height: 20pt;
font-weight: bold;
font-style: italic}
you can simply use:
P {font: bold
italic 12pt/20pt Times, serif}
Note: The order of attributes is significant: the font weight and style must be specified
before the others.

Colors
The color attribute sets the type to a named color or RGB value. You can use the 16
named colors or hexadecimal red-green-blue (RGB) color values:
{color: teal}
{color: #33CC00}
Named colors consist of the following:
black silver gray white
maroon red purple fuchsia
green lime olive yellow
navy blue teal aqua
For more information on colors, see the articles by Robert Hess on the MSDN Online
Web Workshop. The Safety Palette Color Picker article provides a complete color chart
with hexadecimal RGB values, and Using Named Colors in Internet Explorer lists a much
larger set of named colors you can use: the X11 named color set.

Special text effects


The text-decoration attribute allows you to use underlining and strike-through for text.
The supported values are underline, line-through, none, and italic.
{text-decoration: underline}
{text-decoration: line-through}

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


30

(The W3C working draft also references overline and blink, which are not currently
supported by Internet Explorer.) To see an example of how you can use text-decoration
to turn underlining off for links, see "Links" above.

Margins
The margin-left, margin-right, and margin-top attributes set the side margins and top-
margin for a tag. You can specify the margins in points, inches, centimeters, or pixels.
For example:
BODY
{margin-left: -10px;
margin-right: -10px;
margin-top: 20px}
(You can use negative values for margin settings to create special effects. For examples,
see the cascading style sheet demo pages created by the Microsoft Typography group.)

Grouping margin attributes


Instead of setting the margin attributes separately, you can combine them into one
attribute called margin. Thus, instead of the example above, you can simply use:
you can simply use:
P {margin: 20px -10px-10px}
The order is top, right, and left. If you specify a single value, it will be applied to all three
margins.

Alignment
The text-align attribute lets you left-justify, center, or right-justify HTML elements:
{text-align: left}
{text-align: center}
{text-align: right}

Indentation
In addition to using margins, you can also set additional indentation for sections of your
page using the text-indent attribute. Again, you can specify indentation in points, inches,
centimeters, or pixels. For example:
H2 {text-indent: 0.5cm}
causes your level-2 headings to be indented 0.5 centimeters from the left margin. You can
also use negative values to pull the text out into the margins.

Background colors and images


You can use the background attribute to highlight sections of your page by setting a
background color or background image. To set a color, you specify a named color (see
the color attribute above) or use an RGB color value:
{background: red}

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


31

{background: #6633FF}
To place an image, you specify the URL in parentheses:
{background:
URL(http://www.microsoft.com/intdev/boxes.gif)}
In Internet Explorer 3.0, you can use backgrounds on any element. You can also use the
repeat, scroll, and position parameters to create special effects with background images.
Repetitions: The values repeat-x, repeat-y, repeat, and no-repeat determine,
respectively, whether the background image is repeated horizontally, vertically, in both
directions (default), or not at all.
Scrolling: The values fixed and scroll (default) determine whether the image is fixed on
the page or scrolls with content.
Position: You can specify the position of the background image with respect to the
element by specifying horizontal and vertical offsets. You can either use the keywords
left/center/right and top/middle/bottom, percentage values, or distances in points,
centimeters, inches, or pixels. For example:
{background:
URL(http://www.microsoft.com/intdev/boxes.gif) 0% 100%}
or
{background: URL(http://www.microsoft.com/intdev/boxes.gif) left
bottom}
places the image at the lower left. See Cascading Style Sheets, Level 1 for
additional examples of background image positioning.

Tips & Tricks


Designing for Multiple Browsers
If you're using embedded styles, you need to make sure that your style definitions do not
get displayed as regular text in browsers (such as Netscape) that don't support style
sheets. (Netscape will ignore the <STYLE> and </STYLE> tags, but will interpret the
style definitions in between these as regular text, because they are not enclosed in angle
brackets. To fix this, embed your style block within a comment, as follows:
<STYLE>
<!--
BODY {font: 10pt "Arial"}
H1 {font: 15pt/17pt "Arial";
font-weight: bold;
color: maroon}
H2 {font: 13pt/15pt "Arial";
font-weight: bold;
color: blue}
P {font: 10pt/12pt "Arial";
color: black}
-->
</STYLE>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


32

Taking Advantage of Inheritance


The HTML tags on your page follow a chain of inheritance. The top-level (parent) tag is
<HTML> followed by <BODY>. If you assign styles to the <BODY> tag, your tables,
lists, paragraphs, and all other lower-level HTML elements will inherit from it. Thus, to
set the global layout and formatting for your entire page, you can simply assign the
appropriate properties to the <BODY> tag. For example:
BODY {font: 10pt/11pt Arial, Helvetica, sans-serif;
background: url(clouds.gif);
margin-left: 0.5in;
margin-right: 0.5in}
sets the default font, leading, background image, and margins for your entire page. If you
need to override the default for specific elements within your page (for example, you
need tables indented further or your abstract paragraph in smaller type), you can add style
specifications for those tags in your style sheet. The tags you haven't set in your style
sheet will inherit from their parent tags or from <BODY>.

Cascading Style Sheets in Internet


Explorer 4.0
Introduction
With the final release of Internet Explorer 4.0, Microsoft is making good on its
commitment to fully support Cascading Style Sheets (CSS), which were introduced in
Internet Explorer 3.0. The extended control that CSS gives over Web page presentation
and layout in this latest release of the browser is sure to enthrall even the jaded HTML
designer.
CSS, for the uninitiated, is a standard for formatting Web pages that goes well beyond the
limitations of HTML. Promulgated by the World Wide Web Consortium (W3C), the
Internet's standards body, CSS extends HTML with more than 70 style properties that can
be applied to HTML tags. With CSS, Web developers have at their disposal a wealth of
additional formatting options for color, spacing, positioning, borders, margins, cursors,
and more.
Internet Explorer 4.0 includes support for the CSS2 specification , and for the W3C
HTML 4.0 specification , which includes inline styles. For example, the developer
can apply the "cursor" property to any HTML element, causing the mouse pointer to
change when passed over the element.
<SPAN STYLE="cursor:hand;">Give this span a hand.</SPAN>
Result:
Give this span a hand.
In this article, we'll cover the different approaches to applying CSS to HTML documents
and present some of the interesting applications of CSS in Internet Explorer 4.0, with
samples. After reading the article, you'll be able to start applying CSS to your own pages,

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


33

and take advantage of Internet Explorer's support for this standard to create stunning
pages and formatting effects.

Adding CSS to Your HTML Documents


HTML gives the developer a certain level of control over the formatting of a document.
You can set headings (<H1>, <H2>,…), make text bold (<B>) or italic (<I>), define lists
(<UL>, <OL>), and so forth. However, this level of control is fairly limited. For
example, developers have no control over the absolute positioning of items on the page,
and are limited in their ability to control size, spacing, and color of page elements.
Seeking to surpass these limits, developers have resorted to workarounds such as
converting text to graphics, creating complicated table layouts, using images for white
space control, and using proprietary HTML extensions and add-ons.
CSS shatters the HTML barrier by putting at the developer's disposal a set of standard
properties specifically geared towards page formatting and layout. These properties are
applied to the document without modifying the underlying HTML. Browsers that are not
CSS-compliant will still see the page in its unaltered HTML state, while browsers that
support CSS will see the page in all its CSS-enhanced glory. See Coping with Non-CSS
browsers.
From the designer's perspective, there are two steps to adding CSS styles to an HTML
document: declaring the styles and applying the styles to HTML elements. For example,
"I want some blue, bold, italic text" would be a simple declaration, while "I want all my
document subheadings to be blue, bold, and italic" would be an application of the style.
Unfortunately, we have to do a bit more than simply utter a few statements in front of the
monitor -- at least until voice recognition and HTML editing technologies get more
sophisticated. We need to understand the syntax of declaring CSS styles and the different
ways in which we can apply these styles to our HTML documents.
Once you've mastered these skills, you'll wistfully remember the days when, to change all
of your document subheadings to blue, bold, and italic, you had to manually add <FONT
COLOR> and <I> tags to each subheading (since it was already displayed as bold by
default). With CSS, you just declare one style, perhaps like this:
H3 { color:blue; font-style:italic; }
and you're done. Imagine the possibilities…

Applying CSS Styles to HTML Elements


You can add CSS properties to your documents in four ways:
1. Using inline styles

2. Using an embedded style sheet

3. Using a linked style sheet

4. Using an imported style sheet

Using Inline Styles

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


34

To use an inline style, you add a STYLE attribute to a specific instance of an HTML
element, using the following syntax:
<tag STYLE="property:value; property:value; …"></tag>
For example:
<B STYLE="color:navy;">In the navy.</B>
Result:
In the navy.
An inline style may be applied to any HTML element, from <A> to <XMP>, and
modifies only the specific instance (occurrence in the document) of the element to which
you apply it. In the example above, only that instance of <B> would be navy -- the rest of
the <B> tags in the document would be unaffected.
Using inline styles to format a document allows for great precision, but can be pretty
tedious to code. If you have a lot of styles, the inline style method can also result in a fair
amount of unnecessary code. Inline styles are also somewhat difficult to maintain,
because the CSS properties are scattered around the page.

Using Embedded Style Sheets


To use an embedded style sheet, you define a style block (delimited by the <STYLE
TYPE="text/css"> and </STYLE> tags), which should be placed in the <HEAD> section
of the document. This block consists of a set of style rules, where each rule defines a
style for an HTML element or group of elements. A style rule has two parts:
• A selector that identifies an HTML element or group of elements

• A declaration of the style properties to be applied to that selector

The generic syntax for a style rule is as follows:


selector { property:value ; property:value; … }
Case (or capitalization) is not important in CSS, but syntax is critical: Each style rule
must start with a selector or group of selectors, followed by an open brace ({), followed
by a set of declarations. Each of these declarations ends with a semi-colon and each
property is separated from its value(s) by a colon (:), ending with a close brace(}). As
with script blocks, it is a good idea to contain style rules within SGML comment
delimiters, to hide them from browsers that do not support CSS. For example:
<STYLE TYPE="text/css"><!--

B { text-transform:uppercase; }
P{
border:silver thick solid; background-color:turquoise;
padding:10px; text-align:center;
}

--></STYLE>

<P>Not every paragraph has a silver lining with a <B>bold</B> outlook.</P>


Result:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


35

Not every paragraph has a silver lining with a BOLD outlook.

In the example above, our style sheet has two rules. The first rule declares uppercase text
for the selector <B> (bold). The second rule declares a silver, thick, solid border, a
background color of turquoise, a padding of 10 pixels, and centered text for the selector
<P> (paragraph). According to this style sheet, all paragraphs (defined with <P>) in the
document will have these border, color, padding, and text alignment features, and all
bold text defined with the <B> tag will contain uppercase text (in addition to being
bold).
Using embedded style sheets offers greater flexibility and ease of maintenance than using
inline styles. For example, if we wanted to change the background color of all paragraphs
in the document, we would change only one thing: the value associated with the
"background-color" property in the style rule for <P> above. The developer can thus
quickly experiment with different formatting combinations for the document by
modifying existing style rules and adding new ones.

Using Linked Style Sheets


You can keep your style sheet in a separate file and link to it from a document or set of
documents, using a <LINK> tag in the <HEAD> section of the linking document, as
follows:
<LINK REL="stylesheet" TYPE="text/css" HREF="mystyles.css">
The linked sheet (mystyles.css in the example above) consists of a set of style rules,
exactly like an embedded style sheet, except that the style rules are not enclosed in
<STYLE TYPE="text/css"></STYLE> and comment (<!-- -->) tags. Linking to an
external sheet allows the developer to apply a set of styles across a group of HTML
documents, thus extending the benefits of embedded style sheets to a set of pages.

Using Imported Style Sheets


An external style sheet may also be imported into a document by using the @import
property in a style sheet:
@import: url(mystyles.css) ;
The @import tag should appear at the beginning of a style block or on a linked sheet,
before any declarations. Rules in imported style sheets are applied before other rules
defined for the containing style sheet, putting them at the bottom of the "pecking order"
of the importing sheet. (See Cascading and Inheritance).

Which Method Should You Use?


You'll probably want to use inline styles when you want to affect the formatting of only a
small number of distinct elements, and use style sheets, either embedded or linked, when
you want to affect a document or set of documents on a global scale.
You may freely combine the use of linked, embedded, and inline styles in the same
document. For example, you might want to have a master list of styles for all documents,
which all of your pages link to. On each page, you could then have an embedded style

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


36

sheet that adds to or modifies the master styles. Finally, you could use an inline style to
add to an embedded style or modify it for a few instances of an element on a given page.
Wherever the same CSS property is set, the most local declaration takes precedence.
More on this idea of precedence in a bit.
Selectors
So far, we've only used the HTML tag name as a selector for applying style rules. Style
sheets offer two additional selectors, CLASS and ID, which give the designer additional
control over which elements should assume which styles.

HTML Element as Selector


Using the HTML tag as a selector, as we have done in the examples so far, is an excellent
way to apply CSS styles if you want all elements of a given type to appear with the same
formatting. This approach is the more rigid of the three, but it is an excellent way to
enforce formatting consistency across a document. One common use of HTML element
selectors is to modify the appearance of hypertext links in the document:
<STYLE TYPE="text/css"><!--

A { text-decoration:none; }

--></STYLE>
This will cause all instances of the Anchor tag, <A>, to appear without the default
underline normally associated with links.
Result:
This is a link and this is another.

CLASS as Selector
If you expect to have formatting variations for different instances of a single element, or
you would like to have different elements share the same format, using a class name as a
selector is a good approach. This is often referred to as "sub-classing" an element.
CLASS is an HTML attribute that has no display characteristics and that you can apply to
any element, like this:
<B CLASS="clsRed">Classy, red, and bold</B>
The style rule for clsRed could be declared as follows:
<STYLE TYPE="text/css"><!--

.clsRed { color:red; }

--></STYLE>
Note that the selector begins with a period (.), which is the required syntax for class
names as selectors. If we add the above rule to the style sheet, every element to which we
assign a class name of clsRed will have red text. If an element doesn't have this class
name, even if it is of the same type as another element that does, it will not have this style
applied.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


37

<B CLASS="clsRed">Classy, red, and bold.</B> <BR>


<I CLASS="clsRed">Red italic.</I> <BR>
<B>Just bold</B> and <I>just italic.</I>
Result:
Classy, red, and bold.
Red italic.
Just bold and just italic.
The choice of class names is one of personal preference; developers can choose whatever
naming scheme makes sense. Classes are often defined in terms of their formatting, as in
the case above. They can also be defined in other, more generic, terms; for example:
<STYLE TYPE="text/css"><!--

.clsImportant {
color:red; font-weight:bold;
text-decoration:underline;
}
.clsCode { font-family:Courier; font-size:10pt; }

--></STYLE>
The style rule applied to class clsImportant turns text red, bold, and underlined. Elements
of class clsCode will contain text that is of a specific font family (Courier) and size (10
pt). In both cases, we can go back and change the style declaration to a different color,
and the class name will still make sense.
I personally like to preface a class name with "cls" to help identify it as a class name.
(This convention is especially useful for scripting.) Again, you are free to adopt my
conventions, or use any other naming scheme you find useful.

ID as Selector
Like CLASS, ID is an HTML attribute that does not affect the display of an element and
can be applied to any element. In general, while class names are usually given to groups
of element instances sharing some common function or format (relative importance,
context, and so on), ID is used to identify one specific instance of an element.
Style rules selected by the ID attribute are declared using the pound sign (#) to precede
the selector, as follows:
<STYLE TYPE="text/css"><!--

#idPinkP { color:pink; text-indent:10px; font-size:12pt; }


#idBoldItal { font-weight:bold; font-style:italic; }

--></STYLE>

<P ID="idPinkP">
...je vois la vie en <SPAN ID="idBoldItal">rose</SPAN>...</P>
Result:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


38

...je vois la vie en rose...


Note that we closed the paragraph with </P>, which tells the browser that the style
associated with the <P> element should no longer be applied.
ID thus serves as a reference to a single instance of an element on the page. As such, you
may have noted, using ID as the selector is basically the same as using an inline style for
a specific element. The only added benefit of using ID is that all the style declarations
can be kept together at the top of the page, which makes it easier to modify existing styles
and to keep track of what is going on as you begin applying styles to your documents.
[Note to scripters: If you are scripting styles, there is an advantage to using inline styles:
An inline style property value is exposed as a property value of the style object, whereas
a style applied in a style sheet is not. In either case, inline or embedded, you can modify
the value of the style object, but you can examine its initial value only if it is set with an
inline style.]

Grouped Selectors
If more than one selector share the same style, they may be grouped in a single rule,
separated by commas. This is done mainly to reduce document weight. For example, if
heading levels 1 to 3 share the same font-face and color, we can combine the selectors
into one declaration, as follows:
<STYLE TYPE="text/css"><!--

H1, H2, H3 { font-family:Tahoma; color:indianred; }

--></STYLE>

Contextual Selectors
If you want a given style to apply to instances of one selector inside of another (such as
<I></I> tags that occur inside of <B></B> tags), you can declare the drill-down to the
desired content with a contextual selector.
A contextual selector is a series of space-delimited individual selectors in a declaration,
such as:
<STYLE TYPE="text/css"><!--

H4 I { color:moccasin; }

--></STYLE>
Here, only instances of <I> within <H4> will have the style declared above.

Choosing Selectors
You will probably find yourself using a combination of the selector types above
depending on the complexity of the document, the universality of the style property, and
your own personal preferences. All three methods may coexist harmoniously, as in the
following example:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


39

<STYLE TYPE="text/css"><!--

BODY { background-color:ivory; }
P { padding:10px; }
.clsCode { font-family:Courier; font-size:10pt; }
#idPara1 { text-align:right; letter-spacing:2pt; }
#idPara2 { text-align:left; }

--></STYLE>
Here's what a paragraph of class name clsCode and ID idPara2 will look like:
<P ID="idPara1">
Some spacey, right-aligned text.
</P>
<P ID="idPara2" CLASS="clsCode">
Some left-aligned, code-ish looking text.
</P>
Result:

S o me sp ac e y, r ig ht - a l ig n e d t e xt .
Some left-aligned, code-ish looking text.

A Note on <DIV> and <SPAN> Elements


Just as CLASS and ID appear to have little use beyond setting styles (and scripting), the
two HTML elements <DIV> and <SPAN> are almost exclusively used as containers for
CSS properties.
<DIV> and <SPAN>, like CLASS and ID -- but unlike other HTML elements -- have no
inherent display characteristics, with one exception each. <DIV> defines a block
consisting of text and HTML tags, and separates this block from surrounding content by
line breaks, while <SPAN> is an inline element which "flows" in with surrounding
content. A quick example should make this distinction clear:
<STYLE TYPE="text/css"><!--

DIV { background-color: black; color:red; font-weight:bold; }


SPAN { background-color: royalblue; color:white; }

--></STYLE>

<P>Some text about to run into a big DIV tag


<DIV>I am a DIV</DIV> and narrowly escape.</P>
<P>Some text about to flow seamlessly into a SPAN tag
<SPAN>I am a SPAN</SPAN> and make a smooth getaway.</P>
Result:
Some text about to run into a big DIV tag
I am a DIV

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


40

and narrowly escape.


Some text about to flow seamlessly into a SPAN tag I am a SPAN and make a smooth
getaway.
A <DIV> is used to create a "box" container that the designer wishes to separate from the
rest of the document content and (optionally) assign box properties such as borders and
margins (see CSS Reference Table). <SPAN> is often used to affect just a portion of text
within a block-level element, such as a paragraph. You will note also from the sample
above that the width of a <SPAN> is limited to the text which it contains, while <DIV>,
like <P>, extends by default over the entire width of the page. This is another distinction
between box and inline elements. (You can control the width of a <DIV> with the
WIDTH style property.)
Using <SPAN> and <DIV> elements to apply styles can be tricky. In general, I
recommend limiting the use of these two elements, especially if you need to
accommodate browsers that don't support CSS. These browsers won't recognize the tags,
and hence won't be able to do anything with <DIV> and <SPAN>, so any formatting
you've applied will be lost. Instead of using a set of sub-classed <SPAN> elements to
apply a style to your text, consider using another HTML element, such as <B> or
<STRONG>, as your selector in the style sheet. And if you can, try replacing <DIV>s
with sub-classed <P> elements. Of course, if you don't need to accommodate non-CSS
browsers, you can <DIV> and <SPAN> to your heart's content!
Cascading and Inheritance
Since the style sheets we are discussing are called Cascading Style Sheets, you may have
been wondering when the first of these three words would finally be mentioned. Now is
the time. Simply stated, "cascading" in CSS specifies how an element instance may
properly be affected by styles of different types (inline style, embedded style sheet,
linked style sheet, imported style sheet) and selected in a number of ways (element tag,
class, ID). The logic is simple: CSS cascades from general to specific, and from top to
bottom.
Take the case of our paragraph with the ID idP1 below:
<STYLE TYPE="text/css"><!--

BODY { background-color:salmon; }
P { margin-left:20px; }
.clsCode { font-family:"Comic Sans MS"; font-size:10pt; color:navy;}
#idP1 { text-align:left; font-weight:bold; }

--></STYLE>

<P ID="idP1" CLASS="clsCode">Multiple styles, no conflicts.</P>


Result:
Multiple styles, no conflicts.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


41

idP1's formatting is affected by the style rules for <BODY>, <P>, clsCode, and idP1.
These potentially conflicting styles are resolved through the laws of cascading and
inheritance.
This means that first, the <BODY>-selected style (background-color) is applied,
followed by the <P>-selected style, clsCode, and finally, idP1, with each style taking
precedence over the previous one. If we had an inline style defined as well, it would have
been applied last, overriding all others. In the cascade, for the same element, a rule with
ID as the selector takes precedence over a rule with CLASS as the selector. CLASS, in
turn, takes precedence over the HTML element name as selector. This is referred to as
"specificity" of the selector. The order of specificity, from greatest to least, is: (1) inline
styles; (2) ID; (3) CLASS; and (4) HTML element.
Since there were no conflicting style assignments -- for example, the background color
for the paragraph was set only in the <BODY> rule, and the font size was set only in the
clsCode style rule -- the styles "trickled down" to the next selector unaltered.
In the case of conflicting assignments with identical selectors, a style selected by a
selector of greater specificity takes precedence. For example, let's apply a color value
(white) to the #idP1 declaration. This will "conflict" with the color value specified in the
.clsCode specification. Since #idP1 has greater specificity, its color (white) will win out
over the previously set color (navy).
<STYLE TYPE="text/css"><!--

BODY { background-color:salmon; }
P { margin-left:20px; }
.clsCode { font-family:"Comic Sans MS"; font-size:10pt; color:navy;}
#idP1 { text-align:left; font-weight:bold; color:white; }

--></STYLE>

<P ID="idP1" CLASS="clsCode">Multiple styles, one conflict.</P>


Result:
Multiple styles, one conflict.

This trickling-down, or "pecking order," of styles is governed to some extent by


inheritance, which works hand-in-hand with cascading. The rules of inheritance specify
which style properties trickle down in the cascade, and which don't. For example, the
"font-family" value we specified in the .clsCode rule above trickled down because it is an
inherited property. Had we applied a "padding" style to BODY, this style would not have
been inherited by idP1, because the "padding" property does not inherit.
You may note in the CSS Reference Table below that background properties are not
inherited. Yet, the "salmon" background-color set in the BODY style rule in our
examples above appears in the paragraph. This is because the default value for
background is "transparent," so while the property itself is not inherited, it "shines
through" unless an opaque color is specified for the element(s) in question.
So, style declarations inherit almost all properties from their predecessors (in the cascade)
and pass them on unaltered, unless the encountered style declaration sets a value for the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


42

same CSS property, as in the example above. (See the CSS Reference Table below for a
quick overview of which properties are inherited and which are not.) This means that you
can declare a font-family of "Wingdings" for your <BODY> at the very top of the
document, and know that your entire document will have this font.
In summary, cascading establishes the order in which multiple style assignments are
evaluated for a given element, and inheritance specifies which style properties are passed
on (and which are not) from one element to another in that order.
This is a very brief discussion of cascading and inheritance. There are exceptions to the
rules (after all, what's a good law without some elements that break the rules?), and
certain properties apply only to a limited number of elements. For more information on
cascading and inheritance, please see the relevant sections on this site and in the W3C
CSS2 specification .
Some Implications of CSS for HTML Design
The extensive level of CSS support in Internet Explorer 4.0 means that developers
targeting a popular browser can, for the first time, use CSS as their primary formatting
medium, rather than employing other non-standard and time-consuming approaches such
as those mentioned in the introduction to this article.
Depending on how you currently author your HTML documents, putting the power of
CSS to use may cause you to adopt some interesting new approaches to how you code.
I'll mention a few here, and invite you to share your own experiences and insights via the
e-mail address at the end of this document.

Return to Basics
Perhaps the most notable and immediate effect of using CSS is that the HTML in your
documents becomes significantly cleaner as you lose the need to stuff your document
with tags whose sole purpose is layout tweaking (what I call "twags"). An extension of
this is that, no longer needing to use "twags" such as <FONT FACE=…>, <FONT
SIZE=…>, and <FONT COLOR=…>, you may find yourself returning to long-forgotten
basic elements like the full range of heading tags (<H1>...<H7>), <STRONG>, <OL>,
and such.
CSS allows a return to the basics of HTML, which should bring a collective sigh of relief
from designers around the world. You will find that your code becomes lighter, cleaner,
and easier to read as you begin to use CSS.

Focus on Structure
Once freed from the tyranny of "twags," you should find yourself able to focus again on
having your HTML actually reflect the structure of your documents. The separation of
document structure from formatting is one of the great benefits of CSS. You can, for
example, define seven levels of headings in "pure" HTML, focusing entirely on their
importance in the flow and structure of your documents. Then, with a linked style sheet,
you can control the formatting of these headings in a globally consistent fashion.
You want one of your sub-headings to be red, small-caps, with a negative margin relative
to the document body? No problem. Define this header according to its function in the
document, <H6> for example, and then declare a style in a linked sheet as follows:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


43

H6 { color:red; font-variant:small-caps; margin-left:-5px; }


That's it. Formatting is separated from content, style from structure. The important
consideration, as you design your documents, becomes using basic HTML tags to
"group" elements that share the same function in your documents. The formatting is
applied subsequently using CSS.

Rapid Application Development


The combination of simple HTML tags and CSS has another wonderful implication for
designers: speed of deployment and prototyping. You can develop a full-blown prototype
of a page with much greater control and precision, and in a fraction of the time that it
would take if you had to use "twags." In addition, changes in formatting, being separate
from document structure, can be completed in the time that it takes to modify a single
style rule. This is significantly faster than modifying individual HTML tags in your
documents, even for those of you who have mastered the art of global search and replace.
Your boss decides that she wants those <H6> subheadings to be violet in color and
lowercase? No problem; change the single style rule's color value and replace the font-
variant property with a text-transform property as follows:
H6 { color:violet; text-transform:lowercase; margin-left:-5px; }
Refresh the document and there you go. All 42 instances of <H6> reflect the new style.
Happy boss, happy you.

Master Templates
You may even find yourself using the time you save with CSS to be a little creative
<gasp> and create a few CSS templates that you can apply to your documents with the
virtual flip of a switch. Even if creativity isn't in your job definition, there are significant
benefits to creating a template for your HTML documents, including savings in time,
improvements in quality and consistency, the ability to quickly prototype and test various
formatting options, and the ability to apply theme-based styles.
I've created a sample that demonstrates one possible scripted approach to using templates.
(I hope that the functionality of the sample will overcome any aesthetic transgressions I
may have committed.) The sample has a menu bar from which you can select one of four
named styles, and a script that loads one of the four styles at random when the page is
loaded or refreshed. Be sure to take a look at the simplicity of the HTML source code as
well as the CSS in the linked sheets. For those of you who'd like to download and play
with the code, I've also provided a zip archive of the HTML document and linked sheets.
View the template sample (requires Internet Explorer 4.0).
Download the zipped files (8K).

Coping with Non-CSS Browsers


Even if you need to use "twags" to serve lesser, non-CSS browsers, CSS can still be a
useful tool for rapid proofing and design. You can use CSS to play with different layouts
and color schemes, and add twags once you've decided on a look. Start with pure HTML,
add CSS, and, finally, add the twags for the other browsers.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


44

Internet Explorer 4.0 will interpret the CSS and ignore twags which conflict, while non-
CSS browsers will not interpret the CSS, and use the twags. So you'll still get the benefits
of rapid development and precise control that CSS provides, while catering to lesser
browsers.

Internet Explorer 3.0 vs. 4.0 Compatibility Issues


Due primarily to the evolution of the CSS standard since the release of Internet Explorer
3.0 last August, you may find that CSS-enhanced pages designed for Internet Explorer
3.0 don't render as nicely in Internet Explorer 4.0, and vice versa. I'll cover some basic
differences between the two versions and then suggest a solution.
Internet Explorer 4.0 adds support for a number of new CSS properties (these are listed in
the CSS Reference Table). Apart from these, the major CSS differences between versions
3.0 and 4.0 are in three areas: margins, font-size, and background.
Area 3.0 Behavior 4.0 Behavior
Margins Value is in addition to the default Value is absolute for the element
for the element. (default will not apply).
Font size (specified as percentage) Value is relative to the element's Value is relative to the parent
default size. element's font size.
Background (in block elements such Fills the color behind the text Fills the color to the margins of the
as <P> and <DIV>) only. parent element.
One way to handle these differences is to use a script in the <HEAD> section of your
HTML document to detect the browser and link the appropriate external style sheet, as
follows:
<SCRIPT LANGUAGE="Javascript"><!--

var bIsIE = navigator.appName == "Microsoft Internet Explorer" ;


var bIsIE4 = bIsIE && parseInt(navigator.appVersion) == 4 ;
if (bIsIE4) {
sCSS = '<LINK REL="stylesheet" TYPE="text/css" HREF="IE4.css">'
}
else {
if (bIsIE) {
sCSS = '<LINK REL="stylesheet" TYPE="text/css" HREF="IE3.css">'
}
}
document.write(sCSS) ;

//--></SCRIPT>
CSS Reference Table
The table below provides a comprehensive list of all CSS-1 and CSS-2 properties
(marked with a superscript 2 ) supported by Internet Explorer 4.0. Each property is listed
by property name, followed by a list of valid values and a sample declaration. The
"Applies to" column indicates the HTML element types to which you can assign this
property. The "Inherited" column indicates whether the property is inherited by

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


45

subsequent elements in the document. Finally, the "IE4" column indicates whether a
property is new, improved, or unchanged in Internet Explorer 4.0, as shown below:
Color Notation Means
Green N New in Internet Explorer 4.0
Light blue I Improved in Internet Explorer 4.0
Light gray -- Same in Internet Explorer 3.0 and 4.0
Note: You can also view the following set of tables in a separate window.

Font Properties
These seven properties control typography in the document. (See Example 1.)
Applies
Property Valid Values Sample Usage Inherited? IE
to
font- [ [ family-name | { font-family: Verdana, MS Sans Serif; } all yes --
family generic-family ], ]* elements
[ family-name |
generic-family ]
font-style normal | italic { font-style:italic; } all yes --
elements
font- normal | small-caps { font-variant:small-caps: } all yes I
variant elements
font- normal | bold { font-weight:bold; } all yes I
weight elements
font-size [ xx-large | x-large | { font-size:12pt; } all yes I
large | medium | elements
small | x-small | xx-
small ] | [ larger |
smaller ] |
percentage | length
font [ font-style || font- { font: bold 12pt Arial; } all yes I
variant || font- elements
weight ] ? font-size [
/ line-height ] ? font-
family
@font- font-family: font- @font-face { font-family: CoolFont; all yes N
face2 family; src:url(url) src:url(http://myserver.com/CoolFont.eot); } elements

Color and Background Properties


These seven properties control the color of the text and the background, as well as the
placement and properties of an optional background image. (See Example 2.)
Property Valid Values Sample Usage Applies to Inherited? IE
color color { color:salmon; } all elements yes --
background- color | transparent { background-color:crimson; all elements no N
color }
background- url | none { background- all elements no N
image image:url(bgWood.jpg); }
background- repeat | repeat-x | repeat-y { background-repeat:no- all elements no N
repeat | no-repeat repeat; }
background- scroll | fixed { background- all elements no N
attachment attachment:fixed; }
background- [ position | length ] | {1,2} { background-position: top block-level and no N
position | [ top | center | bottom ] || center;} replaced
[ left | center | right ] elements
background transparent | color || url || { background: silver all elements no I
repeat || scroll || position url(bgRock.jpg) repeat-y }

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


46

Text Properties
These seven properties control text alignment, spacing, and other formatting, such as
underline and case (capitalization). (See Example 3.)
Property Valid Values Sample Usage Applies to Inherited? IE
letter-spacing normal | length { letter-spacing:2pt; } all elements yes N
text- none | underline | overline | { text- all elements no I
decoration line-through decoration:underline; }
vertical-align sub | super | { vertical-align:sub; } inline elements no N
text-transform capitalize | uppercase | { text- all elements yes I
lowercase | none transform:lowercase; }
text-align left | right | center | justify { text-align:center; } block-level yes I
elements
text-indent length | percentage { text-indent:20px; } block-level yes --
elements
line-height normal | number | length | { line-height:5pt; } all elements yes I
percentage

Box Properties
There are 32 box properties that control the formatting of the "box" associated with
"block" and "replaceable" elements (as discussed in detail in the W3C CSS1
Recommendation ). (See Example 4.)
Property Valid Values Sample Usage Applies to Inherited? IE
margin-top length | { margin-top:5px; } block-level no I
percentage | auto and replaced
elements
margin- length | { margin-right:5px; } block-level no I
right percentage | auto and replaced
elements
margin- length | { margin-bottom:1em; block-level no N
bottom percentage | auto } and replaced
elements
margin-left length | { margin-left:5pt; } block-level no I
percentage | auto and replaced
elements
margin length | { margin: 10px 5px block-level no I
percentage | auto 10px 5px; } and replaced
{1,4} elements
padding- length | { padding-top:10%; } block-level no N
top percentage and replaced
elements
padding- length | { padding-right:15px; block-level no N
right percentage } and replaced
elements
padding- length | { padding- block-level no N
bottom percentage bottom:1.2em; } and replaced
elements
padding- length | { padding-left:10pt; } block-level no N
left percentage and replaced
elements

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


47

padding length | { padding: 10px 10px block-level no N


percentage {1,4} 10px 15px; } and replaced
elements
border-top- thin | medium | { border-top- block-level no N
width thick | length width:thin; } and replaced
elements
border- thin | medium | { border-right- block-level no N
right-width thick | length width:medium; } and replaced
elements
border- thin | medium | { border-bottom- block-level no N
bottom- thick | length width:thick; } and replaced
width elements
border-left- thin | medium | { border-left- block-level no N
width thick | length width:15px; } and replaced
elements
border- thin | medium | { border-width: 3px block-level no N
width thick | length 5px 3px 5px; } and replaced
{1,4} elements
border-top- color { border-top- block-level no N
color color:navajowhite; } and replaced
elements
border- color { border-right- block-level no N
right-color color:whitesmoke; } and replaced
elements
border- color { border-bottom- block-level no N
bottom- color:black; } and replaced
color elements
border-left- color { border-left- block-level no N
color color:#C0C0C0; } and replaced
elements
border- color {1,4} { border-color: green block-level no N
color red white blue; } and replaced
elements
border-top- none | solid | { border-top- block-level no N
style double | groove | style:solid; } and replaced
ridge | inset | elements
outset
border- none | solid | { border-right- block-level no N
right-style double | groove | style:double; } and replaced
ridge | inset | elements
outset
border- none | solid | { border-bottom- block-level no N
bottom- double | groove | style:groove; } and replaced
style ridge | inset | elements
outset
border-left- none | solid | { border-left- block-level no N

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


48

style double | groove | style:none; } and replaced


ridge | inset | elements
outset
border- none | solid | { border-style:ridge; } block-level no N
style double | groove | and replaced
ridge | inset | elements
outset
border-top border-width | { border-top: medium block-level no N
border-style | outset red; } and replaced
border-color elements
border- border-width | { border-right: thick block-level no N
right border-style | inset maroon; } and replaced
border-color elements
border- border-width | { border-bottom: 10px block-level no N
bottom border-style | ridge gray; } and replaced
border-color elements
border-left border-width | { border-left: 1px block-level no N
border-style | groove red; } and replaced
border-color elements
border border-width | { border: thin solid block-level no N
border-style | blue; } and replaced
border-color elements
float none | left | right { float:none; } DIV, SPAN, no N
and replaced
elements
clear none | left | right | { clear:left; } all elements no N
both

Classification Properties
These five properties consist of "display" and "list" properties: "display" indicates
whether the element is displayed in the document, and the "list-" properties control the
formatting of HTML lists, such as <UL> and <OL>. (See Example 5.)
Property Valid Values Sample Usage Applies to Inherited? IE
display none | block | { display:none; } TABLE, INPUT, no N
inline | list- TEXTAREA,
item INPUT
type=button, DIV,
SPAN, IFRAME,
IMG, BODY,
MARQUEE,
SELECT
list-style- disk | circle | { list-style- list-item elements yes N
type square | type:upper-alpha; }
decimal |
lower-roman |
upper-roman |

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


49

lower-alpha |
upper-alpha |
none
list-style- url | none { list-style- list-item elements yes N
image image:url(icFile.gif);
}
list-style- inside | { list-style- list-item elements yes N
position outside position:inside; }
list-style keyword || { list-style: square list-item elements yes N
position || url outside
url(icFolder.gif); }

Positioning Properties
These nine properties provide a powerful level of control over the two- and three-
dimensional appearance of elements in the document. CSS positioning merits special
coverage both in the DHTML, HTML & CSS section of the MSDN Online Web
Workshop and in the W3C documents, and is worthy of special study. (See Example 6
and Example 7.)
Property Valid Values Sample Usage Applies to Inherited? IE
clip shape | auto { clip:rect(0px 200px all elements no N
200px 0px); }
height length | auto { height:200px; } DIV, SPAN and no N
replaced elements
left length | { left:0px; } absolutely and no N
percentage | relatively
auto positioned elements
overflow visible | hidden | { overflow:scroll; } all elements no N
scroll | auto
position absolute| { position:absolute; } all elements no N
relative | static
top length | { top:0px; } absolutely and no N
percentage | relatively
auto positioned elements
visibility visible | hidden | { visibility:visible; } all elements no N
inherit
width length | { width:80%; } DIV, SPAN and no N
percentage | replaced elements
auto
z-index auto | integer { z-index:-1; } absolutely and no N
relatively
positioned elements

Printing Properties
These two properties allow the developer to specify exact locations for page breaks that affect the
printing of the document.
Property Valid Values Sample Usage Applies to Inherited? IE
page-break- auto | always || { page-break- block-level no N

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


50

before left | right before:always; } elements


page-break- auto | always || { page-break- block-level no N
after left | right before:auto; } elements

Filter Properties
The three filter properties represent another important topic that deserves separate study.
Almost all filter properties are applied using scripting. (See Example 8.)
Applies
Property Valid Values Sample Usage Inherited? IE
to
Visual filtername(fparameter1, { filter:FlipH(enable=1) } all no N
Filter2 fparameter2) elements
Reveal RevealTrans(duration=duration, { all no N
Transition transition=transitionshape) filter:revealTrans(duration=1.0, elements
Filter2 transition=12); }
Blend BlendTrans(duration=duration) { filter: blendTrans(duration = all no N
Transition 1.5) } elements
Filter2

Pseudo Classes and Other Properties


This catch-all category includes three properties: the @import property, used to import
an external style sheet into an existing style sheet (as explained in Using Imported Style
Sheets); the cursor property controls the appearance of the mouse pointer as it passes
over the element (as shown in Introduction); and the !important property, used to
override the default cascade for a given style. It also contains four pseudo-classes for the
A attribute.
Applies
Property Valid Values Sample Usage Inherited? IE
to
@import url(url) @import style yes N
url(mystyles.css); sheets
cursor2 auto | crosshair | default | hand | move { cursor:hand; } all yes N
| e-resize | ne-resize | nw-resize | n- elements
resize | se-resize | sw-resize | s-resize |
w-resize | text | wait | help
!important !important { font- style no N
weight:bold!important } sheets
active, hover2, n/a a:hover { color:red; } all yes I
link, visited elements

Internet Explorer 4.0 CSS Examples


The samples in this section require Internet Explorer 4.0.
Example 1: Font properties
Example 1 uses font properties to enhance the appearance of a line of text. Note that the
font property allows the grouping of the "font-" properties into one declaration.
Example 2: Color and background properties
Example 2 uses color properties to add color to the text in Example 1. Note that the
HTML is exactly the same as in Example 1; only the CSS style rules have changed.
Example 3: Text properties

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


51

Example 3 aligns four paragraphs differently, and modifies the text formatting to
highlight the text-align value in question.
Example 4: Box properties
Example 4 uses scripted dynamic styles to show the formatting that may be applied to an
element's border.
Example 5: Classification properties
Example 5 uses both types of classification properties (display and list) to control the
appearance of an unordered list.
Examples 6 and 7: Positioning properties
Example 6 uses positioning to create a colorful presentation consisting overlapping text.
Example 7 combines positioning, box, and color properties to show the level of control
over HTML elements. In this case, both a <TEXTAREA> and a <DIV> are formatted to
look like an <IFRAME>.

CSS Positioning
Introduction
Most of you who have any involvement in authoring for the World Wide Web have probably by
now heard about Cascading Style Sheets (CSS). CSS was created by several companies under the
supervision of the World Wide Web Consortium (W3C), the primary Internet standards
organization, to add powerful formatting capabilities to standard HTML. The first level of the
CSS specification, Cascading Style Sheets, level 1 (CSS-1), was put forth as a recommendation
(the W3C's terminology for "finalized") in December 1996, and the second level (CSS-2) in May
1998. Internet Explorer 4.0 supports virtually all of CSS-1 and portions of CSS-2 that were in
place upon its release.
You may also have heard the term "CSS positioning." If you're like me, you may have
wondered not only what it is, but what its relationship is with CSS. Is CSS positioning
just another part of CSS, or is it something special? The answer is both. To explain how
CSS positioning fits in with CSS in general, let's have a look at the categories of
properties found in CSS:
Table 1. Categories of CSS Properties
Category Description
Font Typography properties
Color and Background Color of text and background, and background image
properties
Text Text alignment, spacing, and formatting
Box Box formatting properties
Classification Display and list properties
Positioning Positioning and flow control of elements
Printing Page break specification
Filter Multimedia effects and transitions
Pseudo-Classes and Other The @import, cursor, and !important properties
Properties

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


52

As you can see, positioning is just one sub-category of properties available within CSS.
However, because it is one of the most powerful, important, and useful aspects of CSS, it
has acquired its own informal name. Indeed, the W3C addresses CSS positioning in an
entirely separate specification, entitled Positioning HTML Elements with Cascading
Style Sheets . It is currently in Working Draft status, meaning that not all of the
functionality has been finalized. This article focuses on the information found in that
document.
That document gives complete and detailed information about CSS positioning. If you
have already read and thoroughly understood it, you probably won't need to continue
with this article. And furthermore, you should be proud of yourself! CSS positioning is a
powerful and flexible set of features, and it was obviously architected by some smart
people. And characteristically, when smart people get together and write a specification,
they don't always explain things at a level suitable for some us more ordinary humans.
When I set out to learn about positioning, I found that I had to read the specification
several times through and then create some of my own test pages before I fully
understood it (particularly how the position property affects the placement of elements
and flow of the document). So I decided it might be nice to try to explain the subject in
lighter terms, more suitable for those newer to HTML and CSS authoring. A secondary
goal of this article is that we feel that CSS positioning is a particularly useful and
powerful feature set of Internet Explorer 4.0, and it is worth calling special attention to it.
In order for this article to be useful, it's important that you have a basic understanding of
HTML authoring. And although you can probably understand what's going on in the
article without much knowledge of CSS, you'll want to be familiar with all of CSS before
you begin authoring your own Web pages. Information about CSS can be found in the
DHTML, HTML & CSS section of the MSDN Online (SBN) Workshop, and in the W3C
recommendation for Cascading Style Sheets, level 1 .

Overview of Properties
Nine properties are considered part of CSS positioning; they are listed in the following table, part
of which I shamelessly pilfered from George Young's CSS article in the Web Workshop.
Table 2. CSS Positioning Properties
Property Description Possible values Applies To
position Makes elements absolute | relative | All elements
positionable static
left Left position of element length | percentage | Absolutely and relatively
auto positioned elements
top Top position of element length | percentage | Absolutely and relatively
auto positioned elements
height Height of element length | auto DIV, SPAN and replaced
elements
width Width of element length | percentage | DIV, SPAN and replaced
auto elements
visibility Controls visibility visible | hidden | All elements
inherit
z-index Layering control auto | integer Absolutely and relatively
positioned elements
clip Defines visible area of shape | auto All elements

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


53

element
overflow Specifies behavior on visible | hidden | All elements
overflow scroll | auto
Before we go into details of the individual properties, let's get some terminology out of
the way.
How some of the properties are implemented depends on the hierarchical relationships
between elements. For our purposes, the <BODY> tag is at the top of the hierarchy for a
given HTML document. An element is the child of another element if it is nested within
the tag of another element. The enclosing element is called the parent element. A sibling
of an element is one that shares a parent. And the previous element refers to the element
that immediately precedes an element in the source file, regardless of whether it has a
parent, sibling, or no relationship.
The origin for a given element is where the 0,0 coordinate pair is located, from which the
top and left properties are offset (we'll go into detail about this later). Each element has
its own origin, which depends on the value of its position property as well as its location
within the hierarchy of elements.
The flow of the document refers to the natural way the content "flows" into the browser
window, which may or may not change (depending on the values of certain properties) as
the browser window is resized.

Position Property
The position property can be set to one of three values: absolute, relative, and static.
The default is static. The position property is one of the more complex of the positioning
properties: the interactions between the values of the position property, the top and left
properties, and location of the element within both the hierarchy and the source file
location can be a little tricky to understand. Consequently, this explanation of the
position property forms a large part of this article.
position: absolute
Calculating where an absolutely positioned element will be rendered is fairly
straightforward. Absolutely positioned elements and their children are not part of the
regular flow of the document, but are positioned independently, possibly overlapping
other elements.
To calculate the origin of an absolutely positioned element, find the next parent element
that is positioned either relatively or absolutely (that is, if a parent is static, skip it and go
up the hierarchical chain to the next parent. If the <BODY> tag is reached, the traversal
stops and it will be considered the parent element regardless of the value of its position
property). The logical beginning of this parent element is the origin for the absolutely
positioned element. That origin may or may not move as the window is resized, but the
element will always be in the same place with respect to that origin.
The origin establishes the top left corner of a rectangle into which the absolutely
positioned element and its children will flow. These three samples demonstrate the origin
calculation for an absolutely positioned element. I've pulled out the relevant lines of code,
and you can click on the link to run the sample.
Please note that you need to view this article's samples using Internet Explorer 4.0 or
later.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


54

Sample 1: Absolutely positioned element with statically positioned parent


<SPAN STYLE="position:static;
background-color:#90EE90">static green parent static green
parent
static green parent static green parent
<SPAN STYLE="position:absolute; top:60px; left:60px;
background-color:#ADD8E6">absolute blue child
absolute blue child absolute blue child absolute blue
child</SPAN>
</SPAN>
Sample 2: Absolutely positioned element with relatively positioned parent
<SPAN STYLE="position:relative;
background-color:#90EE90">relative green parent relative
green parent
relative green parent relative green parent
<SPAN STYLE="position:absolute; top:60px; left:60px;
background-color:#ADD8E6">absolute blue child
absolute blue child absolute blue child absolute blue
child</SPAN>
</SPAN>
Sample 3: Absolutely positioned element with absolutely positioned parent
<SPAN STYLE="position:absolute;
background-color:#90EE90">absolute green parent absolute
green parent
absolute green parent absolute green parent
<SPAN STYLE="position:absolute; top:60px; left:60px;
background-color:#ADD8E6">absolute blue child
absolute blue child absolute blue child absolute blue
child</SPAN>
</SPAN>
In the first sample, because the parent is statically positioned, we "ignore" this and look
to the next element in the hierarchy. In this case it's the BODY element, so we use the
beginning of the BODY (that is, the beginning of the document) as the origin. In the other
two examples, the parents of the absolutely positioned blue element are relatively and
absolutely positioned, so they are used to establish the origin. So the blue text is
positioned in the same place in the second and third examples (60 pixels below the top of
the green element), which is slightly lower than in the first one (60 pixels lower than the
top of the BODY element). In all three cases, the blue text is absolutely positioned, so no
matter how you resize the window to make the green text flow, the blue text begins at the
same location, and will overwrite the green text if necessary.
The way that the top and left properties are used also helps determine where an
absolutely positioned element is positioned. If the element has its top and left properties
set, the element will be positioned using these offsets with respect to the origin that we
just talked about. If the top property is omitted or is set to auto (which is equivalent

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


55

because auto is the default), the element will have its top edge beginning at the top of the
last line of text of the parent element if it's text, and lined up with the top edge of the
parent if it's an image. If the left property is omitted, the element will have its left edge
positioned at the end of the last line of text of the parent element if it's text, and at the
right edge of the parent if it's an image.
Following are four samples that demonstrate this. Be sure to resize the windows to see
how changing a parent's position affects its absolutely positioned child. You can
substitute the "relative green parent" text with an image to see the behavior when the
parent is an image.
Sample 4: Absolutely positioned element with neither top nor left set
<SPAN STYLE="position:relative;
background-color:#90EE90">relative green parent relative
green parent
relative green parent relative green parent relative green parent
relative green parent
relative green parent relative green parent
<SPAN STYLE="position:absolute;
background-color:#ADD8E6">Absolute blue child with
neither top nor left set.</SPAN>
</SPAN>
In Sample 4, because neither top nor left are set, the origin of the blue element is at the
end of the green one. However, because the green element reflows when the browser
window changes, this origin can actually move around. You'll see how this works if you
make the browser window progressively narrower and watch the blue text.
Sample 5: Absolutely positioned element with top and left set
<SPAN STYLE="position:relative;
background-color:#90EE90">relative green parent relative
green parent
relative green parent relative green parent relative green parent
relative green parent
relative green parent relative green parent
<SPAN STYLE="position:absolute; top:10px; left:50px;
background-color:#ADD8E6">Absolute blue child
with top:10px and left:50px.</SPAN>
</SPAN>
In Sample 5, because both the top and left are set, the origin for the blue element never
moves no matter how narrow you make the browser window.
Sample 6: Absolutely positioned element with just top set
<SPAN STYLE="position:relative;
background-color:#90EE90">relative green parent
relative green parent relative green parent relative green parent
relative green parent
relative green parent relative green parent relative green parent
<SPAN STYLE="position:absolute; top:10px;

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


56

background-color:#ADD8E6">Absolute blue child


with top:10px.</SPAN>
</SPAN>
In Sample 6 we've got only the top set. So, according to the rules, that means the top
value of the origin will never move -- the blue element will always begin 10 pixels from
the top of its (non-static) parent, the green element. But the left value for the origin is set
to auto (by default, because it's not set at all), meaning to the end of the parent (green)
element, so you'll see the left edge of the blue element's rectangle move as you make the
browser window narrower.
Sample 7: Absolutely positioned element with just left set
<SPAN STYLE="position:relative;
background-color:#90EE90">relative green parent relative
green parent
relative green parent relative green parent relative green parent
relative green parent
relative green parent relative green parent
<SPAN STYLE="position:absolute; left:50px;
background-color:#ADD8E6">Absolute blue child
with left:50px.</SPAN>
</SPAN>
Sample 7 is just the reverse of Sample 6; in this case, the left side of the blue element's
rectangle remains constant at 50 pixels, while the top varies depending on where the end
of the green parent element is.
As we've already mentioned, the absolutely positioned element defines a new rectangle
into which it and all of its children flow (and will draw over the top of other elements if
necessary). The box begins at the top left corner of the element. You can set the width
and height properties for the element. If no width property is defined, the rectangle to
will extend to the right edge of the browser window. If a width is defined, it will retain
that width even if the rectangle extends beyond the browser window; that part of the
contents will therefore be obscured. If no height property is defined, the rectangle will
extend as far down as necessary to display all of the contents. (Note that these
descriptions for what happens when either the width or height properties are not defined
represent default behavior; this behavior can be changed by setting the overflow
property, which is discussed later).
Sample 8: Absolutely positioned element with no width or height defined
<SPAN STYLE="position:relative;
background-color:#90EE90">Relative green parent.
<SPAN STYLE="position:absolute; top:50px; left:50px;
background-color:#ADD8E6">absolute blue child
absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child
absolute blue child absolute blue child absolute blue child
absolute blue child
</SPAN>
</SPAN>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


57

Sample 8 shows an absolutely positioned element without width or height defined. You
can see as you make the browser window narrower that the rectangle into which the blue
element flows always extends to the right edge of the browser window, reflowing
downward if necessary.
Sample 9: Absolutely positioned element with width defined
<SPAN STYLE="position:relative;
background-color:#90EE90">Relative green parent.
<SPAN STYLE="position:absolute; top:50px; left:50px;
width:200px; background-color:#ADD8E6">absolute
blue child absolute blue child absolute blue child absolute blue
child absolute blue child
absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child
</SPAN>
</SPAN>
Sample 9 demonstrates the use of the width property. In this case, the width of the blue
element's rectangle remains the same regardless of the width of the browser.
We talked before about how absolutely positioned elements and their children were not
part of the regular flow, but instead create their own rectangle. Sample 10 demonstrates
this. The blue absolutely positioned element defines the origin of its rectangle to be at
50,50 and the width at 250 pixels. Since no height is set, the rectangle extends down as
far down as necessary. The blue element has a red relatively positioned child, and you'll
see that this child flows after the blue element but entirely within the left and right
boundaries of the defined rectangle.
Sample 10: Absolutely positioned element with relatively positioned child
<SPAN STYLE="position:relative;
background-color:#90EE90">Relative green parent.
<SPAN STYLE="position:absolute; top:50px; left:50px;
width:250px; background-color:#ADD8E6">absolute
blue child absolute blue child absolute blue child absolute blue
child absolute blue child
absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child
<SPAN STYLE="position:relative;
background-color:#FFB6C1">relative red child relative
red child relative red child relative red child relative red
child
relative red child relative red child
</SPAN>
</SPAN>
</SPAN>
position: relative

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


58

Figuring out where relatively positioned elements will end up is a little trickier.
Relatively and statically positioned elements form the flow of elements in a document (as
opposed to absolutely positioned elements, which are positioned as if on a layer above
the other elements). To figure out what the flow of elements looks like, look through the
source file, and mentally remove all absolutely positioned elements, including any
children of those elements. Then position the remaining relatively positioned elements
one after another -- this is because for a relatively positioned element, the origin for
element is at the end of the previous element in the flow (not in the source file),
regardless of the hierarchical relationship.
Relatively positioned elements that are children of absolutely positioned elements were
"removed" from the flow as explained above; they are still placed after the end of the
previous element in the source, except that they are now relative to an absolutely
positioned element that can be at any arbitrary place.
This is not easy to explain, but the examples should make it more clear. Samples 11, 12,
and 13 all display identically. Because all are relatively positioned elements with no top
or left properties set, they simply flow one after another, regardless of their hierarchical
relationship with each other.
Sample 11: Three same-level relatively positioned elements
<SPAN STYLE="position:relative;
background-color:#90EE90">Green relative
element.</SPAN>
<SPAN STYLE="position:relative;
background-color:#ADD8E6">Blue relative
element.</SPAN>
<SPAN STYLE="position:relative;
background-color:#FFB6C1">Red relative element.</SPAN>
Sample 12: Three nested relatively positioned elements
<SPAN STYLE="position:relative;
background-color:#90EE90">Green relative element.
<SPAN STYLE="position:relative;
background-color:#ADD8E6">Blue relative child of green.
<SPAN STYLE="position:relative;
background-color:#FFB6C1">Red relative child of blue.
</SPAN>
</SPAN>
</SPAN>
Sample 13: Three relatively positioned elements; the second is a child of the first
<SPAN STYLE="position:relative;
background-color:#90EE90">Green relative element.
<SPAN STYLE="position:relative;
background-color:#ADD8E6">Blue relative child of
green.</SPAN>
</SPAN>
<SPAN STYLE="position:relative;

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


59

background-color:#FFB6C1">Red relative element.</SPAN>


Sample 14 demonstrates how absolutely positioned elements are not part of the document
flow. Even though the blue element is between the two relatively positioned elements in
the source file, it does not affect the flow of the document. No matter how the window is
resized, the blue element begins at the same location, and the red element flows directly
after the green one.
Sample 14: Relative, absolute, relative
<SPAN STYLE="position:relative;
background-color:#90EE90">green relative element
green relative element green relative element</SPAN>
<SPAN STYLE="position:absolute; top:50px; left:50px;
background-color:#ADD8E6">Blue absolute
element with top:50px and left:50px.</SPAN>
<SPAN STYLE="position:relative;
background-color:#FFB6C1">red relative element
red relative element red relative element</SPAN>
Sample 15 is similar except that the absolutely positioned blue element has a child. As
you can see, the blue element and its child are pulled out of the flow of the document,
while the red element again follows the green one.
Sample 15: Relative, absolute with relative child, relative
<SPAN STYLE="position:relative;
background-color:#90EE90">green relative element
green relative element green relative element</SPAN>
<SPAN STYLE="position:absolute; top:50px; left:50px;
background-color:#ADD8E6">Blue absolute element
with top:50px and left:50px.
<SPAN STYLE="position:relative;
background-color:#FFFFFF">White relative
child of blue.</SPAN>
</SPAN>
<SPAN STYLE="position:relative;
background-color:#FFB6C1">red relative element
red relative element red relative element</SPAN>
Now, when we start setting the top and left properties of the relatively positioned
elements, things get even more interesting. Let's say we have a relatively positioned
element that has its top and/or left properties set. Another relatively positioned element
that directly follows it in the flow calculates its origin as follows:
• If the following element is a child of the first element, the origin of the following
element is at the end of the first element.

• If the following element is not a child of the first element, the origin of the
following element is at the end of where the first element would have been if it
hadn't had its position altered by the top and left properties.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


60

Confused? Don't feel bad -- I got a bit of a headache myself sorting all this out. Once
again, let's look at some examples to make it easier. These are exactly the same as
Samples 11 and 12, but with the top property set on the center element. You'll recall that
the three displayed identically before regardless of hierarchical relationship, but now they
behave slightly differently.
Sample 16: Three same-level relatively positioned elements
<SPAN STYLE="position:relative;
background-color:#90EE90">Green relative
element.</SPAN>
<SPAN STYLE="position:relative; top:20px;
background-color:#ADD8E6">Blue relative element
with top:20px.</SPAN>
<SPAN STYLE="position:relative;
background-color:#FFB6C1">Red relative element.</SPAN>
In Sample 16, the blue element is offset 20 pixels from the top of where it would have
been. Because the following red element is not a child of the blue element, it is drawn at
the end of where the blue element would have been, had we not adjusted its position
using the top property.
Sample 17: Three nested relatively positioned elements
<SPAN STYLE="position:relative;
background-color:#90EE90">Green relative element.
<SPAN STYLE="position:relative; top:20px;
background-color:#ADD8E6">Blue relative child of green
with top:20px.
<SPAN STYLE="position:relative;
background-color:#FFB6C1">Red relative child of blue.
</SPAN>
</SPAN>
</SPAN>
Sample 17 shows what happens now that the red element is a child of the blue; the
position of the blue element has been altered, and the red element is drawn at the end of
where the blue element now is.
position: static
We already discussed how statically positioned elements are ignored when calculating
the origin for absolutely positioned elements. When mixed in with relatively positioned
elements, statically positioned elements take the same origin as a relatively positioned
element would; the primary difference is that you cannot set or offset the position of a
statically positioned element using the top and left properties. A common mistake is to
attempt to set these properties without first setting the position property to absolute or
relative, (because the default for the position property is static) and then wonder why
they have no effect. And because the top and left properties are meaningless when
position is static, it follows that, as their name implies, a statically positioned element
cannot have its position altered through script.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


61

Visibility Property
The visibility property of an element controls whether the element will be visible on the
page, depending on whether it is set to visible or hidden. Note that even if the property is
set to hidden, the space for the element within the flow of the document remains
allocated. Contrast this with the display property (which is categorized under the
"Classification" properties even though it is functionally related to the visibility
property); when the display property is set to none, the space allocated for the element in
the document flow is relinquished. This example demonstrates the difference between
these two properties:
Sample 18: Comparison of the visibility and display properties (VBScript)
Sample 18: Comparison of the visibility and display properties (JScript)
On the first image, the button preceding it toggles the visibility property between visible
and hidden, while the second button toggles the display property of the second image
between none and the null string. (Note that we use the null string here because none is
the only value that is currently explicitly supported. While specifying inline or block will
appear to work for now, your pages will be rendered differently in the future when these
values are supported. Null will always default to the default value, so it will display the
element without breaking your code in the future.)

Clip Property
The clip property lets you define what portion of an element is visible. It does not affect the amount of space allocated
for the element within the flow of the document.
The sample shows the syntax for setting the clip region initially, using an inline style
sheet or script (the JavaScript and Visual Basic® Scripting Edition (VBScript) versions
are identical except for JavaScript's terminating semicolon). Pay close attention to the
order of the parameters: top, right, bottom, left:
Inline style sheet
<IMG ID=Olivia1 STYLE="position:absolute;
top:0px; left:0px; width:136px; height:228px;
clip:rect(0 136 228 0)" SRC=olivia1.gif>
as well as how to set the clip region in script:
Script
Olivia1.style.clip = "rect(0 136 228
0)"

Overflow Property
The overflow property lets you choose what happens when the contents of an element do not fit within the rectangle
defined by some or all of the top, left, height and width properties. There are four possible values for the overflow
property, that function as follows:
• Visible -- Will expand size of the element to fit all of the contents. This is the default.

• Hidden -- Will clip size of the element to match its declared size.

• Auto -- Will put scroll bars on the element only if the contents exceed the stated size.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


62

• Scroll -- Will put scroll bars on the element regardless of the size of the element.
The following sample demonstrates the behavior for all four values.
Sample 20: The overflow property
Each of the four sections uses identical code (except for the positioning), shown below,
with only the value of the overflow property changed. I've made the background of the
elements white so that you can see how much space the element is utilizing.
<DIV STYLE="position:absolute; top:60px;
left:0px; width:100px; height:100px;
overflow:visible; background-color:white">
This is short.
</DIV>
<DIV STYLE="position:absolute; top:60px; left:200px;
width:100px; height:100px;
overflow:visible; background-color:white">
This is really really really really really really really really
really really really long.
</DIV>

Z-Index Property
The z-index property determines the order in which overlapping elements will be drawn, thereby determining the
visible portion of each. By default, elements are drawn in the order in which they appear; the result is that elements
appearing later in the source will be drawn over the top of earlier ones. The z-index property lets you control the order
in which you want things layered; elements are drawn from lowest to highest z-index values.
Sample 21: The z-index property
This property is very straightforward; the sample just shows the syntax and demonstrates
the drawing order.

Dynamic Positioning
Now that I've gotten through the hard part of explaining absolute and relative positioning, it's time to talk about one of
the fun parts of CSS positioning. Any element that can be positioned either absolutely or relatively can have its position
adjusted dynamically through script. This lets you create animations using any element that supports the position
property. A major upside to using dynamic positioning to create animations is that they run entirely on the client side,
and are therefore more efficient than many server-side solutions.
I'll demonstrate the concept of dynamic positioning in a boring moving-text sample. But
it should be enough to demonstrate the concept; dynamic positioning is very
straightforward to implement. All the same rules that we've already covered about how
elements get positioned still apply.
For example, in this sample, the blue text is a sibling of the red text. As we discussed
earlier, a sibling is positioned relative to the end of the space the preceding element
would have occupied had it not been positioned with the top and left properties. So the
blue text stays put while the red text moves.
Sample 22: Animate with siblings (VBScript)
Sample 22: Animate with siblings (JScript)
On the other hand, in this sample, the blue text is a child of the red text. As our rules
stated, that means it is supposed to be positioned relative to the actual position of the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


63

parent, and sure enough, the blue text faithfully follows the red text around, even though
we never explicitly change its position.
Sample 23: Animate with children (VBScript)
Sample 23: Animate with children (JScript)
Let's have a look at the JavaScript version of the Sample 22 (both samples move the text
the same way; the only difference is the relationship between the two text elements). The
HTML portion of the sample looks like this:
<BODY BGCOLOR=lightgrey
onload="StartMove()">

<SPAN ID=MovingText STYLE="position:relative;


background-color:#FFB6C1">This text
can whiz on and off the page.</SPAN>
<SPAN STYLE="position:relative;
background-color:#ADD8E6">This text
is a sibling of the moving red text.</SPAN>

</BODY>
First, note that when we define the text, we set the position property to be relative.
Remember, even though we don't want to explicitly position the text, position must be
set to relative or absolute to be able to dynamically change the position. In the <BODY>
tag we've specified that the StartMove() function should be called when the page is
loaded. This function looks like this:
function StartMove() {

TextVisible = 1;
action = window.setInterval("MoveText()", 50);
}
We set a variable called TextVisible to 1 to tell ourselves that the text is currently visible.
We just use this variable basically to keep track of which way the text is moving, on or
off the page. Then we set a timer to call the MoveText() function every 50 milliseconds.
function MoveText()
{
if (TextVisible == 0)
{
MovingText.style.pixelLeft += 10;
if (MovingText.style.pixelLeft == 0 )
{
TextVisible = 1;
}
}
else
{
MovingText.style.pixelLeft -= 10;

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


64

if (MovingText.style.pixelLeft == -240 )
{
TextVisible = 0;
}
}
}
Each time this function is called, it checks the value of TextVisible. If it is 0, this means
that the string is still not fully on the page and needs to be moved to the right, so it adds
10 pixels to the value of its left position (the pixelLeft property). It then checks to see if
we are fully on the page (at which time the pixelLeft value will be 0), and if we are, sets
the value of the TextVisible variable to 1. Then in future calls to MoveText(), we subtract
10 pixels from pixelLeft and therefore move the text to the left, off the screen. We keep
doing this until we have moved 240 pixels to the left, then set TextVisible to 0 and the
whole process will repeat itself infinitely. (Note the use of the pixelLeft property rather
than the left property; we need to do this because we're manipulating the value, and left
returns the value as a string where pixelLeft is an integer.)
That's all there is to dynamically positioning elements -- just decide what you want to do,
think about how it will affect the position of other elements on the page, and change the
position according to a timer, a user action, or whatever else meets your needs.

Don't Forget to Test


If you have complex positioning needs, you can get as fancy as you like nesting elements
and manipulating properties to achieve your goals. Or, if you still find this a little
confusing to follow, you can probably do most of what you want to do and understand
your code if you keep it simple and don't nest your elements too deeply. Either way, don't
forget to view your pages in all sizes of browser windows, from the smallest to the
largest, to ensure the results are what you intended.

CSS Attributes Reference


This section defines the supported cascading style sheets (CSS) attributes. An asterisk (*)
indicates the attribute is available as of Microsoft® Internet Explorer 5 or later. If an
attribute or property has been proposed to the World Wide Web Consortium (W3C) but
not yet made standard, it is marked as "proposed."
Behavior properties behavior (proposed)*
Font and text properties direction*
font
@font-face
font-family
font-size
font-style
font-variant
font-weight
ime-mode (proposed)*
layout-grid (proposed)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


65

layout-grid-char (proposed)
layout-grid-char-spacing (proposed)
layout-grid-line (proposed)
layout-grid-mode (proposed)
layout-grid-type (proposed)
line-break (proposed)*
line-height
letter-spacing
ruby-align (proposed)*
ruby-overhang (proposed)*
ruby-position (proposed)*
text-align
text-decoration
text-justify (proposed)*
text-indent
text-transform
unicode-bidi
vertical-align
word-break (proposed)*
word-spacing (Macintosh only)
Color and background properties background
background-attachment
background-color
background-image
background-position
background-repeat
color
Layout properties border
border-bottom
border-bottom-color
border-bottom-style
border-bottom-width
border-collapse*
border-color
border-left
border-left-color
border-left-style
border-left-width
border-right
border-right-color
border-right-style
border-right-width
border-style
border-top
border-top-color
border-top-style
border-top-width

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


66

border-width
clear
float
margin
margin-bottom
margin-left
margin-right
margin-top
padding
padding-bottom
padding-left
padding-right
padding-top
table-layout*
Classification properties display
list-style
list-style-image
list-style-position
list-style-type
Positioning properties bottom
clip
height
left
overflow
overflow-x (proposed)
overflow-y (proposed)
position
right
top
visibility
width
z-index
Printing properties page-break-after
page-break-before
Filter properties filter (proposed)
Pseudo-classes and other properties active
cursor
hover
@import
!important
link
visited
Unsupported CSS attributes first-letter pseudo
first-line pseudo
white-space

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


67

CSS Length Units


This section defines the supported length units for CSS attributes. Unless otherwise
specified, the length units are supported as of Microsoft® Internet Explorer 3.0 or later.
An asterisk (*) indicates the length unit is available as of Internet Explorer 4.0 or later.
Relative length units
em * The height of the element's font.
ex * The height of the letter "x".
px Pixels.
% Percentage.
Absolute length units
in Inches (1 inch = 2.54 centimeters).
cm Centimeters.
mm Millimeters.
pt Points (1 point = 1/72 inches).
pc Picas (1 pica = 12 points).
Measurements and positions in cascading style sheets (CSS) properties are indicated in
length units. Internet Explorer supports two types of length units: relative and absolute.
A relative length unit specifies a length in relation to another length property. Relative
length units scale better from one output device to another, such as from a monitor to a
printer.
An absolute length unit specifies an absolute measurement, such as inches or centimeters.
Absolute length units are useful when the physical properties of the output device are
known.
See Also

Hang in There, CSS Authors: We'll Get


Through this Together
Stop Pulling Your Hair Out!
Have you been pulling your hair out, trying to decipher how all the different
implementations of CSS work in Netscape 4. x, Internet Explorer 3. x and Internet
Explorer 4.0 for both the Macintosh and Windows 95 operating systems? There are
plenty of people who sympathize with you, including me. After painstaking hours of
testing and authoring CSS, several people have pulled together some very helpful
resources.
Rushing into Resources?
When I wrote my October column, it was nearly impossible to find information on how
to author CSS that worked in browsers supporting CSS. All I could find was a small
chapter in a book on Dynamic HTML, hot off the press with the launch of Internet
Explorer 4.0. I was so excited to have finally found some information that I instantly
started working with the book's samples and information. Turns out they were wrong.
What? How can that be?
Should one never trust the written word of books or publications on DHMTL?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


68

Sue Sims: "At least not until you confirm it for yourself. Even that's hard. I found some
CSS implementation differences between Netscape Navigator 4.01 and version 4.04,
although I never saw any documentation on it, nor any change in the Netscape Navigator-
known CSS bugs page on the Netscape site's DevEdge area."
What about relying on published CSS material?
Sue Sims: "I learned about relying on published CSS material the hard way, too. A
DHTML book I rushed to purchase had doubtful information in the first chapter, along
with some examples, which did not work as advertised. Lesson learned: Don't rush; wait
until enough time has passed for experiments to succeed, and then buy when you
recognize the author's name as someone you trust."
Trustworthy CSS Resources.
If you are just starting to tackle CSS compatibility issues, you are fortunate! There are
now resources available. A highly recommended resource is Eric Meyer's compatibility
charts on the Web Review Web site.
Another great resource , which is part of the CSS Pointers group, details bugs and
workarounds that have been found by members of the group.
In compiling this page, the authors and participants in the style-sheet newsgroup ran
hundreds of tests on all the CSS properties to find workarounds. I recommend joining the
newsgroup at news:comp.infosystems.www.authoring.stylesheets . I've been
hanging out on the newsgroup, not saying anything, but using it for information. You will
be surprised at how many questions and answers are available. Newsgroups can be a very
helpful resource, because they involve a community and a consensus of information.
The MSDN Online private newsgroups is also very informative.
The CSS Pointers Web site has an extensive list of resources and information.
The World Wide Web Consortium (W3C) is the mecca for CSS past, present, and
future information.
Clever Workarounds Exist
The best solution is to keep CSS authoring simple, and gradually build your pages with
more advanced style sheets. When you start to use CSS Positioning , you will find
more differentiation between browser implementations. Here are a few helpful solutions
for authoring compatible CSS.
Class Names Not Working?
When authoring a style sheet, you can create classes.
THIS IS A CLASS CALLED PINK APPLIED TO A
PARAGRAPH
<STYLE type="text/css">.PINK {color:pink; font-family:verdana}
</STYLE>
<P CLASS=PINK>this paragraph is pink</P>
You can create any names you like for classes, with a couple exceptions. You can't start
your class names with a digit or a dash. For example, creating a class called: .153
{color:pink} or .-153 {color:pink} will not work in all browsers. But using a class name
called .p123 {color:pink} is safe. Take a look at this sample to learn how to avoid
problems with class names.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


69

To learn more, see Section 7.1 (forward-compatible parsing) of the CSS, level 1
W3C recommendation: "in CSS1, selectors (element names, classes and IDs) can contain
only the characters A-Z, 0-9, and Unicode characters 161-255, plus dash (-); they cannot
start with a dash or a digit; ..."
Font-size is too small?
Avoid small font sizes; on the Mac platform, fonts set to font-size small, or to point or
pixel amounts less than 10, will render type that is illegible. When using Netscape
Navigator 4. x on the Macintosh, font size set to small (<P STYLE="font-size:small">)
will be legible only in some fonts. For all browsers, set your font sizes greater than the
quantity of 10 pixels or 10 points so the type will be legible. Small points and pixels are
hard to read.
View a sample of small font sizes.
Favorite workarounds from the CSS Pointers Group:
Drop Cap
Although browsers do not yet support the pseudoelement "first-letter," a simulated drop
cap is achieved with CSS by using the following code:
<STYLE>
<!--
.dropcap {float: left; color: red;
font-size: x-large; width: 1em;
height: 1em; }
-->
</STYLE>
<SPAN class="dropcap">T</SPAN>his is a
paragraph with a fairly large "T" in
front of it. Addition of the width
attribute allows rendering in
Internet Explorer.
Doing a drop cap this way will work for most browers -- except that the height attribute
does not work on different Mac versions. The letter will be dropped, but it will overlap
the preceding lines of text.
Background Color
You may have noticed that Netscape causes background color to extend only under text.
The solution here is to add a border with 1 pixel width to the background declaration.
This CSS class allows highlighting of any block of text included in the <SPAN> tags.
<STYLE>
<!--
.highlight {background-color: yellow;
color: black;width: 10em;
font-size: x-small;border: 1px ridge;}
-->

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


70

</STYLE>

<P><SPAN CLASS="highlight">This sample text


will have a background color of yellow,
which will extend to encompass the text,
regardless of the length.</SPAN></P>
View a sample of the highlight class.

Managing Style Sheets


Dynamically changing cascading style sheets (CSS) styles that are applied to documents
is not limited to the inline styles (styles defined with the STYLE= attribute). Global style
sheets defined with a LINK or STYLE tag in the HEAD section of the document can be
manipulated through script. Manipulating the global style sheet is a powerful way to
dynamically change the styles that apply to Web pages.
styleSheets Collection
Global style sheets are made accessible to script through the styleSheets collection on the
document object. This collection represents instances of STYLE and LINK elements in
the HEAD section of the document with a type (or type attribute) of "text/css". Style
sheets of other types are not supported. Imported style sheets are contained within a
STYLE element, and are surfaced by the containing STYLE element as type styleSheet.
STYLE and LINK elements can be added to the document through the createElement
method on the window object. This method adds a new style sheet object to the
styleSheets collection on the document. Style rules and imported style sheets can then be
added to this style sheet with the addImport and addRule methods.
You can use identifiers to access style sheets in the document. You set an identifier for a
style sheet by setting the ID attribute of the LINK or STYLE element.
Disabling Style Sheets
A powerful feature of the styleSheet object is that you can turn a style sheet off and on
dynamically. The disabled property defaults to false, but can be set to "true" to remove
the style sheet from being applied to the document. Toggling the application of style
sheets is another technique for dynamically changing the style of a Web page.
Replacing Style Sheets
You can replace one style sheet with another by setting the href property of the style
sheet to the URL of the replacement, as in the following example:
if (document.styleSheets(0).href != null)
document.styleSheets(0).href = "newstyle.css";
When you replace a style sheet, the styleSheets collection is immediately updated to
reflect the change. Replacing a style sheet in this way is available only for style sheets
that have been included using the LINK element or the @import statement. The href
property is null for style sheets defined using the STYLE element.
Dynamically Changing Style Sheet Rules

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


71

Each style sheet is a collection of rules. The rules collection of the styleSheet object
enumerates these rules. This collection can be accessed even if the style sheet is disabled.
Rules are added and removed from the rules collection with add and remove methods on
the individual style sheet. A rule that is added to a disabled style sheet will not apply to
the document unless the style sheet's disabled property is changed to "false".
The rules in the rules collection are in the source order of the document. Style rules
linked in using the "@import" syntax of CSS are expanded in-place in the rules
collection per the CSS1 specification.
As rules are added or deleted, a rule's absolute position in the rule collection might
change, but its position relative to other rules will remain the same. The default location
to add a new rule (without specifying an index) is at the end of the collection, which is
the highest precedence (not accounting for selector specificity, as per the CSS
specification) and is applied to the document last. If an index is supplied, the rule should
be inserted before the rule currently in that ordinal position in the collection, or, if the
index is larger than the number of rules in the collection, it should be added to the end.
The following is an example of using the addRule method.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript">
function newRule() {
document.styleSheets.MyStyles.addRule("P","color:blue");
}
</SCRIPT>
<STYLE ID="MyStyles">
H1 {color:red}
H2 {color:red;font-style:italic}
</STYLE>
</HEAD>
<BODY onclick="newRule()">
<H1>Welcome!</H1>
<P>This document uses style sheets.</P>
<H2>Ways to Include Style Sheets</H2>
<UL>
<LI>LINK
<LI>STYLE
<LI>@import
</UL>
</BODY>
</HTML>
Show Me
Each rule has a selector, identifying the elements to apply the rule to, and a list of style
assignments, identifying the style attributes to apply to these elements. The selector is
typically the name of an element, class, or identifier, but can also be a combination of
names, such as a comma-separated list of element names. Each style assignment consists
of a style attribute name and a value separated by a colon. If there is more than one

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


72

assignment, the assignments are separated by semicolons. The rule object has a readOnly
property that indicates whether the particular rule is from an editable source. Imported
and linked styles cannot be edited, so the readOnly property for the contained rule would
return "true".
As an example of manipulating style rules, consider the following simple style sheet:
<STYLE
ID="MyStyles">
H1 {color:red}
H2 {color:red;font-style:italic}
</STYLE>
The rules collection would contain two rules. Each rule has two parts (and corresponding
properties): the selector and the style. The selector in the first rule in the above style sheet
is H1.
alert(document.styleSheets[0].rules[0].selectorText); // this returns "H1"
To change the style of the first rule in the first style sheet, use the following:
document.styleSheets[0].rules[0].style.color = "blue";
User-Defined Style Sheets
Through the Options dialog box of the browser, users can specify a style sheet that they
want to have applied to all pages that they view. This style sheet will be applied to the
document first, meaning the author has the final say of how a CSS attribute is defined.
Style sheets defined in the document override the user-defined style sheet. The user-
defined style sheet is simply a "preference" that will affect the page if the author has not
defined a rule for that CSS attribute. User-defined style sheets specified by the user in the
Options box dialog of the browser are not listed in the styleSheets collection.

Enhancing Table Presentation


Microsoft® Internet Explorer 5 gives the author more control over table presentation.
Significantly faster rendering is now possible. Using this layout, authors can increase
table rendering speeds by several orders of magnitude, particularly for longer, more
complex tables.
Authors can also manipulate what table information reaches users, as well as when and
how it is displayed. To this end, the author can now collapse rows and cells, render table
content invisible, and join shared borders. These key features accord with the Cascading
Style Sheets specification, keeping Internet Explorer the leader in standards
support.
This overview examines all of these new features and suggests how they may be
combined with other techniques available for enhancing table presentation.
• Benefits

• Table Layout

• Collapsing or Hiding Rows and Cells

• Joining Borders

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


73

• Printing Tables on Multiple Pages

• Conclusion

• Related Topics

Benefits
Tables provide structured information to end users. Often, however, the amount of data
overwhelms the user, or the type of information is simply not relevant. Internet Explorer
solves these problems by enabling the author to show and hide information based on user
actions or information gathered about the user's system.

Presentation is further improved by taking advantage of the new borderCollapse and


tableLayout properties. Each of these properties adds performance gains to table
rendering. With user patience usually measured in seconds, this speed is vital for
delivering information to users before they move on to another page. Using the
tableLayout property can easily halve the time for rendering of large tables. Faster
rendering is possible with even larger tables.
Table Layout
Table rendering performance can be increased by specifying the tableLayout property.
This property causes Internet Explorer to incrementally render the table, providing users
with information at a faster pace. Using the tableLayout property, the layout of a table is
determined in the following order:
1. From information in the width property for the COL or COLGROUP objects.

2. By analyzing the formatting of the first table row.

3. By an equal division of the columns.


First, information from the width property of the COL or COLGROUP object is used if it is available. If it is
unavailable, then formatting for the first table row is taken into account. Lastly, if formatting is not available for the
COL or COLGROUP objects, or the first table row, table layout is determined by an equal division of the columns.

Sample
The following example shows the use of the cascading style sheets (CSS) attribute, table-layout, to fix the table layout,
resulting in faster rendering of the table. Note that the widths need not be set on the TABLE and COL objects. When
the width is not specified, the browser looks to the contents of the first row's cells to fix the column widths and,
consequently, the table width.
<TABLE STYLE="table-layout:fixed" WIDTH=600>
<COL WIDTH=100><COL WIDTH=300><COL WIDTH=200>
<TR HEIGHT=20>
<TD>...</TD><TD>...</TD><TD>...</TD>
</TR>
:
</TABLE>
The performance gains are significant, especially for large tables. Because the browser
does not need to parse through the table once simply to lay it out, the table rows can start
to render immediately. Click the button to view a demonstration of this rendering gain.
Show Me

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


74

Take care in choosing the column width. Cell content that exceeds the width of the
column is wrapped, if possible, or clipped if the content cannot be wrapped. If row height
has been set, the wrapped text will be clipped where it exceeds the height restriction. If
data sources are dynamically bound to the table through data binding, consideration of all
the content that may appear is especially important.
Collapsing or Hiding Rows and Cells
Too much information can confuse or distract your readers. To aid your readers and
improve their comprehension of important data, you can selectively show information or
you can enable the user to selectively view information. A number of techniques are
available to achieve this end.
Hiding the full table itself is the most basic means of hiding data. This full table hiding
has been available to authors since Internet Explorer 4. Using the display property, the
entire table may be hidden and its physical space eliminated in the layout. Choosing the
visibility property, on the other hand, hides the table but preserves its space in the layout.
The display and visibility properties can be limited to rows and cells. Using the display
property, rows can be collapsed out of view. If, instead, you desire the space occupied by
the row or cell to show, but not the information, apply the visibility property. Changing
the visibility through scripting is useful for showing and hiding overlapping content
based on user interaction. Note that for a child element to be visible, the parent element
must also be visible. For style scripting information, see Dynamic Styles.
Note that similar functionality is available through the data-binding filtering mechanism.
Data binding may be a more appropriate choice where scalability is important. For more
information, see Data Binding.
• Collapsing Rows

• Hiding Information in Rows or Cells

• Hiding Information in Multiple Rows

Collapsing Rows
Collapsing rows easily hides unimportant or irrelevant information from users.
Sample
The following sample uses function calls to hide and show table rows and cells. If the user is interested only in
household pets, the display property on the rows that do not have household pets is set to "none" on the onclick event.
<SCRIPT>
function getPets() {
tblChoice1.style.display="none";
tblChoice2.style.display="";
tblChoice3.style.display="none";
}
</SCRIPT>
:
<TABLE>
<TR ID="tblChoice1">

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


75

<TD>Horses</TD><TD
ID="tblChoice1_1">Thoroughbreds</TD><TD>Fast</TD>
</TR>
<TR ID="tblChoice2">
<TD>Dogs</TD><TD
ID="tblChoice2_1">Greyhounds</TD><TD>Fast</TD>
</TR>
<TR ID="tblChoice3">
<TD>Marsupials</TD><TD
ID="tblChoice3_1">Opossums</TD><TD>Slow</TD>
</TR>
</TABLE>
:
<INPUT TYPE=button onclick="getPets()" VALUE="Show household pets">
Show Me
Note that the author may use inline scripting to achieve the same result by replacing the
onclick call in the last line above with:
onclick = "tblChoice1.style.display= 'none';
tblChoice2.style.display= ''; tblChoice3.style.display= 'none'"
Hiding Information in Rows and Cells
Visibility can be set on individual cells, groups of cells, rows, or tables to hide information while maintaining the
physical space occupied by the data. The following sample uses function calls to hide and show table cells. For
example, if the user is interested only in fast pets, the visibility property on the rows that do not have fast pets is set to
"hidden" on the onclick event.
Sample
<SCRIPT>
function getFast() {
tblChoice1_1.style.visibility="visible";
tblChoice2_1.style.visibility="visible";
tblChoice3_1.style.visibility="hidden";
}
</SCRIPT>
:
<TABLE>
<TR>
<TD>Horses</TD><TD
ID="tblChoice1_1">Thoroughbreds</TD><TD>Fast</TD>
</TR>
<TR>
<TD>Dogs</TD><TD
ID="tblChoice2_1">Greyhounds</TD><TD>Fast</TD>
</TR>
<TR>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


76

<TD>Marsupials</TD><TD
ID="tblChoice3_1">Opossums</TD><TD>Slow</TD>
</TR>
</TABLE>
:
<INPUT TYPE=button onclick="getFast()" VALUE="Show fast pets">
Show Me

Hiding Information in Multiple Rows


The display property can be set on groups of rows to hide information while maintaining the physical space occupied
by the row. Using the TBODY object within the TABLE object, the author can specify the rows to which the display
property is applied.
Sample
In the following example, the information contained between the TBODY objects is toggled depending on the user's
choice.
<TABLE STYLE="table-layout:'fixed'">
<COL WIDTH=100><COL WIDTH=150><COL WIDTH=150>
<TR>
<TD>EST</TD><TD>9:00 a.m.</TD><TD>5:00 p.m.</TD>
</TR>
<TBODY ID=tblTB_1>
<TR>
<TD>CST</TD><TD>8:00 a.m.</TD><TD>4:00 p.m.</TD>
</TR>
</TBODY>
<TBODY ID=tblTB_2>
<TR>
<TD>MST</TD><TD>7:00 a.m.</TD><TD>3:00 p.m.</TD>
</TR>
</TBODY>
<TR>
<TD>PST</TD><TD>6:00 a.m.</TD><TD>D2:00 p.m.</TD>
</TR>
</TABLE>
<P>
:
<BUTTON onclick="tblTB_1.style.display='none';tblTB_2.style.display=''">
Hide CST</BUTTON>
<BUTTON onclick="tblTB_1.style.display='';tblTB_2.style.display='none'">
Hide MST</BUTTON>
Show Me
The advantage here is in the coding: setting the visibility property on each row in a large
table is cumbersome. Leveraging the TBODY object accomplishes this goal with less
script.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


77

Joining Borders
Authors can also collapse interior borders to keep a consistent width on all the borders in
the table. Although borders should not overwhelm the data itself, traditional table
rendering results in double-width borders between cells. Internet Explorer 5 allows you to
maintain a consistent border width throughout the table.
Sample
The following example uses the border-collapse CSS attribute on the TABLE object, as shown in the following code.
Alternately, the borderCollapse property could be used to script the same functionality.
<TABLE ID=id1 STYLE="border-collapse:collapse">
<TR><TD>EST</TD><TD>9:00 a.m.</TD></TR>
<TR><TD>CST</TD><TD>8:00 a.m.</TD></TR>
<TR><TD>PST</TD><TD>6:00 a.m.</TD></TR>
</TABLE>
Show Me
Authors now can show tables emulating the thin border lines used in Microsoft® Excel,
as shown in the following table (the collapsed borders will only be evident if you are
using Internet Explorer 5).
EST 9:00 a.m. 5:00 p.m.
CST 8:00 a.m. 4:00 p.m.
PST 7:00 a.m. 2:00 p.m.
The look of the preceding table is achieved using the following embedded style sheet:
<STYLE>
TD {border:'thin black solid'}
</STYLE>
The same table without collapsed borders (that is, in standard HTML) uses more space
between the cells in order to render the detached borders.
EST 9:00 a.m. 5:00 p.m.
CST 8:00 a.m. 4:00 p.m.
PST 6:00 a.m. 2:00 p.m.
Not only do authors have a new choice between these two styles of borders, additional
styles can be attached to either using the CSS border properties made available in Internet
Explorer 4.0.
Printing Tables on Multiple Pages
When a page containing a table is printed, the CSS attributes page-break-before and
page-break-after can be used to specify where in a table the break should occur. This is
helpful for Web sites that implement large tables to organize pages. In addition, the
display property exposes the table-header-group and table-footer-group possible values,
which specify that the THEAD or TFOOT objects are always before or after any table
rows. Using these possible values for the THEAD and TFOOT objects specifies that the
header and footer will print on every page that a particular table spans.
END---

General Questions

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


78

1. What is CSS?

CSS stands for Cascading Style Sheets and is a simple styling language which
allows attaching style to HTML elements. Every element type as well as every
occurance of a specific element within that type can be declared an unique style,
e.g. margins, positioning, color or size.
2. What are Style Sheets?

Style Sheets are templates, very similar to templates in desktop publishing


applications, containing a collection of rules declared to various selectors
(elements).
3. What is external Style Sheet? How to link?

External Style Sheet is a template/document/file containing style information


which can be linked with any number of HTML documents. This is a very
convenient way of formatting the entire site as well as restyling it by editing just
one file.
The file is linked with HTML documents via the LINK element inside the HEAD
element. Files containing style information must have extension .css, e.g. style.css.
<HEAD>
<LINK REL=STYLESHEET HREF="style.css" TYPE="text/css">
</HEAD>

4. What is embedded style? How to link?

Embedded style is the style attached to one specific document. The style
information is specified as a content of the STYLE element inside the HEAD
element and will apply to the entire document.
<HEAD>
<STYLE TYPE="text/css">
<!--
P {text-indent: 10pt}
-->
</STYLE>
</HEAD>

Note: The styling rules are written as a HTML comment, that is, between <!-- and
--> to hide the content in browsers without CSS support which would otherwise
be displayed.
5. What is inline style? How to link?

Inline style is the style attached to one specific element. The style is specified
directly in the start tag as a value of the STYLE attribute and will apply
exclusively to this specific element occurance.
<P STYLE="text-indent: 10pt">Indented paragraph</P>

6. What is imported Style Sheet? How to link?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


79

Imported Style Sheet is a sheet that can be imported to (combined with) another
sheet. This allows creating one main sheet containing declarations that apply to
the whole site and partial sheets containing declarations that apply to specific
elements (or documents) that may require additional styling. By importing partial
sheets to the main sheet a number of sources can be combined into one.

To import a style sheet or style sheets include the @import notation or notations
in the STYLE element. The @import notations must come before any other
declaration. If more than one sheet is imported they will cascade in order they are
imported - the last imported sheet will override the next last; the next last will
override the second last, and so on. If the imported style is in conflict with the
rules declared in the main sheet then it will be overridden.
<LINK REL=STYLESHEET HREF="main.css" TYPE="text/css">
<STYLE TYPE="text=css">
<!--
@import url(http://www.and.so.on.partial1.css);
@import url(http://www.and.so.on.partial2.css);
.... other statements
-->
</STYLE>
7. What is alternate Style Sheet? How to link?

Alternate Style Sheet is a sheet defining an alternate style to be used in place of


style(s) declared as persistent and/or preferred .
Persistent style is a default style that applies when style sheets are enabled but can
disabled in favor of an alternate style, e.g.:

<LINK REL=Stylesheet HREF="style.css" TYPE="text/css">


Preferred style is a default style that applies automatically and is declared by
setting the TITLE attribute to the LINK element. There can only be one preferred
style, e.g.:
<LINK REL=Stylesheet HREF="style2.css" TYPE="text/css"
TITLE="appropriate style description">
Alternate style gives an user the choice of selecting an alternative style - a very
convenient way of specifying a media dependent style. Note: Each group of
alternate styles must have unique TITLE, e.g.:

<LINK REL="Alternate Stylesheet" HREF="style3.css" TYPE="text/css"


TITLE="appropriate style description" MEDIA=screen>
<LINK REL="Alternate Stylesheet" HREF="style4.css" TYPE="text/css"
TITLE="appropriate style description" MEDIA=print>
Alternate stylesheets are not yet supported.

8. What is persistent style?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


80

Se Alternate style
9. What is preferred style?

Se Alternate style
10. How do I combine multiple sheets into one?

To combine multiple/partial style sheets into one set the TITLE attribute taking
one and the same value to the LINK element. The combined style will apply as a
preferred style, e.g.:

<LINK REL=Stylesheet HREF="default.css" TITLE="combined">


<LINK REL=Stylesheet HREF="fonts.css" TITLE="combined">
<LINK REL=Stylesheet HREF="tables.css" TITLE="combined">
11. What is CSS rule 'ruleset'?

There are two types of CSS rules: ruleset and at-rule. Ruleset identifies selector or
selectors and declares style which is to be attached to that selector or selectors.
For example P {text-indent: 10pt} is a CSS rule. CSS rulesets consist of two parts:
selector, e.g. P and declaration, e.g. {text-indent: 10pt}.
P {text-indent: 10pt} - CSS rule (ruleset)
{text-indent: 10pt} - CSS declaration
text-indent - CSS property
10pt - CSS value

12. What is CSS rule 'at-rule'?

There are two types of CSS rules: ruleset and at-rule. At-rule is a rule that applies
to the whole style sheet and not to a specific selector only (like in ruleset). They
all begin with the @ symbol followed by a keyword made up of letters a-z, A-Z,
digits 0-9, dashes and escaped characters, e.g. @import or @font-face.
13. What is selector?

CSS selector is equivalent of HTML element(s). It is a string identifying to which


element(s) the corresponding declaration(s) will apply and as such the link
between the HTML document and the style sheet.
For example in P {text-indent: 10pt} the selector is P and is called type selector as it
matches all instances of this element type in the document.

in P, UL {text-indent: 10pt} the selector is P and UL (see grouping); in .class {text-indent:


10pt} the selector is .class (see class selector).

14. What is CLASS selector?

Class selector is a "stand alone" class to which a specific style is declared. Using
the CLASS attribute the declared style can then be associated with any HTML
element. The class selectors are created by a period followed by the class's name.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


81

The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a
numeric code, however, they cannot start with a dash or a digit. (Note: in HTML
the value of the CLASS attribute can contain more characters).It is a good
practice to name classes according to their function than their appearance.
.footnote {font: 70%} /* class as selector */
<ADDRESS CLASS=footnote/>This element is associated with the CLASS
footnote</ADDRESS>
<P CLASS=footnote>And so is this</P>

15. What is ID selector?

ID selector is an individually identified (named) selector to which a specific style


is declared. Using the ID attribute the declared style can then be associated with
one and only one HTML element per document as to differentiate it from all other
elements. ID selectors are created by a character # followed by the selector's
name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen,
escaped characters, Unicode characters 161-255, as well as any Unicode character
as a numeric code, however, they cannot start with a dash or a digit.
#abc123 {color: red; background: black}
<P ID=abc123>This and only this element can be identified as abc123</P>

16. What is contextual selector?

Contextual selector is a selector that addresses specific occurrence of an element.


It is a string of individual selectors separated by white space, a search pattern,
where only the last element in the pattern is addressed providing it matches the
specified context.
TD P CODE {color: red}
The element CODE will be displayed in red but only if it occurs in the context of
the element P which must occur in the context of the element TD.
TD P CODE, H1 EM {color: red}
The element CODE will be displayed in red as described above AND the element
EM will also be red but only if it occurs in the context of H1
P .footnote {color: red}
Any element with CLASS footnote will be red but only if it occurs in the context
of P
P .footnote [lang]{color: red}
Any element with attribute LANG will be red but only if it is classed as
"footnote" and occurs in the context of P
17. What is attribute selector? [CSS2]

Attribute selector is a selector defined by 1) the attribute set to element(s), 2) the


attribute and value(s), 3) the attribute and value parts:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


82

1a) A[title] {text-decoration: underline}


All A elements containing the TITLE attribute will be underlined
1b) A[class=name] {text-decoration: underline}
The A elements classed as 'name' will be underlined
2) A[title="attribute element"] {text-decoration: underline}
The A elements containing the TITLE attribute with a value that is an exact match
of the specified value, which in this example is 'attribute element', will be
underlined
3) A[title~="attribute"] {text-decoration: underline}
The A elements containing the TITLE attribute with a value containing the
specified word, which in this example is 'attribute', will be underlined
18. What is parent-child selector? [CSS2]

Parent-child selector is a selector representing the direct descendent of a parent


element. Parent-child selectors are created by listing two or more tilde (~)
separated selectors.

BODY ~ P {background: red; color: white}


The P element will be declared the specified style only if it directly descends from
the BODY element:
<BODY><P>Red and white paragraph </P></BODY>
BODY ~ P ~ EM {background: red; color: white}
The EM element will be declared the specified style only if it directly descends
from the P element which in its turn directly descends from the BODY element:
<BODY><P><EM>Red and white EM</EM></P></BODY>
19. What is CSS declaration?

CSS declaration is style attached to a specific selector. It consists of two parts;


property which is equivalent of HTML attribute, e.g. text-indent: and value which is
equivalent of HTML value, e.g. 10pt. NOTE: properties are always ended with a
colon.
20. What is 'important' declaration?

Important declaration is a declaration with increased weight. Declaration with


increased weight will override declarations with normal weight. If both reader's
and author's style sheet contain statements with important declarations the
author's declaration will override the reader's.
BODY {background: white ! important; color: black}
In the example above the background property has increased weight while the
color property has normal.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


83

21. What is property?

Property is a stylistic parameter (attribute) that can be influenced through CSS,


e.g. FONT or WIDTH. There must always be a corresponing value or values set
to each property, e.g. font: bold or font: bold san-serif.

22. What is shorthand property?

Shorthand property is a property made up of individual properties that have a


common "addressee". For example properties: font-weight, font-style, font-variant, font-
size, font-family, refer to the font. To reduce the size of style sheets and also save
some keystrokes as well as bandwidth they can all be specified as one shorthand
property font, e.g.:
H1 {font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-size: 160%;
font-family: serif}

can be all shorthanded to a space separated list:


H1 {font: bold italic small-caps 160% serif}

Note: To make things even simpler the line-height property can be specified
together with the font-size property:
H1 {font: bold italic small-caps 160%/170% serif}

23. What is value?

Value is a 'physical' characteristic of the property. Property declares what should


be formatted, e.g. FONT while value suggests how the property should be
formatted, e.g. 12pt. By setting the value 12pt to the property FONT it is
suggested that the formatted text be displayed in a 12 point font. There must
always be a corresponding property to each value or set of values.
H1 {font: bold 180%}
In the example above the H1 selector is declared the FONT property which in its
turn is declared the values BOLD and 180%.
The values suggesting alternatives are specified in a comma separated list, e.g.
H1 {font-family: font1, font2}
24. What is initial value?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


84

Initial value is a default value of the property, that is the value given to the root
element of the document tree. All properties have an initial value. If no specific
value is set and/or if a property is not inherited the initial value is used. For
example the background property is not inherited, however, the background of the
parent element shines through because the initial value of background property is
transparent.
<P style="background: red">Hello <strong>World</strong></P>
Content of the element P will also have red background
25. Can I attach more than one declaration to a selector?

Yes. If more than one declaration is attached to a selector they must appear in a
semi colon separated list, e.g.;
Selector {declaration1; declaration2}
P {background: white; color: black}

26. What is class?

Class is a group of 1) instances of the same element to which an unique style can
be attached or 2) instances of different elements to which the same style can be
attached.

1) The rule P {color: red} will display red text in all paragraphs. By classifying the
selector P different style can be attached to each class allowing the display of
some paragraphs in one style and some other paragraphs in another style.

2) A class can also be specified without associating a specific element to it and


then attached to any element which is to be styled in accordance with it's
declaration. All elements to which a specific class is attached will have the same
style.
To classify an element add a period to the selector followed by an unique name.
The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a
numeric code, however, they cannot start with a dash or a digit. (Note: in HTML
the value of the CLASS attribute can contain more characters). (Note: text
between /* and */ are my comments).
CSS
P.name1 {color: red} /* one class of P selector */
P.name2 {color: blue} /* another class of P selector */
.name3 {color: green} /* can be attached to any element */

HTML
<P class=name1>This paragraph will be red</P>
<P class=name2>This paragraph will be blue</P>
<P class=name3>This paragraph will be green</P>
<LI class=name3>This list item will be green</LI>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


85

It is a good practice to name classes according to their function than their


appearance; e.g. P.fotnote and not P.green. In CSS1 only one class can be attached to
a selector. CSS2 allows attaching more classes, e.g.:
P.name1.name2.name3 {declaration} <P class="name1 name2 name2">This
paragraph has three classes attached</P>
27. What is grouping

Grouping is gathering (1) into a comma separated list two or more selectors that
share the same style or (2) into a semicolon separated list two or more
declarations that are attached to the same selector (2).
1. The selectors LI, P with class name .first and class .footnote share the same style,
e.g.:
LI {font-style: italic}
P.first {font-style: italic}
.footnote {font-style: italic}

To reduce the size of style sheets and also save some typing time they can all be
grouped in one list.
LI, P.first, .footnote {font-style: italic}

2. The declarations {font-style: italic} and {color: red} can be attached to one selector,
e.g.:
H2 {font-style: italic}
H2 {color: red}

and can also be grouped into one list:


H2 {font-style: italic; color: red}

28. What are pseudo-elements?

Pseudo-elements are fictional elements that do not exist in HTML. They address
the element's sub-part (non-existent in HTML) and not the element itself. In CSS1
there are two pseudo-elements: 'first-line pseudo-element' and 'first-letter pseudo-
element'. They can be attached to block-level elements (e.g. paragraphs or
headings) to allow typographical styling of their sub-parts. Pseudo-element is
created by a colon followed by pseudo-element's name, e.g:
P:first-line
H1:first-letter
and can be combined with normal classes; e.g:
P.initial:first-line
First-line pseudo-element allows sub-parting the element's first line and
attaching specific style exclusively to this sub-part; e.g.:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


86

P.initial:first-line {text-transform: uppercase}


<P class=initial>The first line of this paragraph will be displayed in uppercase letters</P>

First-letter pseudo-element allows sub-parting the element's first letter and


attaching specific style exclusively to this sub-part; e.g.:
P.initial:first-letter { font-size: 200%; color: red}
<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>

29. What are pseudo-classes?

Pseudo-classes are fictional element types that do not exist in HTML. In CSS1
there is only one element type which can be classed this way, namely the A
element (anchor). By creating three fictional types of the A element individual
style can be attached to each class. These three fictional element types are: A as
unvisited link, A as active link and A as visited link. Pseudo-classes are created
by a colon followed by pseudo-class's name. They can also be combined with
normal classes, e.g.:
A:link {background: black; color: white}
A:active {background: black; color: red}
A:visited {background: transparent; color: black}
<A HREF....>This anchor (or rather these anchors) will be displayed as declared above</A>
A.foot:link {background: black; color: white}
A.foft:active {background; black: color: red}
A.foot:visited {background: transparent; color: black}
<A CLASS=foot HREF....>This anchor and all other anchors with CLASS foot will be displayed
as declared above</A>

30. What is cascade?

Cascade is a method of defining the weight (importance) of individual styling


rules thus allowing conflicting rules to be sorted out should such rules apply to the
same selector.

Declarations with increased weight take precedence over declaration with normal
weight:
P {color: white ! important} /* increased weight */
P (color: black} /* normal weight */
31. What is cascading order?

Cascading order is a sorting system consisting of rules by which declarations are


sorted out so that there are not conflicts as to which declaration is to influence the
presentation. The sorting begins with rule no 1. If a match is found the search is

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


87

over. If there is no match under rule no 1 the search continues under rule no 2 and
so on.
1. Find all declarations that apply to a specific selector/property
and
Declare the specified style if the selector matches the element
if there isn't any
Let the element inherit its parent property
if there isn't any
Use initial value
2. Sort by weight (! important)
Increased weight take precedence over normal weight
3. Sort by origin
Rules with normal weight declared in author's style sheet will override
rules with normal weight declared in user's personal style sheets
Rules with increased weight declared in user's personal style sheet will
override rules with normal weight declared in author's style sheet
Rules with increased weight declared in author's style sheet will override
rules with increased weight declared in user's personal style sheets
Author's and user's rules will override UA's default style sheet.

4. Sort by selector's specificity


More specific selector will override less specific one:
ID-selector (most specific), followed by
Classified contextual selectors (TABLE P EM.fot)
Class selectors (EM.fot)
Contextual selectors - the "lower down" the more weight, (TABLE P
EM), (TABLE P EM STRONG) - STRONG has more weight than EM.
5. Sort by order specified
If two rules have the same weight, the latter specified overrides ones
specified earlier. Style sheets are sorted out as follows:
The STYLE attribute (inline style) overrides all other styles
The Style element (embedded style) overrides linked and imported sheets
The LINK element (external style) overrides imported style
The @import statement - imported style sheets also cascade with each
other in the same order as they are imported
32. What are inline, block, parent, children, replaced and floating elements?
Inline
elements which do not have line breaks. Can occur in block elements or other inline elements, cannot contain
block elements.
Inline elements in HTML 3.2; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, TT,
I, B, U, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, FONT, BASEFONT, BR,
SCRIPT, MAP, INPUT, SELECT, TEXTAREA.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


88

Inline elements in HTML 4.0; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE,
ABBR, ACRONYM, TT, I, B, BIG, SMALL, SUB, SUP, A, IMG, OBJECT, BR, SCRIPT, MAP,
Q, SPAN, BDO, INPUT, SELECT, TEXTAREA, LABEL, BUTTON, (INS, DEL).

Inline elements in HTML 4.0 Transitional; EM, STRONG, DFN, CODE, SAMP, KBD,
VAR, CITE, ABBR, ACRONYM, TT, I, B, U, S, STRIKE, BIG, SMALL, SUB, SUP, A, IMG,
APPLET, OBJECT, FONT, BASEFONT, BR, SCRIPT, MAP, Q, SPAN, BDO, IFRAME,
INPUT, SELECT, TEXTAREA, LABEL, BUTTON, (INS, DEL).
Block
elements which do have line breaks. May occur in other block elements, cannot occur in inline elements, may
contain both block and inline elements.
Block elements in HTML 3.2; H1, H2, H3, H4, H5, H6, ADDRESS, P, DL, DT, DD, UL,
OL, DIR, MENU, LI, DIV, CENTER, BLOCKQUOTE, PRE, HR, ISINDEX, TABLE, FORM.

Block elements in HTML 4.0; P, H1, H2, H3, H4, H5, H6, UL, OL, PRE, DL, DIV,
NOSCRIPT, BLOCKQUOTE, FORM, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).

Block elements in HTML 4.0 Transitional; P, H1, H2, H3, H4, H5, H6, UL, OL, DIR,
MENU, PRE, DL, DIV, CENTER, NOSCRIPT, NOFRAMES, BLOCKQUOTE, FORM,
ISINDEX, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).
Parents and children
elements which either contain (parents) or are in the content of (children) other elements, e.g.
<P>text<STRONG>text</STRONG>text</P>. P is a parent of STRONG. STRONG is a child of P. If
not specified otherwise, children will inherit parent's properties. NOTE: not all properties are inherited. For
more information, see INHERITANCE.
Replaced
elements which content is replaced. For example content of the IMG element is replaced with an image,
content of the INPUT element is replace with a field.
Floating
elements which follow the flow of a parent - inline elements.

33. How does inheritance work?

HTML documents are structured hierarchically. There is an ancestor, the top level
element, the HTML element, from which all other elements (children) are
descended. As in any other family also children of the HTML family can inherit
their parents, e.g. color or size.
By letting the children inherit their parents a default style can be created for top
level elements and their children. (Note: not all properties can be inherited). The
inheritance starts at the oldest ancestor and is passed on to its children and then
their children and the children's children and so on.

Inherited style can be overridden by declaring specific style to child element. For
example if the EM element is not to inherit its parent P then own style must be
declared to it. For example:
BODY {font-size: 10pt}
All text will be displayed in a 10 point font

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


89

BODY {font-size: 10pt}


H1 {font-size: 14pt} or H1 {font-size: 180%}

All text except for the level 1 headings will be displayed in a 10 point font. H1
will be displayed in a 14 point font (or in a font that is 80% larger than the one set
to BODY). If the element H1 contains other elements, e.g. EM then the EM element
will also be displayed in a 14 point font (or 180%) it will inherit the property of
the parent H1. If the EM element is to be displayed in some other font then own
font properties must be declared to it, e.g:
BODY {font-size: 10pt}
H1 {font-size: 14pt} or H1 {font-size: 180%}
EM {font-size: 15pt} or EM {font-size: 110%}

The EM element will be displayed in a 15 point font or will be 10% larger than H1.
NOTE: EM is, in this example, inside H1 therefore will inherit H1's properties and
not BODY's.
The above declaration will display all EM elements in 15 point font or font that is
10% larger than font declared to the parent element. If this specific font is to
apply to EM elements but only if they are inside H1 and not every occurrence of
EM then EM must take a form of a contextual selector.

H1 EM {font-size: 15pt} or H1 EM {font-size: 110%}

In the example above EM is a contextual selector. It will be displayed in specified


font only if it will be found in the context of H1.

Not all properties are inherited. One such property is background. However, since
it's initial value is transparent the background of the parent element will shine
through by default unless it is explicitly set.

34. Are Style Sheets case sensitive?

No. Style sheets are case insensitive. Whatever is case insensitive in HTML is
also case insensitive in CSS. However, parts that are not under control of CSS like
font family names and URLs can be case sensitive - IMAGE.gif and image.gif is not
the same file.
35. Which characters can CSS-names contain?

The CSS-names; names of selectors, classes and IDs can contain characters a-z,
A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255,
as well as any Unicode character as a numeric code. The names cannot start with
a dash or a digit. (Note: in HTML the value of the CLASS attribute can contain
more characters).

36. Can I include comments in my Style Sheet?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


90

Yes. Comments can be written anywhere where whitespace is allowed and are
treated as white space themselves. Anything written between /* and */ is treated
as a comment (white space). NOTE: Comments cannot be nested.
/* This is a CSS-comment */

37. Can Style Sheets and HTML stylistic elements be used in the same document?

Yes. Style Sheets will be ignored in browsers without CSS-support and HTML
stylistic elements used.

38. Which set of definitions, HTML attributes or CSS properties, take precedence?

CSS properties take precedence over HTML attributes. If both are specified,
HTML attributes will be displayed in browsers without CSS support but won't
have any effect in browsers with CSS support.
39. Can CSS be used with other than HTML documents?

Yes. CSS can be used with any ny structured document format. e.g. XML,
however, the method of linking CSS with other document types has not been
decided yet (Feb 98).

Specific Questions
1. Why won't my styled documents validate against HTML 3.2?

HTML 3.2 does not support the element SPAN nor the attributes: STYLE,
CLASS, ID as well as the element's LINK attributes; TYPE and TITLE therefore
usage of them will be flagged as errors.
Presently there is no perfect solution to the problem. The available options are:
1. Documents can be validated against "HTML 3.2 + CSS1"-DTD, which was written by W3C solely
for the purpose of allowing style in HTML 3.2 documents to validate. However, this DTD does not
support the attribute TYPE which is essential in specifying the style language used. To validate
against HTML 3.2 + CSS1 use the following Doctype Declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Experimental 970421//EN">

2. Validate against HTML 4.0. This DTD supports all "CSS elements and attributes", however, this
HTML level is still in experimental version. To validate against HTML 4.0 use the following
Doctype Declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

2. Which browsers support CSS?

It depends on your definition of "support." If you are interested in those browsers


which makes some attempt at supporting CSS, no matter how partial or bug-
ridden, then the list is:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


91

o Internet Explorer 3.0 and above

o Navigator 4.0 and above

o Opera 3.6 and above

o Konqueror

o Arena

o Emacs-w3

o Amaya

o Lexicon

o XPublish by Media Design in·Progress

If instead you're interested in those browsers which are known to do a credible job
of bug-free and mostly completel support for CSS1, then the list narrows
somewhat dramatically:
o Internet Explorer 5.0 for Macintosh and above

o Internet Exporer 5.5 for Windows and above

o Netscape Navigator 6.0 and above

o Opera 4.0 and above

While none of these browser can be claimed to have a perfect implementation of


CSS1, they are all quite good and can be relied upon to operate in a consistent
fashion for most of CSS1. NOTE: At the present time (April 2001) none of the
above browsers implement the CSS2 specification consistently nor fully.
3. Aren't optional closing tags optional any more?

Optional closing tags like </P> are and have always been optional. However, some
popular browsers, like IE all versions, have problems rendering elements correctly
when these tags are omitted. If, for example, the P element is not closed the
properties declared to it will involuntarily be "inherited" by the element or
elements that follow it. If one such property is 'margin-left' you may end up with a
document containing one (or none) word per line.
Although optional closing tags are optional it is nevertheless a good idea to use
them.
4. What is the difference between ID and CLASS?

ID identifies and sets style to one and only one occurrence of an element while
class can be attached to any number of elements. By singling out one occurrence
of an element the unique value can be declared to said element.

CSS
#eva1 {background: red; color: white}
.eva2 {background: red; color: white}

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


92

HTML - ID
<P ID=eva1>Paragraph 1 - ONLY THIS occurrence of the element P (or single occurrence of
some other element) can be identified as eva1</P>
<P ID=eva1>Paragraph 2 - This occurrence of the element P CANNOT be identified as eva1</P>

HTML - CLASS
<P class=eva2>Paragraph 1 - This occurrence of the element P can be classified as eva2</P>
<P class=eva2>Paragraph 2 - And so can this, as well as occurrences of any other element, </P>

5. How to make text-links without underline?


6. a:link, a:visited {text-decoration: none}
or
<a style="text-decoration: none" HREF="...">
...will show the links without underlining. However, suppressing the underlining
of links isn't a very smart idea as most people are used to having them underlined.
Also, such links are not spotted unless someone coincidentally runs a mouse over
them. If, for whatever reason, links without underline are required background
and foreground colors can be instead declared to them so that they can be
distinguished from other text, e.g.;
a:link, a:visited {text-decoration: none; background: red; color: blue}
or
<a style="text-decoration: none; background: red; color: blue" HREF="...">
Both background and foreground colors should be specified as the property that is
not specified can be
7. How can I specify two different sets of link colors?

By classifying each set of links and then attaching desired color to each set.
CSS:
<style type="text/css">
<!--
A.set1:link {color: some_color; background: some_background_color}
A.set1:visited {color: some_color; background: some_background_color}
A.set1:active {color: some_color; background: some_background_color}

A.set2:link {color: some_color; background: some_background_color}


A.set2:visited {color: some_color; background: some_background_color}
A.set2:active {color: some_color; background: some_background_color}
-->
</style>

You can name set1 and set2 any way you like as long as the names are made up of
letters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode
characters 161-255, as well as any Unicode character as a numeric code.
Note: to avoid conflict with user's settings a background property (background
color) should also be specified together with the color property (foreground
color).

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


93

HTML:
<A class=set1 .....> will show colors as specified in class "set1"
<A class=set2 .....> will show colors as specified in class "set2"

8. How do I place text over an image?

To place text or image over an image you use the position property. The below
exemple is supported by IE 4.0. All you have to do is adapt the units to your need.
<div style="position: relative; width: 200px; height: 100px">
<div style="position: absolute; top: 0; left: 0; width: 200px">
<image>
</div>
<div style="position: absolute; top: 20%; left: 20%; width: 200px">
Text that nicely wraps
</div>
</div>
9. What is the percentage value in 'font-size' relative to?

It is relative to the parent element's font-size. For example, if the style sheet says:
H1 {font-size: 20pt;}
SUP {font-size: 80%;}
...then a <SUP> inside an <H1> will have a font-size of 80% times 20pt, or 16pt.
10. How do I place two paragraphs next to each other?

There are several ways to accomplish this effect, although each has its own
benefits and drawbacks. We start with the simplest method of positioning two
paragraphs next to each other.
<DIV style="float: left; width: 50%">Paragraph 1</DIV>
<DIV style="float: left; width: 50%">Paragraph 2</DIV>
Trickier is this example, which relies on positioning but does not suffer the
vertical-overlap problems which plague many other positioning solutions. The
problem is that it relies on an incorrect positioning implementation, and will break
down dramatically in conformant browsers.
<P>
<SPAN STYLE="position: relative; left: 50%; width: 50%">
<SPAN STYLE="position: absolute; left: -100%; width: 100%">
Paragraph 1</SPAN>
Paragraph 2</SPAN>
</P>
If floating is not sufficient to your purposes, or you cannot accept display
variances in older browsers, then it may be best to fall back to table-based
solutions.
11. How can I place multiple blocks next to each other?

In theory, the following will produce 4 "columns":


<DIV style="float: left; width: 25%;">Block 1</DIV>
<DIV style="float: left; width: 25%;">Block 2</DIV>
<DIV style="float: left; width: 25%;">Block 3</DIV>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


94

<DIV style="float: left; width: 25%;">Block 4</DIV>


Each "column" will occupy 25% of the screen. This relies on a correct
implementation of float, which cannot be said of many legacy browsers. If you
cannot accept display variances in older browsers, then it may be best to fall back
to table-based solutions.
12. When is auto different from 0 in margin properties?

In vertical margins, auto is always equal to 0. In horizontal margins, auto is only


equal to 0 if the width property is also auto. Here are three examples, assume that
there is a <P> that is a child of <BODY>:
Example 1: auto value on the width.
BODY {width: 30em;}
P {width: auto; margin-left: auto; margin-right: auto;}
Since the width property is auto, the auto values of the two margins will be ignored.
The result is a P that is 30em wide, with no margins.
Example 2: two auto margins
BODY {width: 30em;}
P {width: 20em; margin-left: auto; margin-right: auto;}
The P will be 20em wide and the remaining 10em will be divided between the
two margins. Paragraphs will be indented 5em at both sides.
Example 3: one auto margin
BODY {width: 30em;}
P {width: 20em; margin-left: 2em; margin-right: auto;}
In this case, paragraphs are 20em wide and are idented 2em on the left side. Since
the total width available is 30em, that means the right margin will be 8em.

Note that the default value of width is auto, so setting one or both margins to auto is
only useful if you set the width to something other than auto at the same time.

13. How do I center block-elements with CSS1?

There are two ways of centering block level elements:


1. By setting the properties margin-left and margin-right to auto and width to some
explicit value:
BODY {width: 30em; background: cyan;}
P {width: 22em; margin-left: auto; margin-right: auto}
In this case, the left and right margins will each be four ems wide, since they
equally split up the eight ems left over from (30em - 22em). Note that it was not
necessary to set an explicit width for the BODY element; it was done here to keep
the math clean.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


95

Another example:
TABLE {margin-left: auto; margin-right: auto; width: 400px;}
In most legacy browsers, a table's width is by default determined by its content. In
CSS-conformant browsers, the complete width of any element (including tables)
defaults to the full width of its parent element's content area. As browser becaome
more conformant, authors will need to be aware of the potential impact on their
designs.

2. By making the block an inline element and then use text-align property
<DIV STYLE="text-align: center">
<TABLE STYLE="display: inline">
...
</TABLE>
</DIV>
This technique depends on the incorrect implementation of text-align behavior in
older browsers. It will likely cease to work in future CSS-conformant browsers,
and eventually it will probably not be a viable solution.

14. How do I move the list bullet to the left/right?

CSS1 has no properties for setting margins or padding around the bullet of a list
itemand in most cases the position of the bullet is browser-dependent. This is
especially true since most browsers disagreed on whether a bullet is found within
the margin or padding of a list item.
In CSS2, properties were introduced to provide greater control over the placement
of bullets (which CSS2 calls a "marker") but these were not widely supported by
mid-2001 browsers. Here is an example of changing a marker's placement:
li:before {display: marker; marker-offset: 22px; content: url(triangle.jpg);}
In this example, a graphic of a triangle is inserted before the content of the li
element, set to be a marker (through display: marker;), and given an offset of 22
pixels. Depending on the margin size of the list item, there may not be room for
the marker to appear next to the list item's content.

15. If a list item has display: none, does it still increase the counter?

In such a case, the counter is not incremented. This is distinct from a case where a
list item is set to visibility: hidden, in which case the counter will still be
incremented.

16. How do I create a short, left-aligned rule for the <HR> element in HTML?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


96

There are several ways. Which one to use depends on your taste. In all cases, the
trick is to position the element with the width, margin-left and margin-right properties.
Here is a solution that uses the border property to put a line above the HR element.
HR {margin: 0.5em 60% 0.5em 0;
border-top: solid;}
The margin property puts half an em of space above and below the rule and makes
the right margin 60% (of the parent's width). The line is therefore 40% of the
parent's width long.

Here is another solution, that creates a black rectangle by using the background and
height properties.
HR {margin: 0.5em 60% 0.5em 0;
height: 0.04em;
background: black;}
The black rectangle is 0.04em high and has a width of 40% of the parent's width.
Table of Contents
17. Do URL's have quotes or not?

Double or single quotes in URLs are optional. The tree following examples are
equally valid:
BODY {background: url(pics/wave.png) blue}
BODY {background: url("pics/wave.png") blue}
BODY {background: url('pics/wave.png') blue}

18. To what are partial URLs relative?

Partial URLs are relative to the source of the style sheet. The style sheet source
can either be linked or embedded. To which source partial URLs are relative to
depends on their occurrence.

If a partial URL occurs in a linked style sheet then it is relative to the linked style
sheet. The URL of the linked style sheet is the URL of the directory where the
sheet is kept.

If a partial URL occurs in an embedded style sheet then it is relative to the


embedded style sheet. The URL of the embedded style sheet is the URL of the
HTML document in which the sheet is embedded.
Note that Navigator 4.x treats partial URLs as being relative to the HTML
document, regardless of the place where the partial URL occurs. This is a serious
bug which forces most authors to use absolute URLs in their CSS.

19. What is wrong with font-family: "Verdana, Arial, Helvetica"?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


97

The quotes. This is actually a list with a single item containing the well-known
'Verdana, Arial, Helvetica' font family. It is probably intended to be a list of three
items.

Unlike in most other CSS1 properties, values for the font-family are separated by
a comma to indicate that they are alternatives. Font names containing whitespace
should be quoted. If quoting is omitted, any whitespace characters before and
after the font name are ignored and any sequence of whitespace characters inside
the font name is converted to a single space.

So to ask for two fonts foo and bar the syntax is:
font-family: foo, bar
To ask for the two fonts Revival 555 and Iodine you can do this:
font-family: "Revival 555", Iodine
You could also do this:
font-family: Revival 555, Iodine
which is equivalent. Notice that this is not three fonts; you can tell because after
the "l" you didn't hit a comma, (more list items to come) a semicolon (end of that
property, another property coming up) or a curly brace (end of that rule). This is
also equivalent:
font-family: Revival 555, Iodine
^^^^^^
whole bunch of spaces converts to one space
But this next one is asking for a different font with two spaces in the name (and
whoever named it was stupid)
font-family: "Revival 555", Iodine
^^two spaces, which are not converted
In general it is more tolerant of user typing to leave out the quotes. Sometimes
you need them, for example there is a real font sold by Fontworks and designed in
1995 by Stephan Müller called Friday, Saturday, Sunday. Yes, two commas in the
actual font name. CSS1 can handle this:
font-family: "Friday, Saturday, Sunday", cursive
Because it can handle this, the example in the title is syntactically correct. But
what the author or tool wrote was almost certainly not what the document author
intended.

20. Why can @import be at the top only?

A style sheet that is imported into another one has a lower ranking in the
cascading order: the importing style sheet overrides the imported one.
Programmers may recognize this as the same model as in Java, Modula, Object-
Pascal, Oberon and other modular programming languages.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


98

However, there is a competing model, well-known to C programmers, where the


imported material is not lower in rank, but is expanded in-place and becomes an
integral part of the importing document.
By allowing @import only at the top of the style sheet, people that think in terms of
the second model (although in principle incorrect) will still get the expected
results: as long as the @import is before any other overriding rules, the two models
are equivalent.
Btw. In all the modular languages import statements are only allowed at the top.
In C, the #include can be put elsewhere, but in practice everybody always puts it at
the top. So there may not be that much need to allow @import elsewhere in the
style sheet either.

21. If one were to set Text and Link colors using a style sheet, should one also define the background
colors for these elements as well?

It is generally true that you should give background or background-color a value, but
not necessarily a color value. E.g., if the document has a background image, you
would "highlight" all links if you give them a background color.
body { background-image: url(light-texture.png) #FFF; color: #000 }
a:link, a:visited, a:active { color: #00F; background-color: transparent; }
By setting the background-image explicitly to transparent, you lower the risk of
another rule in the cascade giving links a background that would highlight them.

22. If background and color should always be set together, why do they exist as separate properties?

There are serveral reasons for this. First, style sheets become more legible -- both
for humans and machines. The background property is already the most complex
property in CSS1 and combining it with color would make it even more complex.
Second, color inherits, but background doesn't and this would be a source of
confusion.

23. Must I quote property values?

Generally no. However, values containing white spaces, e.g. font-family names
should be quoted as whitespaces surrounding the font name are ignored and
whitespaces inside the font name are converted to a single space, thus font names
made up of more than one word (e.g.) 'Times New Roman' are interpreted as three
different names: Times, New and Roman.

24. How do I quote font names in quoted values of the style attribute?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


99

The attribute values can contain both single quotes and double quotes as long as
they come in matching pairs. If two pair of quotes are required include single
quotes in double ones or vice versa:
<P STYLE="font-family: 'New Times Roman'; font-size: 90%">
<P STYLE='font-family: "New Times Roman"; font-size: 90%'>
It's been reported the latter method doesn't work very well in some browsers,
therefore the first one should be used.

25. How do I write my style sheet so that it gracefully cascades with user's personal sheet ?

You can help with this by setting properties in recommended places. Style rules
that apply to the whole document should be set in the BODY element -- and only
there. In this way, the user can easily modify document-wide style settings.

26. How do I have a background image that isn't tiled?

Specify the background-repeat property as no-repeat. You can also use the
background property as a shortcut for specifying multiple background-*
properties at once. Here's an example:
BODY {background: #fff url(watermark.jpg) no-repeat;}

27. What does \ABCD (and \ABCDE) mean?

CSS allows Unicode characters to be entered by number. For example, if a


CLASS value in some Russian document contains Cyrillic letters EL PE (Unicode
numbers 041B and 041F) and you want to write a style rule for that class, you can
put that letter into the style sheet by writing:
.\041B\041F {font-style: italic;}
This works on all keyboards, so you don't need a Cyrillic keyboard to write
CLASS names in Russian or another language that uses that script.
The digits and letters after the backslash (\) are a hexadecimal number.
Hexadecimal numbers are made from ordinary digits and the letters A to F (or a to
f). Unicode numbers consist of four such digits.
If the number starts with a 0, you may omit it. The above could also be written as:
.\41B\41F {font-style: italic;}
But be careful if the next letter after the three digits is also a digit or a letter a to f!
This is OK: .\41B-\41F, since the dash (-) cannot be mistaken for a hexadecimal
digit, but .\41B9\41F is only two letters, not three.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


100

Four digits is the maximum, however, so if you write:


.\041B9\041F {font-style: italic;}
That's three letters: two Cyrillic ones with a 9 in between.

Unicode numbers can be found in the Unicode book: The Unicode Standard
version 2.0, Addison Wesley Developers Press, Reading, Massachusets, 1996,
ISBN 0-201-48345-9.

28. Document Style Semantics and Specification Language (DSSSL)?

Document Style Semantics and Specification Language is an international


standard, an expression language, a styling language for associating processing
(formatting and transformation) with SGML documents, for example XML.
The specification and draft can be found at http://www.jclark.com/dsssl/

29. What is Extensible Stylesheet Language (XSL)?

XSL is a proposed styling language for formatting XML (eXtensible Markup


Language) documents. The proposal was submitted to the W3C by Microsoft,
Inso, and ArborText.

30. Tips

Tip
Netscape seems to have a problem with rendering the last row of justified text
correctly, that is not justified last row. The solution to the problem is white space
between the text and the closing tag, e.g.:
<P style="text-align: justify>Text
</P>
Tip
The actual width of SIZE and COLS attributes used with INPUT and TEXTAREA
elements, respectively, is based on character width. Internet Explorer displays the
content of TEXTAREA in monospaced font therefore the width of these two fields
differs even when the same value is set to the SIZE and COLS attributes. To get the
elements equally long/short the same font must be declared to both of them, e.g.:
<INPUT NAME="name" TYPE="text" size="40" STYLE="font: normal 10pt Arial">

<TEXTAREA NAME="name" ROWS=4 COLS=40 STYLE="font: normal 10pt Arial">

How come my styles don't work in [insert browser here]?


Although there can be many different answers for this simple question, the first thing to
check is that you have correctly written your styles, and that you have a correctly-written

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


101

page. In order to do this, make sure you validate both your page and its stylesheet using
the W3C validators:

• W3C CSS Validator

• W3C HTML Validator


Once you're sure that you've eliminated all HTML and CSS errors, then it makes sense to
start looking for browser bugs—not before.
How can I apply styles to form elements like INPUT and SELECT in Navigator 4.x?
You can't do this correctly. It is possible to trick Navigator into grabbing styles from
parent elements, but this is an exploitation of a bug in Navigator's inheritance code and
should only be used as a last resort. This is especially true since the workaround can
introduce even worse dislpays in other browsers.

I'm trying to get Navigator 4.x to use 'hover' styles on hyperlinks, but nothing happens.
What's wrong?
The good news is that you probably aren't doing anything wrong. The bad news is that
Navigator 4.x doesn't support the hover pseudo-class, so any attempts to make it work
will be futile. There are rumors of Javascript workarounds, but these almost always turn
out to be related to image-rollover effects.

I set styles on the BODY tag, but none of my page's text has the specified style. Why not?
In most cases, this is because you have laid your page out using tables. For a variety of
reasons, table implementations in current browsers will break the CSS inheritance
mechanism, so setting styles on the BODY tag is not enough (even though it really
should be). Modify the selector of your BODY rule to look like this:

BODY, TABLE, TD, TH


This will apply the styles directly to TABLE and table cell elements. Note that this will
only sometimes work in Navigator, which has extra-special problems with tables and
styles.
I set an ID on a table cell, and then wrote a rule for it, and Navigator 4.x is ignoring it
completely. Why?
Navigator 4.x doesn't particularly like ID selectors, so the best thing to do is convert your
IDs to classes and adjust your rules accordingly. Note that this may lead to other
problems with the cascade, since ID selectors have a higher weight than class selectors.

How can I use CSS to enforce a specific width for the document?
To begin with, you shouldn't be doing this with Web pages—document widths are
appropriate for paged media (such as printouts), but not Web browsers. If you're still
determined to do this, then in theory you can set a width on the BODY element, like this:

BODY {width: 666px;}


This behavior is not well supported, however; only MacIE 4.5+, Opera 3+, and Navigator
6 will even attempt to do as you ask.
My styles look great in a Web browser, but when I print out the page, I get horribly
mangled output (one line of text per page, etc.)!

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


102

If you're printing in Navigator 4.x, check to see if your styles use the line-height property.
If line-height is set using points or length units (ems, pixels, inches, etc.), the pages get
kafluffled.

How can I remove the underline from hypertext links?


Try:
<html>

<head>

<style><!--
A { text-decoration:none }
//--></style>

</head>

<body>
<p>
<a href="...">This is not underlined in Internet Explorer 4+ and Netscape Navigator 4+</a>
</p>
</body>

</html>
What does CSS cascading mean?
There are 3 different types of style sheets:
• Author: Created by the author of the document your are browsing. Designed to fit the site your are currently
visiting.

• User: Your very own style sheet, created to fulfill your own needs.

• User agent: Default style sheets inside the browser you're using.

These 3 different style sheets will overlap in scope, and they then interact according to
the cascade, which assigns a weight to each style rule. When several rules apply, the one
with the greatest weight takes precedence.
Imported style sheets also cascade, and their weight depends on their import order.
The cascading order is then the order in which the user agent finds the value for an
element/property. User agents use the following algorithm:
1. Find all declarations that apply to the element and property in question, for the target media type.

2. Sort the declarations by weight and origin: For normal declarations, author style sheets override user style
sheets which override the default style sheet. For "!important" declarations, user style sheets override author
style sheets which override the default style sheet.

3. Sort by specificity of selector: more specific selectors will override more general ones.

4. Sort by order specified: if two rules have the same weight, the latter specified wins. Rules in imported style
sheets are considered to be before any rules in the style sheet itself.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


103

The search for the property value is then terminated, when any of the above steps yields a
rule, that has a higher weight than the other rules, that apply to the same element/property
combination.
All in all, apart from the "!important" setting, author style sheets have higher weight than
those of the reader.
How do I insert style then?
The following code will make the H1-tag in your HTML-document blue:
<HTML>
<TITLE>CSS FAQ</TITLE>
<STYLE type="text/css">
H1 { color: blue }
</STYLE>
<BODY>
<H1>The CSS FAQ</H1>
</BODY>
</HTML>
How do I link to an external CSS style sheet?
Use the LINK element:
<HTML>
<TITLE>CSS FAQ</TITLE>
<LINK rel="stylesheet" href="faq.css" type="text/css">
<BODY>
<H1>The CSS FAQ</H1>
</BODY>
</HTML>
The advantage with external style sheets, is that they can be reused on several HTML
documents. If you want to change the style of your pages, you also do not have to alter
the HTML code, but only the style sheet.
How do I import a CSS style sheet?
There are 2 valid ways of importing style rules from other style sheets:
@import "faq.css";
@import url(myway.css);
So that browsers can avoid retrieving resources for unsupported media types, authors
may specify media-dependent @import rules using the following code:
@import url(readable.css) print;
@import url(visual.css) projection, tv;
Can do I have a primary and secondary CSS style sheet?
Yes!
What happens is, that you have defined your P-tag as Verdana. For some reason, you then
want all files in the /garamond/ subdirectory to use Garamond instead of Verdana.
Instead of defining a class, you just import another css file using the following code:
<STYLE>
@import url(basic.css);
@import url(garamond.css);
</STYLE>

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


104

If you use this in all files in the subdirectory, declarations in garamond.css will override
settings from the "basic.css" style sheet, since it comes later in the cascade. M/p>
This concept, is also possible in RDF, where you can have multiple DTD's as your
vocabulary.
What's the difference between a user and author CSS style sheet?
An author style sheet is a style sheet you download, when you surf WebPages.
An user style sheet is your own personal style sheet, that resides inside your very own
browser & PC. If you in your personal style sheet had defined, that you want to display
the P-tag with Arial and font size 16, this would not overrule the author style sheet,
unless you had marked it with "!important".
What is the !important CSS rule?
CSS tries to create a balance of power between author and user style sheets. By default,
rules in an author's style sheet override those in a user's style sheet.

However, for balance, an "!important" declaration takes precedence over a normal


declaration. Both author and user style sheets can contain "!important" rules, but user
"!important" rules override author "!important" rules.

Note: In CSS1, it works the other way: Author "!important" rules took precedence over
user "!important" rules.
If you, in your style sheet want to mark something as important, use the following code:
P { font-size: 18pt ! important }
You are telling your user, that it is important, that you use 18pt, as your fontsize.
Is CSS case sensitive?
No!
Just remember that font family names and URLs can be case sensitive (these are not
controlled by CSS though). E.g. http://www.IRT.org/lOgO.gif, might not be the same as
http://www.irt.org/LOGO.GIF
How do I include comments in CSS?
As with any other language, you probably want to include comments, to make things
easier, not only for yourself, but also for your users.

In CSS comments begin with "/*" and end with "*/".


Here's an example:
<STYLE>
/* As big as it gets */
P.big {font-size: 72px}
</STYLE>
CSS also allows the SGML comment delimiters ("<!--" and "-->) in certain places, but
they do not delimit CSS comments.
CSS style sheets and printing?

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


105

While Style Sheets are great for screen presentation, you must practice caution when
defining font sizes in pixels, if your site visitors frequently print out content from your
site. You may define font sizes in "points" instead. By nature "pixels" are relevant to the
output devices resolution, while points (pt) are device-independent measurements. For
example, consider the following lines of code:
<style>
P {font-size: 72px}
</style>
On a printer with a 75dpi resolution, 72px is around 1 inch, at 150dpi--less than 1/2 inch,
at 300dpi--less than 1/4 inch, and at 600dpi--less than 1/8 inch. To remedy this problem,
use
<style>
P {font-size: 72pt}
</style>
Your printed font size will be 1 inch in all resolutions we described above.
How do I insert a CSS page break?
The following code will force a pagebreak in CSS2:
<P style="page-break-after: always">
NN4 does not support CSS2, neither does MSIE4 completely support CSS2.
How do I avoid a CSS page break?
The following code will try to avoid a pagebreak, whenever it reaches the H1-tag:
<H1 style="page-break-after: avoid; page-break-inside: avoid">
How do I get rid of the underlining of hyperlinks using CSS?
The following CSS code will do the trick in external or document-level style sheets:
A { text-decoration: none }
In inline styles, use the following code instead:
<a href="http://www.w3.org/TR/REC-CSS2" style="text-decoration: none">
The CSS2 Recommendation from the W3C</a>
If CSS is supported in your browser, the following link should not be underlined: The
CSS2 Recommendation from the W3C
How do I insert a bold line into a table using CSS?
Try the following code:
<TR STYLE="border-bottom: thick solid #FFFFFF>
How do I make my HTML document speak using ACSS?
The aural rendering of a document, commonly used by the blind and print-impaired
communities, occurs by converting the document to plain text and feeding this to a screen
reader - software or hardware, that simply reads all the characters on the screen.
Besides the obvious accessibility advantages, there are other large markets for listening to
information, including in-car use, industrial and medical documentation systems, home
entertainment, perhaps it could even work nicely with a phone.
Consider the following example:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


106

H1 {
voice-family: Romeo, male
}
P{
voice-family: Juliet, female
}
All H1 tags will then be read by a male voice, and P tags will be read by a female voice.
What browsers support ACSS?
Since ACSS still is only a W3C Working Draft, no browsers support it - unfortunately.
There are though still software, that will read the Web for you:
Productivity Works have created pwWebSpeak, a Windows program, that works as an
Internet browser for users who wish to access the Internet in a non-visual or combined
auditory and visual manner.
The Emacspeak system, is a speech output system for Emacs. If you cannot see, and are
working on the UNIX platform, this software will help you
How do I turn up the volume using ACSS?
You can set the volume, to any number between 0 and 100. 0 represents the minimum
audible volume level, and 100 corresponds to the maximum comfortable level.
You can also use:
• Silent: No sound at all. The value 0 is not the same as silent!

• x-soft: Same as 0

• soft: Same as 25

• medium: Same as 50

• loud: Same as 75

• x-loud: Same as 100

Here's an example:
H1 {
voice-family: Romeo, male
volume: 60
}
P{
voice-family: Juliet, female
volume: loud
}
The male voice, Romeo, will then not be as loud, as the female voice, Juliet.
How do I make my document speak faster using ACSS?
In some cases, if you're in a rush, you might want your document to speak real fast. Just
as with volume, there are different speech-rates:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


107

You can specify any number, as the speaking rate in words per minute. This quantity
varies somewhat by language, but is nevertheless widely supported by speech
synthesizers.
You can also use:
• x-slow: Same as 80 words per minute

• slow: Same as 120 words per minute

• medium: Same as 180 - 200 words per minute

• fast: Same as 300 words per minute

• x-fast: Same as 500 words per minute

• faster: Adds 40 words per minute to the current speech rate

• slower: Subtracts 40 words per minutes from the current speech rate

Try this:
H1 {
voice-family: announcer, male
speech-rate: medium
}
P{
voice-family: Juliet, female
speech-rate: 250
}
Juliet will then be talking a bit faster than the announcer.
How do I insert a pauseusing ACSS ?
To make your document more usable, you might want to insert small breaks, after each
paragraph. This is done with the following code:
P{
voice-family: Juliet, female
volume: loud
pause: 20ms
}
P.slow {
voice-family: Juliet, female
volume: loud
pause-after: 10ms
}
How do I play background sound using ACSS?
While an element is spoken, you can use the play-during property to specify a sound to
be played as a background.

Try this:
P{
voice-family: Juliet, female
volume: loud
play-during: none

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


108

}
P.sad {
voice-family: Romeo, male
volume: medium
play-during: url(violin.aiff)
}
P.happy
voice-family: John, child
volume: medium
play-during: url(piano.wav)
}

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

You might also like