Stuart Moulthrop
& Nancy Kaplan
University of Baltimore
School of Information Arts and Technologies ·
Revised 2008
Part 7: Cascading Stylesheets
Stylesheets represent a gigantic step forward for 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 -- they even offer three-dimensional layering and (with scripting support) possibilities for 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 with existing, legacy documents.
The World Wide Web Consortium (W3C) has published two specifications on stylesheets: Cascading Stylesheets Level 1 (CSS 1) and Cascading Stylesheets Level 2 (CSS 2). 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 go with CSS 2 here.
Most major Web browsers support CSS to a considerable extent. However, bothersome gaps and idiosyncracies still exist, most noticeably in Microsoft's Internet Explorer, the world's most popular browser.
For years, Web designers have dreamed of a software environment where all browsers -- Microsoft and open source, Windows and Macintosh, PC and appliance -- all do the work of the Web in exactly the same way. This dream has yet to become reality, and our situation has been complicated by the advent of Web-enabled smart phones, game platforms, car nav systems, and even weirder contexts for Internet computing.
Even as we close out the 21st century's first decade, CSS implementation remains a tricky business.So why bother with stylesheets at all? First, because you can do a number of powerful and important things with them that are entirely safe, at least across the leading browser families (Internet Explorer, Mozilla Firefox, Safari) and the major PC platforms (Windows, MacOS, UNIX/Linux). Second, because sooner or later the dream will come true, and CSS will be as stable and as universally supported as HTML.
If you want to do Web design, you need to know CSS.
- Since multiple instances of the same styling (a red headline, for example) have to be entered individually, it's very easy to make mistakes.
- 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.
- By adding a STYLE attribute to the initial tag of the container itself. This is called in-line styling.
- By adding a <STYLE></STYLE> container in the HEAD division of your document. This is called an internal stylesheet.
- 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.
Like the phrase Web page, the term stylesheet implies a certain archaism, since on the Internet there are no physical pages or sheets. In those dark ages Before Computing, primitive publishers kept a tangible object called a stylesheet, which was a page, or more typically a small booklet, listing house rules for handling aspects of editing and layout, such as when to use italic and when boldface, what to capitalize, how to identify people, and so forth. The New York Times' stylesheet famously requires celebrities to be referred to by a courtesy title and last name; so the pop-star-turned-actor Meat Loaf inevitably appears in those pages as Mr. Loaf.
When word processors came along, the old stylesheet concept was picked up as a metaphor, used to describe settings that could be applied to a document or its parts. All metaphors inherently gloss over distinctions, trying to persuade us that two fundamentally different things are somehow the same. As Neal Stephenson points out, this con game never really succeeds, and we inevitably encounter "metaphor shear," or failure of correspondence. No matter what we call it, new technology is never the same as the old ways.
In the case of software stylesheets, the shear occurs when we remember that computers are powerful tools for automation. An ink-stained editor in days of yore may have sometimes forgotten to put the title of a TV show in double quotes, or the name of a company in italics, but if a Web author remembers to mark up those phrases correctly, her CSS stylesheet will get the treatment right every time. Stylesheets afford highly effective control over the appearance of documents.
Before the introduction of CSS, many visual elements had to be laboriously coded, one by one. 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:
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 let you customize markup in very flexible ways.
You can specify rules for these elements in three ways:
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.
Stylesheet rules have this general form:
PROPERTY: VALUE
Notice that this syntax differs 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. This is another of Web design's less-than-charming inconsistencies; but it does remind us that stylesheets and HTML are different, despite their intimate relationship.
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. To cause all the text in a paragraph to be displayed in a 10-point sans-serif font, write the initial P or paragraph tag this way:
<P STYLE="font: 10pt sans-serif;">
We'd refer to the lone entry in this in-line stylesheet as the FONT rule. There are actually several ways to control font features. This one combines the specifications for size and family, using the generic identifier sans-serif to summon up whatever sans-serif type the browser recognizes as its default. The semicolon at the end of this rule is optional in this case, but as you'll see in later examples, it's a very good idea, since you might want to add other rules to your internal stylesheet, and a semicolon is required between any two rules. Finish every stylesheet rule with a semicolon.
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. It calls for that same 10-point sans serif font, but this time in medium-dark purple, and bold.
Internal stylesheets are often quite useful, but they are nearly as inefficient as the older method using the deprecated FONT tag, because each instance of the rule must be coded separately.
For better efficiency and accuracy, you might want to use a <STYLE></STYLE> container within which you specify all the rules for various HTML elements. This container is called an internal stylesheet.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. These symbols, sometimes also called or curly braces, are produced on most keyboards by pressing SHIFT and [ for the left bracket and SHIFT and ] for the right.
Don't confuse curly brackets with parentheses. (Alas, the older your eyes get, the harder this will become.) If you put parentheses in your stylesheets, the rules in question won't work.
Here's an example of an internal stylesheet:
<STYLE TYPE="text/css">
BODY {background-color: #FFFFFF;}
P {FONT: 12pt serif;}
A:LINK {color: #0000CC;}
A:VISITED {color: #990000;}
H1 {font: 14pt serif; color: #660000;}
H2 {font: 12pt serif; color: #666666;}
</STYLE>
This stylesheet decrees that its page shall have a white background, use a 12-point serif font for all its paragraphs, show cues for unvisited links in bright blue, cues for visited links in a darker red, use 14-point serif in medium-dark red for first-level headings, and use 12-point serif in medium gray for second-level headings.
Several details are worth noticing.
First, note that the initial STYLE tag contains a TYPE attribute specifying which variety of stylesheet the page uses. You must include this attribute, even though it will always have only one value, namely, text/css.
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 is another bothersome difference between CSS and HTML, so learn it carefully. Forgetting this detail can wreck your stylesheet if you get it wrong.
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 need only rewrite 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 bit less likely to develop Carpal Tunnel Syndrome.
One more detail concerning internal stylesheets: in some increasingly rare cases, people (or large organizations) use browsers that don't understand stylesheets. 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 can look 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 syntax -- though the blame falls on HTML this time, not CSS.
Here's an example of an internal stylesheet with hiding:
<STYLE TYPE="text/css">
<!--
P {FONT: 12pt serif}
BODY {background-color: #FFFFFF}
A:LINK {color: #0000CC}
A:VISITED {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.
Today it's probably not necessary to hide stylesheets in most cases. Use the technique only if you have a clearly defined user population that includes non-CSS browsers, or if someone complains about stylesheet code in viewed pages.
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 is 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:
BODY {background-color: #FFFFFF}
P {FONT: 12pt serif}
A:LINK {color: #0000CC}
A:VISITED {color: #990000}
That's all we need. External stylesheets are often very small documents indeed.
Once we've moved the stylesheet instructions to an external file, we can delete 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 page markup (that's the .htm file, not the .css file). Here's an example:
<LINK REL="stylesheet" TYPE="text/css" HREF="mystyle.css" />
The <LINK> element is another singleton, so in XHTML style, it requires a terminal space-and-slash.
LINK 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 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!
To make stylesheets as flexible and powerful as possible, CSS adds two tags and two attributes to HTML 4.
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. People commonly use the SPAN container, for instance, 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">
Each of these HTML tags will apply the indicated color change to the element in question.
As in the case of the CLASS attribute, you must take care to spell the ID value consistently at all times.
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 inclined to think 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.
Stylesheets are designed to permit graceful degradation. This term refers to a design principle in CSS 1 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 you open our page using a browser that doesn't support this CSS feature. 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.
7.4.1 · Font Styling
- 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 many 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. If you're not a graphic designer, or someone who loves one, you almost certainly won't have those fonts on your PC.
- You might want to think about Web font options in terms of several clusters:
- 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:
- 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 two levels of weighting: bold (or the numerical value 700), or normal (numerical value 500). 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. Specify colors as hexadecimal values preceded by a hashmark (#).
- 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:
- These style rules suppress the underlining on link anchors -- something many Web authors have wanted to do for a long, long time, though the technique represents a strong break from conventions and remains controversial.
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 (or some vendor) 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 allow 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.
| 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 |
BODY { font: 14pt/16pt Palatino, Times, serif; }
A:LINK { text-decoration: none; }
A:VISITED { text-decoration: none; }
- 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 any edge of the browser window.
Measurements can be given in points, pixels, centimeters, or inches.
Absolute positioning is enormously useful, since it permits you to specify exactly where items fall on your Web page. For example, if you write a DIV rule (or a rule for any other block-level element) where position is absolute and left is set to 10px, you can be assured that the left side of your DIV will appear 10 pixels from the left margin. Likewise, if you use the top selector, you can indicate with similar precision how far from the top of the browser window your DIV will appear.
Be very careful with the right and bottom selectors, however. They don't position the right or bottom edges of your DIV, but rather set the position of the upper left corner of your DIV with reference to the bottom or right edges of the browser window. Remember, folks, those edges of the window are MOVEABLE, which means that using absolute positioning on bottom or right does not fix your page element, but allows it to shift as the window size is reconfigured by the user. In other words, there's nothing especially absolute about this sort of positioning.
Use top and left for absolute positioning; or use static if you really want things fixed in place. - Width
- You may specify the width of any block element in the usual terms (pixels, points, inches, or centimeters) by including a WIDTH selector. As we've seen, this is a convenient way to specify line width, making your documents considerably more readable.
- Margin
- You can likewise specify four margins for a block element: left, right, top, and bottom. Here's an example:
- 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:
- This stylesheet rule produces a 2-pixel vertical line along all four edges of any DIV styled as "mainText."
- The syntax above is for the so-called shorthand version of the BORDER property. Note that it consists of three items, separated by spaces: the border style ("solid"), the width of the borders (2 pixels), and the color (bright red, or #FF0000).
- If you want a different visual style for your borders, you may substitute dashed, double, groove, ridge, inset, or outset.
- Be VERY careful not to use commas to separate your values, or to put a space between the width number and the "px" indication, as either of these mistakes will invalidate your border rule.
- Finally, note that you may set borders on any subset of the four edges of a block-level element. Suppose we wanted our border only on the left side:
- Or on just the left and bottom edges:
- Note that in this last case, we give the color as a separate property, to avoid typing it twice.
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 when you start experimenting with block styling, once all browsers support the technique, it will finish off tables as a foundation of Web layout; though you may still run into problems in some cases, even today.
DIV.mainText { margin-left: 2in; margin-top: 10pt; margin-right: 50px; margin-bottom: 10px }
DIV.mainText { border: 2px solid #FF0000; }
DIV.mainText { border-left: 2px solid #FF0000; }
DIV.mainText
{
border-color: #FF0000;
border-left: 2px solid;
border-bottom: 2px solid;
}
- 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 attribute in an HTML element. It's BACKGROUND-COLOR: #FFFFCC, not BGCOLOR="#FFFFCC". The usage for BACKGROUND-IMAGE is a bit more complicated, as in this example:
- 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 other lines (or graphics) above, below, or along its margins. This effect does not require any alteration of z-index. It's probably the most striking thing you can do with stylesheets -- and 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 using stylesheets in conjunction with JavaScript, the subject of the next part of these notes. All stylesheet rules, including those that control 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.
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.
P { BACKGROUND-IMAGE: url(images/bgImage.jpg); }
Now for a final word about browsers and their discontents. As we've said, CSS support is vastly better in 2008 than it was in 2000, though there are still small but troublesome differences in the way some browsers interpret CSS rules and stylesheet-enabled markup.
Some of these differences are fairly large. For example, if you attempt to set a fixed page width using the following rule...
BODY { WIDTH: 650; }
...you'll be disappointed, when checking your page in Microsoft Internet Explorer (MSIE). As late as Version 7, MSIE does not support width constraint through the BODY element.
However, we can substitute a rule that will work for both MSIE and the other popular family of browsers (circa 2008), those based on the open-source Mozilla (e.g., Firefox and Safari):
DIV.MAIN { WIDTH: 650; }
In this case, we assume that everything after the opening <HTML> tag lies within this container:
<DIV CLASS="MAIN"> </DIV>
Other differences between browser versions are less clear-cut, and may tend to emerge only as you begin to do complex and sophisticated things with stylesheets. Our best advice: proceed with caution, and test in multiple browsers on all three major computing platforms (Windows, MacOS, Linux).
Here's a case study that illustrates this more complex level of difficulty, and some ways to escape it. Below are two views of Stuart Moulthrop's home page in early 2008, using two popular browsers for Windows:
|
|
| 1: Mozilla Firefox | 2: Internet Explorer |
The images shown in the large, lefthand panel in each page view belong to a Flash movie that supplies a continuous montage of randomly-selected JPEGs. The difference between them is intentional, not problematic.
There is also an unintended difference between the two page views. Look closely at the lower right corner in each screenshot. Image 2 (Internet Explorer) contains white space, marked by the red arrow, that is absent in Image 1 (Mozilla Firefox). This artifact reveals CSS browser disparities in action.
The HTML code for this page includes an internal stylesheet, containing a DIV rule that governs the fourth rectangular division, to the right of the image block. The rule looks like this:
div.classLinks
{
font: 13px/28px Lucida Sans Console; color: #336699; font-weight: 500;
position: absolute; left: 500px; top: 350px; width: 300px; height: 118;
padding-left: 16; padding-top: 16; padding-bottom: 16;
background-color: #EEEEEE;
}
As you can see, Firefox and Explorer interpret this code in subtly but visibly different ways. In Firefox, the background color for the DIV (a very light gray) stretches to a point matching the bottom of the Flash element, 500 pixels from the top of the window. In Explorer, the background color of the DIV breaks off too early, leaving that awkward gap.
As it turns out, the problem stems from padding-top and padding-bottom. In Firefox, these selectors inject background-colored space above and below the lines of text in the DIV. In Explorer, they appear to have no effect beyond the last line of text. There would seem to be some difference in the way Firefox and Explorer define the limits of a block-level element when text and padding are involved.
As it turns out, there are many possible solutions for this browser problem. Here are three we've tried successfully:
- Insert blank lines using the <BR /> element, adjusting the height of the problematic DIV slightly. (This actually leaves the DIV one pixel short in Explorer, but it takes a sharp eye to notice.)
- Add a one-pixel spacer graphic, either transparent or keyed to the background color (#EEEEEE), with height set to a value that stretches the DIV in Explorer to just the right extent. The spacer graphic has no effect on the DIV in Firefox.
- Rewrite the four DIV rules, eliminating top and bottom padding; use <BR /> to insert blank lines as needed. This is the most satisfactory solution.
This case study tells us something about a particular quirk of CSS. However, padding is only one of several features whose browser support may vary. As we've said, you need to be ready to do this sort of designer-detective work whenever you deploy CSS to a wide variety of browsers and platforms. Get ready to test, and to tinker.
Index · Part 1 · Part 2 · Part 3 · Part 4 · Part 5 · Part 6 · Part 8 · Part 9 · Top
Course and Materials ©1997 - 2008 by Stuart Moulthrop
and Nancy Kaplan