| ★ wanayoo — archive 1999 http://www.dhtmlzone.com/articles/dhtmlcss.html | Nouvelle recherche | Portail wanayoo |
Dynamic HTML and Cascading Style Sheets (CSS)
By Nick HeinleA powerful partnership: DHTML and CSS
CSS brings powerful layout and designcapabilities to DHTML. With CSS, you can specify font sizes and faces, margin heights and widths, borders and padding, even text decoration. In addition, using CSS you can create absolutely positioned content. No longer do you have to toil with complex and limited tables; now content can be contained within movable, malleable blocks. This visual control and accuracy, when combined with scripting languages and powerful object models, gives web authors the power to make any document more engaging.Introducing CSS
CSS is a language in itself, one of the many languages that you'll need to know to master DHTML. The purpose of CSS is to define styles for a document's content. A style can instruct a word to be blue or specify that the text on the first line of a paragraph be capitalized. CSS allows its styles to be grouped, associated, and applied to specific elements.Understanding styles
A style is a grouping of properties that define how an HTML element will appear in a document. For example, a CSS style could say, "make this text green, 24 points, and give it a left margin of 5 pixels."
<DIV STYLE = "color: green; font-size: 24pt; margin-left: 5px"> Green Giant </DIV>Notice that the text is surrounded by a DIV tag. For a style to be applied to an HTML element, that element must be contained by a tag (such as DIV, A, SPAN or even P). Inside the tag, there's a special attribute, STYLE, in which the CSS style for the element is defined.
The CSS syntax is very different from that of HTML. First, each property (for example, color and font-size) is separated from its value by a colon [:]. Property-value combinations are separated by semi-colons [;]. If you take a close look at these style properties, you'll see that they do what they say. The color property defines the text's color, the font-size property defines the text's point size, and so on.
There are many style properties in the CSS specification. To learn more about them, visit the World Wide Web Consortium's CSS reference page.
Grouping styles: classes and style sheets
The previous example shows a single style being applied to a single element. This is called an inline style. When you group multiple style properties together betweenSTYLEtags, you create a style sheet.
<STYLE> .greengiant { color: green; font-size: 24pt; margin-left: 5px; } .littlered { color: red; font-size: 12pt; } </STYLE>This style sheet contains two unique groupings of CSS style properties, namedgreengiantandlittlered. The names of these groupings are referred to as classes. Class names are preceded by a period [.], and the style properties that comprise the classes (for example, font-size) are placed between opening and closing curly braces. This is the syntax for creating classes of styles within a style sheet.Once a class had been defined in the style sheet, it can be applied to any HTML elements on the page. To apply a class from a style sheet to an element on the page, surround the target element with a tag and add the CLASS attribute with the name of the class (leave off the preceeding period).
<DIV CLASS = "littlered"> Riding Hood </DIV>This example applies the style attached to thelittleredclass to the text enclosed in the DIV tags. Based on the style properties defined for thelittlered class, the text would appear in a red, 12 point font.Applying styles to existing tags
In addition to applying CLASS styles to tags, you can also apply styles directly to the tags themselves. For example, all of the links on a page could be made to have no underlining, or all P tags could indent the first line by 5 pixels.<STYLE> A { color: green; font-size: 24pt; text-decoration: none; } </STYLE>In this example, all of the links in the document will appear in a 24 point green font with no underline. The syntax is almost the same as with classes, except that the grouping of styles is given the name of the target tag (in this case A) instead a unique class name preceeded by a period.Absolute positioning
CSS has properties that enable absolute positioning of HTML elements, allowing content to be placed at exact x, y, and z coordinates. This gives you more control over the layout of a page, and when combined with DHTML, allows you to animate absolutely positioned content.To create absolutely positioned elements with CSS, first create classes for the elements that need to be absolutely positioned (or use inline styles), then apply those classes to the elements on the page. The following code creates an absolutely positioned piece of text:
<HEAD> <STYLE> .hilda { position: absolute; top: 100px; left: 50px; visibility: visible; z-index: 1; color: #008000; font-family: times; font-size: 72px; } </STYLE> </HEAD> <BODY> <DIV CLASS = "hilda">Hello Hilda</DIV> </BODY>The style sheet class in this example,hilda, is initially defined as an absolutely positioned class--its position property is set to absolute rather than relative.The left and top properties define the x and y coordinates. The left property determines the location of an element's left side relative to the left side of the document, and the top property determines the location of an element's top side relative to the top of the document. In this example, the text that this class is applied to is positioned 100 pixels from the top of the page (top: 100px) and 50 pixels from the left of the page (left: 50px).
The visibility and z-index properties are also important. The visibility property specifies whether an element is hidden or visible. The z-index property controls the layering of an element. If two elements overlap, the element with the higher z-index will appear on top.
Controlling CSS through DHTML
Note:
The syntax for creating CSS documents is the same in both Navigator 4 and IE 4, but the syntax for controlling CSS properties is not because there is currently no "official" document object model. This is only temporary; Netscape and Microsoft have pledged future support for a standard that is being formulated by the World Wide Web Consortium (W3C).In theory, scripting languages like JavaScript and VBScript have access to every property of a CSS style through the document object model. This means that a style applied to a link could change when the mouse is moved over it, the text of an article could expand in size when the reader selects it, or an absolutely positioned element could move across the page when clicked. In practice, only IE 4 has access to all the CSS style properties. Navigator 4's script access is limited to the absolute positioning properties (left, top, z-index, and visibility).
IE 4and Navigator 4 also have different ways of referring to elements in a document. The following example illustrates these differences and how to access the style properties of HTML elements through the document object model.
<DIV ID = "hildaElement" CLASS = "hilda">Hello Hilda</DIV>Notice that the new attribute ID has been added to the
DIVtag. (The ID attribute and the NAME attribute are identical in terms of the document object model: either one can define an HTML element's unique name.) To accesshildaElement's style properties in Navigator, the JavaScript syntax is:
document.hildaElement.styleProperty;In this example,
documentis the object that represents the document,hildaElementis the HTML element with the IDhildaElement, andstylePropertyis a given style property of that element, such as z-index.To access this same element and its style properties in IE, the JavaScript (actually JScript, Microsoft's JavaScript-like language) syntax is:
document.all.hildaElement.style.styleProperty;Notice that there are two additional objects in this example: the
allobject afterdocument, and thestyleobject betweenhildaElementand its style property.Because the IE document object model is currently more expansive that the Navigator object model, the remaining code examples will refer to IE's syntax and capabilities. See "Handling CSS compatibility issues" later in this document for more information.
Dynamic styles
Based on the explanations in the previous section, understanding how to access and control the style properties of HTML elements is relatively simple. In this example, a selection of text is surrounded by aDIVtag which has a CLASS attribute that points to a style sheet class namedsmallgreen:
<DIV CLASS = "smallgreen" ID = "smallbig"> Small is Big </DIV>Once the HTML element is given a unique name with the ID attribute, a script can control the style properties of the element. For example, to change the font-size property ofsmallbig, access the element's style property and from there itsfontSizeproperty. (fontSizeis the same property that CSS uses to controlfont-size, but because of naming limitations in scripting languages, the hyphen is replaced with an intercap.)
document.all.smallbig.style.fontSize = 24;To change
smallbig's color to blue, simply repeat the above process, substitutingcolorforfontSize.
document.all.smallbig.style.color = "blue";Dynamic positioning
Controlling the absolute positioning of HTML elements is similar to controlling an element's style properties. However, you can use special techniques with absolute positioning to achieve such effects as animation and gradual movement.For example, to move an HTML element from one part of the page to the other, you could simply change the left or top properties of the element like this:
document.all.someElement.style.left = 100;To achieve more control you can use functions to incrementally move the element. This JavaScript function, for example, slides the element from the top of the page to the bottom:
function slideElement(theElement, from, to) { if (from < to) { theElement.style.top = (from += 10); setTimeout('slideElement(' + theElement + ',' + from + ',' + to + ')', 50); } }To use this function, pass it the target element, the initial top coordinate, and the final top coordinate:
slideElement(document.all.someElement, 0, 30 0);When the function is run, it moves the element down the page 10 pixels at a time until it's 300 pixels from the top.
It works like this: the function is initially passed values of 0 and 300 as parameters
fromandto. It's also passed the element that will be moved,document.all.someElement. Iffromis less thanto, the function increases the value offromby 10 and gives that number to the HTML element's top property, thereby moving the object down the page 10 pixels at a time. The setTimeout() method repeats the function every 50 milliseconds, continuing the process until the HTML element is 300 pixels from the top of the page.Another simple effect is hiding and showing HTML elements using the
onMouseOverandonMouseOutevent handlers. You only need two small functions for this:function showElement(theElement) { element.style.visibility = 'visible'; } function hideElement(theElement) { theElement.style.visibility = 'hidden'; }Pass each of these functions the name of the element to be hidden or shown. For example, when the mouse is moved over the link below, an element calleddescis made visible:
<A HREF = "/old?u=http%3A%2F%2Fwww.dhtmlzone.com%2Farticles%2Fhome.html&y=1999" onMouseOver = "showObject(document.all.desc)" onMouseOut = "hideObject(document.all.desc)">Home</A>Handling CSS compatibility issues
You can easily resolve the CSS compatibility issue by adding some additional JavaScript code to your document. This code begins by determining which browser is being used:var isNS = (navigator.appName == 'Netscape' && parseInt(navigator.appVersion) >= 4);Here a variable,isNS, tells you if the browser is Navigator 4 or not. After determining the browser, use a conditional to assign the HTML elements on the page to shortcut variables which will be accessible to both browsers. This example creates a variable calledhildaRefthat will be used to referencehildaElement's style properties.
var hildaRef = (isNS) ? document.hildaElement : document.all.hildaElement.style;The variable
hildaRefis set equal todocument.hildaElementif the browser in use is Navigator 4, anddocument.all.hildaElement.styleif it's not Navigator 4. The assumption is that if the browser isn't Navigator 4, it's IE 4 (a rather dangerous assumption; you'll probably want to do additional checks before this to weed out non-DHTML browsers). To use this code, put the actual HTML element in place of theElement.After giving the HTML element to a shortcut variable, it can be controlled through the shortcut variable in both Navigator and IE. For example, the syntax to change the left property of
hildaElementis:
hildaRef.left = 100;