Archives
 
 
 
  Special
 
 
 
  About Us
 
 
 

Newsletter
Free E-mail Newsletter from BYTE.com

 
    
           
Visit the home page Browse the four-year online archive Download platform-neutral CPU/FPU benchmarks Find information for advertisers, authors, vendors, subscribers Request free information on products written about or advertised in BYTE Submit a press release, or scan recent announcements Talk with BYTE's staff and readers about products and technologies

ArticlesCascading Style Sheets


November 1997 / Web Project / Cascading Style Sheets

CSS will change the way Web designers and developers work. Here are some practical ways to learn and apply it.

Jon Udell

HTML purists say that the markup language, like SGML, expresses only the structure of documents. The browser -- not the author -- controls presentation, because only the browser knows best how to adapt content to exploit the capabilities and workaround constraints of its host system.

The reality of HTML is quite different, of course. There's intense pressure on publishers and software developers alike to control the look of their Web pages. We do this with bastard HTML tags, such as <FONT> and <CENTER>; with nested tables; and with nonbreaking spaces a nd invisible GIFs. By resorting to these hacks we achieve the necessary effects, but we also trade away universal access and easy maintenance.

CSS purists say that style sheets influence, but do not absolutely control, the presentation of documents. Author and reader can share influence, and the rendered page is a negotiated compromise. Non-CSS browsers can fall back to vanilla HTML, which remains the skeleton of any CSS-enhanced page.

The reality of CSS will likely diverge from the ideal, just as HTML has, for the same reasons, involving the same tradeoffs. With HTML, I'm always looking for the sweet spot -- the right balance of purity and pragmatism. Because that's a moving target, I continually adjust my pages and applications to track it. So with CSS.

What's the sweet spot for CSS right now, with immature support for style sheets in the 4.0 browsers from Netscape and Microsoft? What's it likely to be in eight months when CSS implementations are more complete, widespread, and reliable? Here are some answers, and some educated guesses.

CASE 1: An HTML/JavaScript/CSS Slide Show

When I give presentations nowadays, I use Web pages for slides. Modifying style across a set of slides always used to be a problem. If you used embedded HTML tags, such as <FONT>, you had to do a global search-and-replace across multiple files to change the look of a presentation consistently.

CSS neatly solves this problem. Now when I create a slide show, I clone pages from a template that includes a reference to a style sheet. The style sheet contains a series of directives, like this:

body { font-family: arial; }
h1 { font-size: 24pt;
       font-weight: bold; }

In this example, CSS defines the default font, and the size of <H1> headers, for every slide. Technically, CSS merely influences these matters, subject to the counter-influence of the user's style pref erences. In practice, that won't happen much until browsers support user style sheets and users learn to apply them.

There's a lot to say about these rules. The font-family , for example, might better be requested like this: Verdana, Arial, Helvetica, MS Sans Serif. Proceeding from specific to generic, this list equips the browser to use the author's preferred fonts when available (in order of preference) and authorizes the browser to fall back on a generic sans serif font if necessary.

Likewise, the font-size might better be expressed in one of these ways:

h1 { font-size: larger; }
h1 { font-size: 200%; }
h1 { font-size: x-large; }

Almost everything in CSS can be expressed using abstract terminology that's relative ( larger, 200% ) or absolute ( x-large ). Relative mode makes an element vary in proportion to other elements; absolute mode makes an element independent of others.

Why x-large rather than 24pt ? Because 0.33 inch (24 points divided by 72 points per inch) might be too small to say "extra large" on a high-res workstation, but overwhelmingly large on a PDA. x-large requests an absolute size, but one that can still be interpreted in a device-appropriate way.

The h1 headers use the body's font-family , although the h1 rule says nothing about font-family . Why? h1 inherits from body . If you're familiar with style sheets in conventional word processors, it may take a while for you to get the hang of this. CSS inheritance is a powerful mechanism. To exploit it requires a mind-set that owes more to object-oriented programming than to desktop publishing. The challenges -- and the rewards -- are similar.

A Dose of Practicality

When I added a table to one of my slides, I ran into a snag. The table didn't inherit my font-family request. Why not? Navigator 4.0's CSS support is very shaky; inheritance across table boundaries is one of man y things that just don't work. Microsoft Internet Explorer (MSIE) 4.0 (currently in beta 2) works properly in this regard, and in general it's far better than Navigator 4.0. It's a second-generation effort for Microsoft, which committed early to CSS with support in MSIE 3.0. Netscape resisted for too long, and it now finds itself in catch-up mode.

What to do? Because I'm the only one giving my presentations, I could use MSIE 4.0 and just ignore Communicator's CSS flaws. But I don't want to just show my presentation; I want to put it on the Web so that others can view it. Requiring MSIE 4.0 won't do. I'd rather build something that works with both browsers. It's frustrating to look for workarounds, but that's the lot of the Web author. Better my frustration than the reader's. In this regard, CSS is going to be a déjà vu experience.

CSS is enormously flexible, so there are lots of different ways to work around problems. To switch my table cells to an alternate font-family , I first tried this:

td { font-family: monospace }

But the preamble that my JavaScript code inserts into every slide builds another table containing navigational icons and a title. The rule shown above sets every table cell in monospace type; I want only certain tables to be handled that way.

CSS offers a variety of solutions. Here's one: You can make a new class out of any element by adding a class attribute to its HTML tag, like this: <td class=BodyTableCell> . Then you can address the set of elements so tagged, as follows:

  td.BodyTableCell { font-family: monospace }

This works. But it's stupid to add a class attribute to every cell. You might as well just say <td><font face=courier> -- just the sort of brute-force redundancy that CSS is supposed to abolish. Here's another idea:

<div class=BodyTable>
<table>...</table>

In CSS you can use two new HTML elements -- DIV an d SPAN -- as metatags that group and classify other elements. DIV defines a block element (anything bounded by line breaks); SPAN marks an in-line element. In this case, the class attribute on DIV defines a class called BodyTable . Now a single wild-card rule, like this:

.BodyTable { font-family: monospace }

can influence all the td s contained within instances of that class.

Was this the solution? Nope. It requires inheritance, which, as you'll remember, doesn't work properly with tables in Navigator 4.0. Fortunately, CSS has another trick up its sleeve. You can select sets of elements not only with attributes ( td , BodyTable ) but also with contextual patterns of attributes. Here is what finally worked:

div th, div td { font-family: courier; }

This says: "Apply courier to TH and TD elements, but only those contained within a DIV." I wrapped the tables that I wanted to match this rule in a <div class=BodyTable>... </div> tag.

Note that it would have been enough simply to say <div> -- the new class BodyTable isn't contributing anything to this solution. I left BodyTable in, though. It won't cause problems with CSS or non-CSS browsers. And it's extra information that might come in handy. Someday I may want to select only the elements that match BodyTable , rather than a more general set that matches div th , div td . Or, in a non-CSS context, I might want to use a Perl script to extract and catalog or rearrange all the tables of that type.

Even if you have no immediate need to influence presentation with style sheets, there are compelling reasons to adopt the CSS method of classifying content. Class attributes do more than lay the foundation for stylistic control of your pages. They can also provide new hooks for managing your content. Document collections are text databases. Class attributes are selectors that operate on these databases. CSS uses these selectors, but other applications can, too. The value of your text databases grows in proportion to the number and specificity of the selectors you can apply to it.

CASE 2: BYTE Home-Page Redesign

A recent redesign of our home page gave me the chance to try out the design and layout capabilities of CSS-enhanced HTML. Our requirements included a variety of static and dynamic elements of various shapes and sizes, all with fixed locations. There's only one way to do this in straight HTML. You wrap everything in tables. CSS offers two other approaches: floating elements and absolute positioning.

Because I'd have to deploy to non-CSS browsers, I started with a table-based approach. Even in this context, CSS can be useful. If you classify elements, you can rapidly evaluate a series of alternate treatments. The family, size, weight, and color of fonts; the alignment, indentation, line spacing, and margins of text; and a host of other stylistic variables are easily twiddled.

Depe nding on your inheritance scheme, you can adjust these things for the whole document tree or for selected branches. Once you settle on a design, you can translate your CSS rules down to the per-element tags required by straight HTML.

The next thing to try was floating elements. HTML authors use the FLOAT attribute of the IMG tag to force images left or right and to flow text around them. CSS generalizes the float property. Any block element -- image, list, DIV -- can float. In theory, you can use this technique to build a page that has a 2-D look but that adapts gracefully to narrow displays. In practice, CSS can do this effectively only in simple cases ( see the screen ).

The inventors of CSS are talking about extensions that will make it a full-blown layout system, but in its current form it isn't one, nor does it pretend to be. Still, the float property is powerful. You can, for example, apply it to a group of elements wrapped in a DIV tag. The effect varies according to the other properties of the DIV (e.g., absolute or relative width, left or right alignment), the properties of the other elements in line with the DIV, and the properties of the DIV's container. It's worth spending some time to sort out all these interactions.

Finally, I tried a version of the home page that uses absolute positioning. With this CSS extension, which is supported in both 4.0 browsers, you can place any element at a precise pixel offset from the top-left origin of the page. It's an all-or-none method because elements positioned in this way will never flow, and any other elements that are allowed to flow are liable to overlap the fixed ones. However, normal flow still occurs inside fixed elements.

Using this technique, I tiled the surface of the page with my major elements. The result was pleasing because, unlike a conventional table treatment, the CSS version didn't have to align elements on a grid. This freedom costs something, of course. Tables can stretch if you express their widths in percentages. A page whose elements stand in fixed relation to the origin cannot stretch.

I like this last version best, and I plan to translate it into straight HTML for deployment. Here's hoping that widespread adoption of CSS will make that ugly procedure unnecessary when our next site redesign rolls around.


TOOLWATCH


ColorPicker.................free

Robert Hess
Internet: 
http://www.microsoft.com/workshop/design/safety/colorpick-f.htm


Here's a handy reference to the "safety palette": the 216 colors that look about the same on all browsers and all platforms. If you're experimenting with color using CSS, bookmark this page.


BOOKNOTE


Cascading Style Sheets: Designing for the Web
..........$29.95

by Håkon Wium Lie and Bert Bos
Addison Wesley Longman
IBSN 0-201-41998-X
Internet: 
http://www.awl.com/css/


This definitive guide, written by the inventors of CSS, covers typography, layout, color, element classification and selection, and inheritance. One invaluable chapter shows how to reinterpret basic HTML page designs using CSS.


Anatomy of a Web Slide Show

Here's a simple JavaScript technique for controlling a Web-based
slide show. 


1. Clone blank slides from this template:


<head>
<link rel=stylesheet type="text/css" href="style.htm">
<script src="script.js"></script>
</
head><body>

Note: Navigator can source the script from an external file, as shown
here; MSIE (including version 4.0, beta 2) cannot.

The style sheet standardizes the look of the presentation; the shared
script controls navigation and presents numbered titles. 


2. Store the filenames and titles of the slides in a JavaScript array.


var docs = new Array (
 'overview.htm|BYTE Site overview',
 'archive.htm|BYTE Site: archive' }


3. Treat the array like a Perl or Java hash (a table of name/value


pairs).


function itemFromDocs (type,i) {
if ( i < 0) i = 0;
if ( i > docs.length-1) i = docs.length-1;
var str = docs[i];
if (type == 'url')       // get the URL
   return str.substring(0,str.lastIndexOf('|')); }
else                    // get the title
return str.substring(str.lastIndexOf('|')+1,str.length);
}


4. Remember the current document.


var href = document.location;
var curr = href.substring
   (h
ref.lastIndexOf('/')+1,href.length);


5. Compute the hyperlink for the next or previous document.


function getLink(which) {
for (var i = 0; i <= docs.length-1; i++) {
  if (curr == itemFromDocs('url',i)) {
     if (which == 'next') { // next slide
       link = itemFromDocs('url',i+1);
       gif = "next.gif"; }
     else {                 // previous slide
       link = itemFromDocs('url',i-1);
       gif = "prev.gif"; } } }
return '<a href=' + base+link + '><img src=' + gif +
   '></a>'; }


6. Emit a page header that includes the slide's title, plus Previous


and Next links.


document.write('<table width=100%><tr><td> + 
   getLink('prev') + '</td><td>' + showTitle() +
      '</td><td>' + getLink('next') + '</td></tr></table>');



Cascading Style Sheets: Designing for the Web

photo_link (49 Kbytes)


HTML + CSS + JavaScript = Dynamic HTML

screen_link (48 Kbytes)

Here's a lightweight approach to active content. In this demo, every list's title (i.e., one, two, three) is wired to a JavaScript function that toggles the CSS display property of the corresponding list. When you set the display property to "none," the browser hides the list a nd reflows the document to reclaim its space.


Jon Udell is BYTE's executive editor for new media. You can reach him by sending e-mail to jon_u@dev5.byte.com .

Up to the Web Project section contentsSearchSend a comment on this articleSubscribe to BYTE or BYTE on CD-ROM  
Flexible C++
Matthew Wilson
My approach to software engineering is far more pragmatic than it is theoretical--and no language better exemplifies this than C++.

more...

BYTE Digest

BYTE Digest editors every month analyze and evaluate the best articles from Information Week, EE Times, Dr. Dobb's Journal, Network Computing, Sys Admin, and dozens of other CMP publications—bringing you critical news and information about wireless communication, computer security, software development, embedded systems, and more!

Find out more

BYTE.com Store

BYTE CD-ROM
NOW, on one CD-ROM, you can instantly access more than 8 years of BYTE.
 
The Best of BYTE Volume 1: Programming Languages
The Best of BYTE
Volume 1: Programming Languages
In this issue of Best of BYTE, we bring together some of the leading programming language designers and implementors...

Copyright © 2005 CMP Media LLC, Privacy Policy, Your California Privacy rights, Terms of Service
Site comments: webmaster@byte.com
SDMG Web Sites: BYTE.com, C/C++ Users Journal, Dr. Dobb's Journal, MSDN Magazine, New Architect, SD Expo, SD Magazine, Sys Admin, The Perl Journal, UnixReview.com, Windows Developer Network