Stuart Moulthrop & Nancy Kaplan
University of Baltimore
School of Communications Design · 2000

Week 5: Forms and Stylesheets


5.1 | FORMS


In HTML, a form is a special division of the page designated by a <FORM></FORM> container. Within this container, other tags and containers are used to produce so-called interactive elements. Some of these components, such as check and "radio" buttons or fill-in fields and areas, allow the user to make choices or enter information. Others, such as action buttons, call up specific functions.

Forms have always been an enormously important aspect of Web design (if not the most visually attractive). Now that the Web is used extensively for e-commerce, forms are even more crucial. Forms are our most powerful tool for turning Web pages from static displays into dynamic documents.

Like all powerful tools, however, forms are complicated--not so much in themselves as in their integration with other structures. Forms provide the potential for interactivity on Web pages, but in order to process the data they collect, you usually need a program of some kind. This is often a Common Gateway Interface Script (CGI) written in PERL, Python, C++, or some other language. Forms may also pass data to application servers such as ASP and Cold Fusion. All these mechanisms reside at the server level, which is beyond the purview of this introductory course. We'll teach you to build and use forms here, but Web applications and server-side scripting are taught in other, more advanced courses.

This limitation has one important exception: JavaScript, to which we come in Week 6. Form elements are (in the technical parlance) exposed to JavaScript and other Web scripting languages (JScript, VBScript). That means that scripts residing entirely on your page can receive and process information from forms--so at least some limited interactivity can take place without re-opening a channel to the server. As you'll see next week, the combination of forms and JavaScript can be powerful indeed. But for the moment, forms themselves:

5.1.1 · The FORM Container

    The FORM tag is a container. It can take several attributes but the most important ones are METHOD and ACTION.

    METHOD specifies how the form data will be passed along by the browser. You can choose between get and post. The get method appends data to a URL (which probably seems a bit strange on first presentation) and thus limits the amount of data you can send to 100 characters. The post method is the more common because it does not restrict the amount of data you can send.

    ACTION tells the form where to send the data collected through its input elements. Often, ACTION specifies the URL of a script intended to handle processing at the server end. (Lots of things besides Web pages can have URLs.)

    One useful ACTION that does not require processing on the server, however, is a MAILTO:. Here's a sample of a FORM container specifying that the form's contents be sent via e-mail:

      <FORM METHOD="post" ACTION="mailto: nakaplan@ubmail.ubalt.edu">
        [ form elements go in here ]
      </FORM>

    A form with a simple action such as this might be used to solicit comments on a Web page. You could do much the same thing with a MAILTO: link, of course, but as we'll see, form elements (the unstated middle parts in the example above) let you tailor the response more carefully than you could in a simple mail link.

5.1.2 · INPUT element

    The INPUT element is the most general type of form element. It is a solitary tag used to create the following:

    standard text fields
    password fields
    check boxes
    radio buttons
    submit and reset buttons

    To differentiate among all these varieties, the INPUT element uses the TYPE attribute. Below is a list of common VALUES for the TYPE attribute.

    TEXT
    An INPUT whose TYPE is "text" usually has three other attributes as well: NAME, SIZE, and MAXLENGTH.

    The NAME attribute is an arbitrary designation used to differentiate one input field from another. You must use a unique NAME for each text input field in your form.


    The SIZE attribute specifies the width of the INPUT field. Up to now we've sized everything either in pixels or percentage of available space. Forms break with this pattern. The SIZE attribute of the text input element is measured in characters--which of course raises some problems. The characters in question are teletype or monofont (usually some variation of Courier), but though all monofont characters have the same width, that width varies with font size, and users are able to select both font face and size for monofont or fixed-width type. As a practical matter, you'll need to work out the width of text input boxes by estimate, trial, and error.


    The MAXLENGTH attribute specifies the maximum number of characters a user can type into the field. MAXLENGTH can be a larger value than SIZE (as it is in the sample text field in the first row of the table above). When MAXLENGTH exceeds SIZE, each new character typed in pushes a character out of sight at the left side of the text box. This is not a good practice. Keep SIZE and MAXLENGTH equal.


    PASSWORD
    An input element whose TYPE is set to "password" is really just an ordinary text field with one variation: the characters typed in appear as asterisks or bullets so that no one but the user knows what is being typed. NAME, SIZE, and MAXLENGTH are usually set for this element as well.


    CHECKBOX
    There are two ways to use checkboxes: alone or in groups. If you need only a single checkbox, you simply write this within the FORM container:

    <INPUT TYPE="checkbox" NAME="[name]">

    Using programming techniques we won't discuss at this point, it's then possible to detect the state of the checkbox by asking for the value associated with its name.


    A group is constructed by giving each checkbox element in the group the same NAME. Grouping checkboxes makes things a tiny bit easier on the programmer who has to extract their values, though practically speaking you could achieve much the same end by using a series of ungrouped elements (i.e., having unique names)

    To identify which box in an exclusive group was checked and which were blank, I need to assign each check box a unique VALUE. For example, to construct a list of subjects in which the user might be interested, I could create a sequence of check boxes like this:

      <INPUT TYPE="checkbox" NAME="categories" VALUE="politics"> politics
      <INPUT TYPE="checkbox" NAME="categories" VALUE="international markets"> international markets
      <INPUT TYPE="checkbox" NAME="categories" VALUE="weather"> weather
      <INPUT TYPE="checkbox" NAME="categories" VALUE="sports"> sports


    Note that we've echoed the VALUE string as ordinary text following the end of the INPUT tag. We've shown these strings in red above. Though this text is important--you wouldn't want to present an unlabeled option--it is not part of the tag and does not need to correspond exactly to the VALUE. I could have a checkbox whose VALUE is "noWayBud" but whose accompanying text reads, "I disagree" or "Perhaps not."


    Also notice that there are no <BR> tags following the text labels. This is yet another small inconsistency of syntax--being one of the oldest additions to HTML, forms are swarming with these departures from standard practice. The solitary <INPUT> tag forces a line break after any text that follows it. Since there is no </INPUT> tag in orthodox HTML, the signal for the line break is another <INPUT> tag, some other form element tag, or the </FORM> tag.


    The page output for the example above is what you see below:


    politics
    international markets
    weather
    sports
    RADIO
    Radio buttons work in much the same way as checkboxes, but with a crucial twist: they behave like the mechanical interface of old car radios (hence the term). In these devices, pressing the button for a new station caused the button for the previous station to pop back into the unpressed position. Only one button could be pressed at a time.


    Like check boxes, radio buttons are grouped together through the NAME attribute and require a VALUE attribute to differentiate members of the group from one another; but where a user can select any number of check boxes within a single group, s/he can check only one radio button. When one member of the group is selected, the others are automatically de-selected. Radio buttons are thus used for mutually exclusive options.

    Using radio buttons, the example above would look like this:

      <INPUT TYPE="radio" NAME="categories" VALUE="politics"> politics
      <INPUT TYPE="radio" NAME="categories" VALUE="international markets"> international markets
      <INPUT TYPE="radio" NAME="categories" VALUE="weather"> weather
      <INPUT TYPE="radio" NAME="categories" VALUE="sports"> sports

    Again, we've echoed the VALUE for each button in plain text outside the tag (shown once again in red), and there's no requirement that the text next to a radio button must be the same as its VALUE string. Here's the markup in action. Try the buttons yourself:
    politics
    international markets
    weather
    sports
    SUBMIT and RESET
    Each of these values for the TYPE attribute creates a button with a particular, predefined function. SUBMIT sends the form data to the script specified in the ACTION attribute of the FORM tag. RESET clears any input the user has entered into the form, returning all binary elements (checkboxes, radio buttons) to their unselected state.

    The VALUE attribute that goes with this INPUT type specifies the words that appear on the button as its label. Note that you can assign values other than "Submit" and "Reset" to these buttons--"Send Data" and "Clear Form," for instance--but try to keep these values useful.

5.1.3 · Text Areas

    This element specifies a free-form input area where your visitors can type whatever they want. Unlike the INPUT elements, <TEXTAREA></TEXTAREA> is a container requiring both a start and an end tag. It is sized by specifying values for two attributes: COLS and ROWS. The code looks like this:

    <TEXTAREA COLS="60" ROWS="4">Try typing here.</TEXTAREA>

    And the output like this:

     

    As in the case of the text and password INPUT types,COLS and ROWS are measured in character dimensions (width and height), and you will once more have to make a best-guess estimate about the exact size of this element.

    Instead of a text label, the TEXTAREA element allows for an initial entry into the text box, in this case the phrase "Try typing here," shown in red above. This welcoming message can be useful, but keep in mind the user will have to select over it in order to write her own entry.

    If you find the horizontal and vertical scrollbars ugly, too bad: there's no way to suppress them. Generally speaking, forms are not much fun to look at.

5.1.4 · Selection Lists

    The SELECT element is used to create static and drop-down menus. The element uses a <SELECT></SELECT> container requiring both a start and an end tag.

    It can accept a SIZE attribute to indicate whether the list will appear in a scrolling box (SIZE = "[any value greater than 1]") or a drop-down menu (SIZE="1"). Yes, this is yet another inconsistency, since SIZE here refers neither to pixels nor to characters but to the number of lines displayed. You'll simply have to memorize this along with all the other inconsistent details relating to forms, then reinforce your memory through practice.

    By default, the SELECT element permits users to choose only one option from the list. If you want to enable multiple multiple choices, you must use the MULTIPLE attribute. The MULTIPLE attribute does not take any value; it's a "flag" attribute like NOSHADE in the <HR> tag.

    The items in a selection list are marked with <OPTION></OPTION> containers which occur within the <SELECT></SELECT> container. You must include at least one OPTION container.

    The markup below creates a drop-down selection list with three choices:

      <SELECT NAME="animals" SIZE="1">
        <OPTION>lions</OPTION>
        <OPTION>tigers</OPTION>
        <OPTION>bears</OPTION>
      </SELECT>

    The results look like this; try it out:

    The menu "drops" down over the text below it, and that the value you select is left visible in the window after you release the mouse button.

    Note that no VALUE attribute is required for the OPTION element. The text typed between the two halves of the the OPTION tag becomes the text displayed in the list as well as the value passed when the form is submitted.

    The same code rendered as a scrolling field with multiple selection possibilities looks like this:

      <SELECT NAME="animals" SIZE="3" MULTIPLE>
        <OPTION>lions</OPTION>
        <OPTION>tigers</OPTION>
        <OPTION>bears</OPTION>
        <OPTION>mice</OPTION>
        <OPTION>voles</OPTION>
        <OPTION>moles</OPTION>
      </SELECT>

    Now the results look like this:

    If you hold down the shift key before you click, you may select as many options from this list as you like.

5.1.5 · Using Tables to Structure Forms

    On many occasions you may want to arrange form elements according to some regular grid. Suppose you have six checkboxes that need to be arrayed in two decks. Here's one possible markup for this form:

      <form>
        <input type="checkbox" value="aspidistra"> aspidistra
        <input type="checkbox" value="mayonnaise"> mayonnaise
        <input type="checkbox" value="camelsNose"> camel's nose
        <br>
        <input type="checkbox" value="crenellations"> crenellations
        <input type="checkbox" value="mustardPlaster"> mustard plaster
        <input type="checkbox" value="spoon"> spoon
      </form>

    The result is what you see below. (We've added a simple, one-cell table to introduce centering and a border. Forms have no alignment or borders.)

    aspidistra mayonnaise camel's nose
    crenellations mustard plaster spoon

    As you can see, the options are scattered around the screen in a way that makes reading very difficult. Compare this arrangement:

    aspidistra mayonnaise camel's nose
    crenellations mustard plaster spoon

    In this second example there are actually two tables: an outer, single-celled table to provide the visible border and an inner table with two rows and six cells. Each checkbox INPUT element is contained within one of those cells. Here's the markup for the inner table:

      <FORM>
      <table cellpadding="10">
      <tr>
      <td>
      <input type="checkbox" value="aspidistra"> aspidistra
      </td><td>
      <input type="checkbox" value="mayonnaise"> mayonnaise
      </td><td>
      <input type="checkbox" value="camelsNose"> camel's nose
      </td>
      </tr><tr>
      <td>
      <input type="checkbox" value="crenellations"> crenellations
      </td><td>
      <input type="checkbox" value="mustardPlaster"> mustard plaster
      </td><td>
      <input type="checkbox" value="spoon"> spoon
      </td>
      </tr>
      </table>
      </FORM>

    If you're a markup purist, you'll notice something rather weird here: the FORM container begins outside the TABLE container, even though all the elements of the form occur inside the table. Further, form elements and table elements are deeply intermingled. Strange though this may look, it's a very common practice and entirely harmless. In fact, you really should use a table to arrange form elements if your form contains more than a few parts.

    If this procedure bothers you, you can begin your form within the table structure. But where? Before or after the first <TR>? Before the first <TD>? Given the intertwining of table and form structures, several alternatives seem equally reasonable.

    Note that if you don't put the </FORM> tag outside the table, you'll end up with an extra blank line after the last table row.


5.2 | STYLESHEETS



5.2.1 · Conception and History

    Stylesheets represent an important step toward the future of Web design and publishing. They give authors much more refined control of document features such as font choice, color, positioning, indentation, line height, word spacing--even three-dimensional layering and (with scripting support) animation. Most important, stylesheets allow us to separate the logical structure of a document (embodied in its standard HTML tagging) from indications about specific appearance. This has been a major objective of markup languages since their beginning. It frees us to create documents that are independent of particular browsers, and browsers whose new features work smoothly along with existing documents.

    The World Wide Web Consortium (W3C) has published two specifications on stylesheets: Cascading Stylesheets Level 1 (CSS1) and Cascading Stylesheets Level 2 (CSS2). The Netscape Corporation initially proposed its own standard, JavaScript-Enabled Stylesheets (JSS) but its functions were largely incorporated into the Consortium's proposals. We'll stick with CSS1 and 2 here.

    Microsoft introduced limited support for CSS1 stylesheets with Internet Explorer 3.0. Their 4-series browsers greatly improved this support, and their 5-series browsers implement CSS1 almost completely. To Microsoft's credit, both Windows and MacOS versions of MSIE 5.x handle stylesheets reliably and well.

    Netscape has lagged behind. There was no stylesheet support in their 3rd-generation browsers and only limited and inconsistent support in the fourth generation, which at this writing is still current--a great delaying factor in the adoption of stylesheets. Netscape is skipping its fifth generation, and the beta release of their 5.0 browser reputedly matches Microsoft's handling of stylesheets; but it's been very slow to appear.

5.2.2 · Principles and Application

    Like "Web page," the term "stylesheet" is really an archaic reference, since on the Internet there are no physical pages, sheets, or slabs or paper. In years B.C. (before computing), publications kept a tangible object called a stylesheet, a page or more typically a small booklet listing house rules for handling certain aspects of editing and layout, such as when to use italic and when boldface, what to capitalize, how to identify people, etc. (The New York Times' stylesheet famously requires all celebrities to be referred to by last name; so the rock star Meat Loaf became "Mr. Loaf.")

    When word processors came along, the old stylesheet concept was picked up as a metaphor to describe a series of settings that could be applied to a document or its parts. The distinction here ("metaphor shear" as Neal Stephenson might say) lies in the fact that software stylesheets are automatic. Human editors may forget to put the title of a TV show in double quotes or the name of a company in italics, but if the author remembered to mark up those strings in the proper way, the software stylesheet will preserve the distinction. Stylesheets give us highly effective control over the appearance of documents.

    Before the introduction of HTML stylesheets, all sorts of visual elements had to be laboriously coded one instance at a time. Every time you wanted an element like a heading treated with an application of color, you would have to add a <FONT></FONT> container around the heading tag, or insert a COLOR attribute in the tag itself. Likewise, to apply color to a small segment of text, you would have to surround that segment with a <FONT></FONT> container. This approach has two major drawbacks:

    • If you decide to change the general color scheme for your work, you must hunt down and alter each <FONT></FONT> container or internal COLOR attribute; changes can't be made globally.


    • Since multiple instances of the same styling (a red headline, for example) have to be entered individually, it's very easy to overlook cases or make mistakes.

    Stylesheets correct this problem, letting you set specific rules for the display of markup elements such as the <BODY></BODY> and <P></P> containers, headings, lists and list elements, table elements, and the specialized containers <SPAN></SPAN> and <DIV></DIV> which essentially let you create customized markup elements.

    You can specify rules for these elements in three ways:

    1. By adding a STYLE attribute to the initial tag of the container itself. This is called in-line styling.


    2. By adding a <STYLE></STYLE> container in the HEAD division of your document. This is called an internal stylesheet.


    3. By adding a special LINK tag to the HEAD division. The link tag specifies that a text document located somewhere on the Internet contains the style rules for your document. This is called an external stylesheet.

    We'll discuss each of these methods in more detail below. For the moment, though, we need to explain what we mean by style rules and how they work. Since the number of features that can be controlled by stylesheets is very large, we won't be able to give a thorough survey in these notes; the reference text for this course contains a more complete account. You might also want to consult a specific text about stylesheets.

5.2.3 · Style Rules

    Stylesheet rules have this general form:

      PROPERTY: VALUE

    Notice that this syntax differs subtly from the standard ATTRIBUTE="VALUE" usage within HTML tags. You'll have to train yourself to use the colon instead of the equal sign when dealing with stylesheets--another one of HTML's charming inconsistencies.

    Stylesheet rules specify the feature to be styled and the treatment to apply to the feature. To style the text for a specific paragraph, for example, you would add a STYLE attribute to the tag (in-line styling). The value of the STYLE attribute is the rule or rules you want to apply to the text. If I want all the text in a paragraph to be displayed in a 10-point sans-serif font, I would write the initial P or paragraph tag this way:

      <P STYLE="font: 10pt sans-serif;">

    Note that style rules are always applied to the initial tag of a container, never to the closing tag (in this case, </P>). We'll give more specifics about font styling below. With rules for color and weight, the tag would look like this:

      <P STYLE="font: 10pt sans-serif; color: #660066; font-weight: bold">

    This last illustration above uses multiple rules within a single STYLE attribute. In this case, the rules are separated by a semicolon (;). No semicolon is required for the final rule of a series. Since in-line style rules are actually atttribute values (yes, this gets a bit tangled), they must be enclosed entirely within double quotes.

5.2.4 · Internal Stylesheets

    Adding style rules inside HTML tags works, but it is nearly as inefficient as the older method using the deprecated FONT tag, because each instance of the rule has to be coded separately. You should instead use a <STYLE></STYLE> within which you specify all the rules for various HTML elements. This container is called an internal stylesheet. If you look at the markup for this page and the other pages of these notes, you will see internal stylesheets in action.

    Usually located inside the HEAD container, a STYLE CONTAINER surrounds a series of selectors each of which is accompanied by its specific declaration or rule. Each declaration is contained within curly brackets--curly brackets or braces are produced on most keyboards by pressing SHIFT and [ to produce the left bracket and SHIFT and ] for the right bracket. Don't confuse curly brackets with parentheses. If you put parentheses in your stylesheets, the rules in question won't work.

    Here's an example of a stylesheet:

      <STYLE TYPE="text/css">
        P {FONT: 12pt serif}
        BODY {background: #FFFFFF}
        A:LINK {color: #0000CC}
        A:VLINK {color: #990000}
        H1 {font: 14pt serif; color: #660000}
        H2 {font: 12pt serif; color: #666666}
      </STYLE>

    Several things are worth noticing here.

    First, note that the initial STYLE tag contains a TYPE attribute specifying which variety of stylesheet the page uses. You must include this attribute, and unless you want to experiment with JavaScript-Enabled Stylesheets, stick with "text/css."

    You'll see that the selectors in this stylesheet all refer to familiar HTML elements such as the <P> tag, the <BODY> division, etc. But angle brackets are not used in specifying these elements. This detail can also wreck your stylesheet if you forget about it.

    Finally, notice that upper and lowercase letters may be mixed in stylesheets. There is one exception to this rule: When you establish classes of markup elements, you must spell the class name identically in all its occurrences.

    The internal stylesheet sets appearance rules for all markup elements on the present page. Consider the advantages of this arrangement: if you change your mind about the color to be applied to H1 or H2 headings, you only need to change the code in one location. Change a dozen headings with a single keystroke! Truly, you are now a Master of the Web... or anyway, you're a little less likely to develop Carpal Tunnel Syndrome.

    One more detail concerning internal stylesheets: some people (and more worrisome, some large organizations) still use browsers that do not recognize stylesheets--for instance, any Netscape Navigator in the 3-series. When these browsers encounter your <STYLE> container, they'll do what browsers always do when they encounter an unfamiliar container--look the other way and leave it out. But when they come to the material inside the tags, they'll simply dump it into your page. This will look rather ugly.

    To solve this problem you may hide the contents of your internal stylesheet by enclosing them in an extended comment tag. That container looks like this:

      <!--
      [Material for hiding goes here.]
      -->

    Note that though this tag is written conventionally on several lines, with its beginning and end separated as if it were a container, the extended comment element is really just a single tag: it has only one left and one right angle bracket. The comment material goes between the two pairs of double hyphens that mark the beginning and end of the tag. Yes, this is one more inconsistency in the syntax. Go figure, but get used to it: we'll recommend this technique again in Week 6 for <SCRIPT> containers.

    Here's an example of an internal stylesheet with hiding:

      <STYLE TYPE="text/css">
      <!--
        P {FONT: 12pt serif}
        BODY {background: #FFFFFF}
        A:LINK {color: #0000CC}
        A:VLINK {color: #990000}
      -->
      </STYLE>

    A word of warning: don't place your extended-comment tag outside the <STYLE> container, or it will knock out your entire stylesheet. The comment tag begins just after the initial <STYLE> tag and ends just before the </STYLE> tag.

    Finally, a last observation about stylesheet hiding: in another year or two it should become unnecessary, because contemporary browsers all support internal stylesheets.

5.2.5 · External Stylesheets

    An external stylesheet is a plain text (or ASCII) file with the extension .css. It contains no HTML markup and is not a Web page. It's stored independently from your markup page at its own Internet address (URL).

    The external stylesheet file contains all the information you would find in an internal stylesheet except for the <STYLE></STYLE> container (remember, no HTML tags in external stylesheets). So if we were to take the stylesheet from the above example and set it up for external use, we would first open a new text-only document in our text editor and then enter the following lines:

      P {FONT: 12pt serif}
      BODY {background: #FFFFFF}
      A:LINK {color: #0000CC}
      A:VLINK {color: #990000}

    That's all -- no containers, no comment tags for hiding. (Browsers that can't handle stylesheets conveniently also can't handle the tag that invokes external stylesheets, so there's nothing to hide from them in this case.) External stylesheets are usually very small documents indeed.

    Once we've moved the stylesheet instructions to an external file we can erase them (and the <STYLE></STYLE> container) from our Web page. But how to make these instructions active on the page once they've been thus removed? The answer is a special tag called <LINK> that occurs in the HEAD portion of the Web page markup (that's the .htm file, not the .css file). Here's what a link tag looks like:

      <LINK REL="stylesheet" TYPE="text/css" HREF="mystyle.css" >

    The <LINK> tag takes three attributes: REL (short for "relationship") specifies the function of the linkage in question; TYPE works here as it does in the <STYLE> container, indicating that we are using a CSS stylesheet encoded as an ASCII or text file; our old friend HREF gives the URL for that linked document. In this case the external stylesheet mystyle.css is assumed to be in the same directory as the present page.

    Note that as in other uses of HREF, the information on the other end of the equals sign can point anywhere on the Internet. That means that external stylesheets can be invoked by any page anywhere; more to the point, it means that you can use a single external stylesheet to establish display rules for hundreds or thousands of pages, simply by including in each of those pages a LINK tag that refers to your single, all-powerful stylesheet. Now you can change a million H1s with a single click!

    The astute or nosy reader may be wondering at this point why the page she is reading (Notes for Week 5) and its various cousins use internal stylesheets instead of a single, external stylesheet--arguably the more efficient approach. We stuck with the internal solution partly so that some stylesheet material would be visible to readers who viewed our source; but also because some browsers, particularly earlier versions of the Netscape 4-series, don't always process external stylesheets properly.

    So, practically speaking, should you use internal or external stylesheets? As with most advanced HTML features, from stylesheets to plug-ins, you need to consider your audience and communications context. If you're designing a company intranet, we suggest specifying stylesheet-capable browsers. Stylesheet documents are considerably more efficient and easier to maintain than older-fashioned HTML. On the other hand, if you're developing for the world at large and you run into problems with particular browsers, be ready to adapt. We have more to say about this with regard to cascading and degradation, below.

5.2.6 · SPANs, DIVs, Classes, and IDs

    To make stylesheets as flexible and powerful as possible, HTML 4.0 offers two new tags and two new attributes.

    The SPAN container is used to identify a short stretch of text to which a style rule can be applied. SPAN is an in-line element: it can occur within a paragraph or some other HTML element.

    The DIV container is a block element and can therefore include multiple paragraphs and other HTML elements. Where a SPAN can mark off a chunk of text within a paragraph, a DIV always marks off a whole section of a document. It will cause the browser to start the display of the text within the DIV container on a new line.

    You can use these containers as-is, with no modifying attributes. A common use of the SPAN container, for instance, is to mark local font changes, as in this example:

      <SPAN STYLE="color: #FF0000">seeing red</SPAN>

    This is of course an example of in-line styling, with the stylesheet rule applied within a STYLE attribute. Suppose, however, we have a document in which the same shade of red is applied 17 times at various points in the text. Then it would be better to use the SPAN container in a slightly different way:

      <SPAN CLASS="redText">too much blood</SPAN>

    This usage relies on either an internal or external stylesheet, either of which must contain the following:

      SPAN.redText { color: #FF0000 }

    Adding the class name followed by a dot (.) creates a unique reference for this particular class of SPAN. The advantage of internal or external stylesheets, as you now know, lies in central control: if we decide we'd like a different shade of red for those 17 occurrences, we only need to change one bit of code.

    Adding the CLASS attribute lets us create in effect a customized version of the SPAN container. There can be as many of these variants as we wish, letting us establish many different local text styles. An important usage note here: the value given in the CLASS attribute (in this case, "redText") must be spelled the same way, including capitalization, in all cases. It's just the same as the NAME attribute in anchor tags.

    We could also have handled SPAN styling in this example using another attribute: ID. The markup looks very similar to the previous example:

      <SPAN ID="redColor">I'm seeing red.</SPAN>

    Again, this reference inside the in-line STYLE attribute presumes other information in an internal or external stylesheet. But an ID differs significantly from a CLASS. The corresponding stylesheet material might look like this:

      #redColor { color: #FF0000 }

    This rule defines a named style called redColor. Note the hashmark (#), which must be used whenever you define a named style. It isn't used to define anything else in stylesheets, and it's not used when you invoke the named style in the ID attribute of a particular tag.

    In addition to particular <SPAN> containers, the named style can be applied via the ID attribute to nearly any tag in the markup. For instance:

      <P ID="redColor">
      <TD ID="redColor">
      <H3 ID="redColor">
      <DIV ID="redColor">

    As in the case of the CLASS attribute, you must take care to spell the ID value consistently at all times.

5.2.6 · Cascading Stylesheets

    Perhaps you've been wondering about the name Cascading Stylesheets. Is it meant to suggest an idyllic trout stream in some distant mountain wilderness? Or does it have more to do with, say... backed-up plumbing?

    A little bit of both, really (though you may be more often reminded of plumbing). CSS stylesheets are designed to share information and control over several levels of hierarchy. The local instance (i.e., one particular tag within a particular page markup) can be considered the high point of the cascade. Its in-line styling takes precedence over any other style rules that might apply. On the next level down is the internal stylesheet, if any, followed by the external stylesheet.

    Consider an example. Suppose I have a local <P></P> container with an in-line STYLE attribute calling for purple text. The internal stylesheet for my page specifies that text in all <P></P> containers be colored bright blue. My page also calls an external stylesheet which specifies bright red for paragraph text. Who wins? The most local code, meaning in this instance the in-line styling attribute: purple text it is.

    This is the theory, anyway. In practice, especially given the fact that Netscape's browsers don't completely support CSS1, the cascade effect sometimes doesn't quite work as planned. You should test and retest, keeping in mind that each major browser should be considered a separate entity. Try to test your pages in each of these six conditions.

    The Major Browsers
    Netscape Navigator for Win9x/NT Netscape Navigator for MacOS Netscape Navigator for Linux/UNIX
    Internet Explorer for Win9x/NT Internet Explorer for MacOS Internet Explorer for Linux/UNIX
5.2.7 · Degradation, Graceful and Otherwise

    The cross-platform, cross-browser testing we've just recommended will acquaint you with a key feature of stylesheets: so-called graceful degradation. This term does not refer to those new Martha Stewart trailer parks, but to a design principle in CSS1 and 2. Since in theory stylesheets simply specify visual treatment for basic elements of document structure, you shouldn't lose vital information if your browser fails to observe a particular style rule.

    This theory works well enough for, say, heading containers. Say we've styled <H1></H1> as 16-point Helvetica, colored gold against a royal blue background; and say we open our page using Netscape Navigator 3.03, a browser that regards stylesheets as so much grafitti. We still see the familiar first-level heading, set in the default large, bold type with no font, color, or background effects. So we still understand the text within the <H1></H1> container as a first-level heading.

    Okay, but suppose in addition to that gaudy H1 we've also decided to dispense with a table-controlled page width, relying instead on a WIDTH: 600px rule for the <BODY></BODY> container. In that same antique browser--or even worse, in certain of the Netscape 4-series--we find ourselves viewing an unconstrained Wall o' Text. Hmm.

    Be careful in applying stylesheets. In another year or two, when the last of Netscape's 4th generation has slipped into the bitbucket, it may be safe to rely on stylesheets for all aspects of layout. For the moment, though, you must be cautious.


5.3 | USING STYLESHEETS



5.3.1 · Font Styling

    The Web world (HTML/HTTP) has long lacked a key element of document design that is a given in desktop publishing: fine control over fonts. Until the advent of the (now deprecated) FONT container, there was no way to specify a font for Web pages: users saw virtually everything in whatever font they had chosen as a default for their browsers. The FONT container didn't improve matters all that much, since it only allowed control of color and "face" (by which Netscape meant font family, not typeface).

    Happily, stylesheets give you much more detailed command of fonts; though there are still important limitations. We'll review those limits first, then go into the various ways to manage fonts through stylesheets.

    Limitations on Font Styling
    Users can only see fonts that are installed on their computers. Early proposals for CSS included the concept of downloadable fonts, but since fonts are proprietary, their owners are reluctant to let them circulate freely around the Web. Alas, this means that many of the fonts well-loved by print designers (e.g., Frutiger and Univers) can't be used effectively in stylesheets. Most people don't have them installed.


    You might want to think about Web font options in terms of several clusters:


    Safe for All Systems Times
    Courier
    Symbol
    Arial, Helvetica (include both names)
    Internet Explorer Installed Arial Black
    Comic Sans MS
    Impact
    Verdana
    Microsoft Office Installed Arial Narrow
    Book Antiqua
    Bookman Old Style
    Century Gothic
    Footlight MT Light
    Impact
    Wingdings

    There are also several generic font specifications, including serif, which indicates any available serifed font (e.g., Times Roman, Palatino, or Garamond) and sans-serif, which asks for any available non-serifed font (e.g., Arial, Helvetica, or Geneva), and monospace which asks for a fixed-width font such as Courier.


    The FONT Selector
    The selector FONT: lets you specify font family, type size, and line height (leading) in a single rule. Here's an example:


      BODY { font: 14pt/16pt Palatino, Times, serif }

    The rule in this case is set for the BODY (i.e., for all text within the BODY container that is not controlled by other rules), but it could have been set for paragraph, headings, table elements, DIV, SPAN, etc.


    Note that the size and line height specifications come before the font family (or in this case, list of font families). We've used typeface points (pt) as the unit of measurement here, but you can also use inches (in), centimeters (cm), or pixels (px). The first term (14pt) indicates the type size (14 point) and the second sets line height or leading, the blank space between one line and the next (16 points in this case).


    We're using a font list here instead of a single specification. As you might guess, the list is sequential: the browser satisfies the first condition it can. If Palatino is installed, we see Palatino. If not, we try Times. Failing Times, we use whatever serifed font is handy. If no specifications work, the browser uses its default font.

    Finally, note that the specific font names are capitalized. Not only are font specifications case-sensitive, but they also demand exact spelling. "Times," for instance, does not match "Times New Roman." The generic option at the end of the list, "serif," is an exception. Generic font names do not need capitalization, though you do need to spell them correctly, and "sans serif" (wrong) will not match "sans-serif" (right).


    Other Ways to Specify Font Features
    There are also a number of finer controls for font features. The FONT-FAMILY selector lets you specify only a font name. The FONT-SIZE selector does the same for size. The FONT-WEIGHT selector lets you select normal, bold, or light weights (though the last probably won't have any effect). Theoretically, the FONT-VARIANT selector lets you specify that a given passage be rendered in small capitals ("small caps"); but again, this probably won't work unless you've specified a font that includes small capitals.


    There is likewise an individual selector for LINE-HEIGHT, plus selectors for WORD-SPACING and LETTER-SPACING. These are all dimensional features and may be set in points, pixels, inches, or centimeters.


    Color
    This selector should be abundantly familiar if you've been paying attention to the examples in these notes. You can set color for any text element, including horizontal rules.


    Text-Decoration
    The TEXT-DECORATION selector deserves particular mention. Its possible values are "underline," "overline," "line-through," "blink," and "none." While this selector can be used with any kind of text element, it's most popularly applied to the ANCHOR tag. For example:


      A:LINK { text-decoration: none }
      A:VLINK { text-decoration: none }

    These style rules suppress the underlining on link anchors--something many Web authors have wanted to do for a long, long time.
5.3.2 · Block Styling

    The stylesheet effects we'll discuss here concern layout rather than text effects--the position, alignment, and demarcation of blocks of text within your page. As you'll see once you start experimenting with block styling, once all browsers support the technique it will probably replace tables as the foundation of Web layout; though that's a few years away.

    What is a Block Element?
    Technically a block element is one that is set off by line breaks, the most common instance being the paragraph. You can style the <P></P> container as a block element, though a more interesting approach might be to style a <DIV></DIV> container instead. This lets you use paragraphs within the DIV for subordinate structure.

    Position
    Any block element can be given a POSITION selector. Values of this selector are "static," "absolute," and "relative." The default value is "relative." If you choose "absolute" positioning, you may specify where your block should begin with reference to the upper left corner of the browser window.


    You set absolute position by including TOP and LEFT selectors. They take values in points, pixels, centimeters, or inches. If you start experimenting with this technique, you'll quickly discover that the TOP specification can be tricky. If you can't be sure what font will be used (browsers differ, remember) then you can't be sure how many lines a particular block will occupy. Hence it's very difficult to decide where the block below it should begin. Lateral positioning is an easier matter.


    Width
    You may specify the width of any block element in the usual terms (pixels, points, inches, or centimeters) by including a WIDTH selector. It's too soon to use this feature in place of tables for right-margin constraint, but the day is coming.


    Margin
    You can likewise specify four margins for a block element: left, right, top, and bottom. Here's an example:


      DIV.mainText { margin-left: 2in; margin-top: 10pt; margin-right: 50px; margin-bottom: 10px }

    Borders
    You may also specify a visible border along any or all of the four margins of a block element. Borders are invisible (actually, sized to zero) by default. To make the border visible, set a non-zero width. For instance:


      DIV.mainText { border-left-width: 2px; border-color: #FF0000 }

    This stylesheet rule produces a 2-pixel vertical line along the left edge of any DIV styled as "mainText." This technique has a clear advantage over the old single-pixel graphic trick which we'd preivously used to approximate a vertical rule: the browser knows exactly how long to make the rule. With the graphic, you have to guess.


    A number of variations are available for borders, including "dashed," "dotted," "solid," "double," "groove," "ridge," and "outset." Give them a try.
5.3.3 · Special Effects

    Finally, block-element styling makes possible a number of gaudy, strange, and radical layout effects which you should probably try for experience's sake. Here's a demonstration page. The page is viewable in any recent browser, but the animation effects will only work in Internet Explorer. Netscape Navigator 4.x does not support the required HTML-4 features.

    Z-Index Layering
    Like the defunct Netscape layers concept, stylesheets let you design in three dimensions. By setting the z-index selector for a block element, you may place it in one of an infinite number of planes metaphorically stacked on the screen. The default z-index is 0, for the bottom level of the screen. Higher values take you "up" or "out"--though in fact they simply mean that when a higher-indexed element intersects one with a lower index, its pixels replace those on the lower plane.


    Color and Graphical Backgrounds
    Using the BACKGROUND-COLOR and BACKGROUND-IMAGE selectors, you can set solid-color or graphical backgrounds for block elements. Remember that a stylesheet selector is not the same thing as an HTML tag attribute. It's BACKGROUND-COLOR: #FFFFCC, not BGCOLOR="#FFFFCC". The usage for BACKGROUND-IMAGE is a bit more complicated, as in this example:


      P { BACKGROUND-IMAGE: url(images/bgImage.jpg) }

    That url([value]) usage is yet another departure from usual syntax patterns, but it's indeed required. Note there are no quotation marks around the URL value for the background image.


    Negative Margins and Spacing
    Here's where things get truly weird. You can assign negative numbers both to the various block-level MARGIN selectors and to the text-level LINE-HEIGHT selector. The result is text that may overlap content above, below, or on its margins. This effect does not require any alteration of z-index. It's probably the most striking thing you can do with stylesheets, but perhaps also the most pointless.


    Visibility
    For block-level and in-line elements (i.e., DIVs and SPANs, you may set a VISIBILITY selector to "show" or "hide." "Hide" leaves a blank space in your layout where the included content has been suppressed.


    Animation
    Strictly speaking this is not a stylesheet feature but rather something you can accomplish by connecting stylesheets with JavaScript, the subject of our next disquisition. All stylesheet rules, including those controlling position, are exposed to the scripting language in CSS-capable browsers. Thus we can use JavaScript to reset the position of a block element in some established sequence. You could use this technique to produce genuinely floating text.

END OF NOTES FOR WEEK 5


Return to Top of Page

Course and Materials ©1997 - 2000 by Stuart Moulthrop and Nancy Kaplan