Professional Documents
Culture Documents
CSScomplete PDF
CSScomplete PDF
CSScomplete PDF
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.
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
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>
(<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
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.)
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.
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
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>
</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.
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.
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.
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
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.
• )
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
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.
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>
</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.
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()">
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) +
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>
<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
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.
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.)
• 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.
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.
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.
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.
Additional Options
Simplification through grouping
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.)
...
<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).
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 */
Quick Reference
Attribute Description Values Example
font-size Sets size of text. points (pt) {font-size: 12pt}
inches (in)
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}
{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%}
(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.)
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.
(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.)
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: #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.
and take advantage of Internet Explorer's support for this standard to create stunning
pages and formatting effects.
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.
B { text-transform:uppercase; }
P{
border:silver thick solid; background-color:turquoise;
padding:10px; text-align:center;
}
--></STYLE>
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.
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.
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.
.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"><!--
--></STYLE>
<P ID="idPinkP">
...je vois la vie en <SPAN ID="idBoldItal">rose</SPAN>...</P>
Result:
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"><!--
--></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:
<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.
--></STYLE>
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>
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>
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:
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).
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.
//--></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
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
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
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 |
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
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
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
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
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.
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;
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
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;
• 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.
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.
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.
• 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
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()">
</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;
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.
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
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
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.
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;}
-->
</STYLE>
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
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.
• Table Layout
• Joining Borders
• 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.
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
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
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">
<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>
<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
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
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?
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>
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?
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.:
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
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?
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.
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>
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}
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}
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.
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>
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}
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.:
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>
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?
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.
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.
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
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.
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.
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).
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:
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:
o Konqueror
o Arena
o Emacs-w3
o Amaya
o Lexicon
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
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}
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>
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}
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).
HTML:
<A class=set1 .....> will show colors as specified in class "set1"
<A class=set2 .....> will show colors as specified in class "set2"
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?
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.
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.
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?
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}
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.
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.
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.
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.
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?
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.
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;}
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.
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">
page. In order to do this, make sure you validate both your page and its stylesheet using
the W3C validators:
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:
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:
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.
<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.
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>
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.
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.
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:
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
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:
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
• 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
}
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)
}