# articles

title: DOM Scripting Your Way to Better Blockquotes
year: 2005
author: Jeremy Keith
author_slug: jeremykeith
published: 2005-12-05T00:00:00+00:00
url: https://24ways.org/2005/dom-scripting-your-way-to-better-blockquotes/
topic: code
contents:
Block quotes are great. I don’t mean they’re great for indenting content – that would be an abuse of the browser’s default styling. I mean they’re great for semantically marking up a chunk of text that is being quoted verbatim. They’re especially useful in blog posts. 

<blockquote>
     <p>Progressive Enhancement, as a label for a strategy for Web design, 
     was coined by Steven Champeon in a series of articles and presentations 
     for Webmonkey and the SxSW Interactive conference.</p>
 </blockquote>

Notice that you can’t just put the quoted text directly between the <blockquote> tags. In order for your markup to be valid, block quotes may only contain block-level elements such as paragraphs.

There is an optional cite attribute that you can place in the opening <blockquote> tag. This should contain a URL containing the original text you are quoting:

<blockquote cite="http://en.wikipedia.org/wiki/Progressive_Enhancement">
     <p>Progressive Enhancement, as a label for a strategy for Web design, 
     was coined by Steven Champeon in a series of articles and presentations 
     for Webmonkey and the SxSW Interactive conference.</p>
 </blockquote>

Great! Except… the default behavior in most browsers is to completely ignore the cite attribute. Even though it contains important and useful information, the URL in the cite attribute is hidden.

You could simply duplicate the information with a hyperlink at the end of the quoted text:

<blockquote cite="http://en.wikipedia.org/wiki/Progressive_Enhancement">
     <p>Progressive Enhancement, as a label for a strategy for Web design, 
     was coined by Steven Champeon in a series of articles and presentations 
     for Webmonkey and the SxSW Interactive conference.</p>
     <p class="attribution">
          <a href="http://en.wikipedia.org/wiki/Progressive_Enhancement">source</a>
     </p>
 </blockquote>

But somehow it feels wrong to have to write out the same URL twice every time you want to quote something. It could also get very tedious if you have a lot of quotes.

Well, “tedious” is no problem to a programming language, so why not use a sprinkling of DOM Scripting? Here’s a plan for generating an attribution link for every block quote with a cite attribute:


	Write a function called prepareBlockquotes.
	Begin by making sure the browser understands the methods you will be using.
	Get all the blockquote elements in the document.
	Start looping through each one.
	Get the value of the cite attribute.
	If the value is empty, continue on to the next iteration of the loop.
	Create a paragraph.
	Create a link.
	Give the paragraph a class of “attribution”.
	Give the link an href attribute with the value from the cite attribute.
	Place the text “source” inside the link.
	Place the link inside the paragraph.
	Place the paragraph inside the block quote.
	Close the for loop.
	Close the function.


Here’s how that translates to JavaScript:

function prepareBlockquotes() {
     if (!document.getElementsByTagName || !document.createElement || !document.appendChild) return;
     var quotes = document.getElementsByTagName("blockquote");
     for (var i=0; i<quotes.length; i++) {
          var source = quotes[i].getAttribute("cite");
          if (!source) continue;
          var para = document.createElement("p");
          var link = document.createElement("a");
          para.className = "attribution";
          link.setAttribute("href",source);
          link.appendChild(document.createTextNode("source"));
          para.appendChild(link);
          quotes[i].appendChild(para);
     }
 }


Now all you need to do is trigger that function when the document has loaded:

window.onload = prepareBlockquotes;

Better yet, use Simon Willison’s handy addLoadEvent function to queue this function up with any others you might want to execute when the page loads.

That’s it. All you need to do is save this function in a JavaScript file and reference that file from the head of your document using <script> tags.

You can style the attribution link using CSS. It might look good aligned to the right with a smaller font size.

If you’re looking for something to do to keep you busy this Christmas, I’m sure that this function could be greatly improved. Here are a few ideas to get you started:


	Should the text inside the generated link be the URL itself?
	If the block quote has a title attribute, how would you take its value and use it as the text inside the generated link?
	Should the attribution paragraph be placed outside the block quote? If so, how would you that (remember, there is an insertBefore method but no insertAfter)?
	Can you think of other instances of useful information that’s locked away inside attributes? Access keys? Abbreviations?


title: Tables with Style
year: 2005
author: Jonathan Snook
author_slug: jonathansnook
published: 2005-12-19T00:00:00+00:00
url: https://24ways.org/2005/tables-with-style/
topic: code
contents:
It might not seem like it but styling tabular data can be a lot of fun. From a semantic point of view, there are plenty of elements to tie some style into. You have cells, rows, row groups and, of course, the table element itself. Adding CSS to a paragraph just isn’t as exciting.

Where do I start?

First, if you have some tabular data (you know, like a spreadsheet with rows and columns) that you’d like to spiffy up, pop it into a table — it’s rightful place!

To add more semantics to your table — and coincidentally to add more hooks for CSS — break up your table into row groups. There are three types of row groups: the header (thead), the body (tbody) and the footer (tfoot). You can only have one header and one footer but you can have as many table bodies as is appropriate.

Sample table example

Inspiration

Table Striping

To improve scanning information within a table, a common technique is to style alternating rows. Also known as zebra tables. Whether you apply it using a class on every other row or turn to JavaScript to accomplish the task, a handy-dandy trick is to use a semi-transparent PNG as your background image. This is especially useful over patterned backgrounds. 

tbody tr.odd td {
     background:transparent url(background.png) repeat top left;
 }

 * html tbody tr.odd td {
     background:#C00;
     filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
          src='background.png', sizingMethod='scale');
 }

We turn off the default background and apply our PNG hack to have this work in Internet Explorer. 

Styling Columns

Did you know you could style a column? That’s right. You can add special column (col) or column group (colgroup) elements. With that you can add border or background styles to the column.

<table>
     <col id="ingredients">
     <col id="serve12">
     <col id="serve24">
 ...

Check out the example.

Fun with Backgrounds

Pop in a tiled background to give your table some character! Internet Explorer’s PNG hack unfortunately only works well when applied to a cell.

To figure out which background will appear over another, just remember the hierarchy:

 (bottom) Table → Column → Row Group → Row → Cell (top)

The Future is Bright

Once browser-makers start implementing CSS3, we’ll have more power at our disposal. Just with :first-child and :last-child, you can pull off a scalable version of our previous table with rounded corners and all — unfortunately, only Firefox manages to pull this one off successfully. And the selector the masses are clamouring for, nth-child, will make zebra tables easy as eggnog.


title: Introduction to Scriptaculous Effects
year: 2005
author: Michael Heilemann
author_slug: michaelheilemann
published: 2005-12-12T00:00:00+00:00
url: https://24ways.org/2005/introduction-to-scriptaculous-effects/
topic: code
contents:
Gather around kids, because this year, much like in that James Bond movie with Denise Richards, Christmas is coming early… in the shape of scrumptuous smooth javascript driven effects at your every whim.

Now what I’m going to do, is take things down a notch. Which is to say, you don’t need to know much beyond how to open a text file and edit it to follow this article. Personally, I for instance can’t code to save my life.

Well, strictly speaking, that’s not entirely true. If my life was on the line, and the code needed was really simple and I wasn’t under any time constraints, then yeah maybe I could hack my way out of it

But my point is this: I’m not a programmer in the traditional sense of the word. In fact, what I do best, is scrounge code off of other people, take it apart and then put it back together with duct tape, chewing gum and dumb blind luck.

No, don’t run! That happens to be a good thing in this case. You see, we’re going to be implementing some really snazzy effects (which are considerably more relevant than most people are willing to admit) on your site, and we’re going to do it with the aid of Thomas Fuchs’ amazing Script.aculo.us library. And it will be like stealing candy from a child.

What Are We Doing?

I’m going to show you the very basics of implementing the Script.aculo.us javascript library’s Combination Effects. These allow you to fade elements on your site in or out, slide them up and down and so on.

Why Use Effects at All?

Before get started though, let me just take a moment to explain how I came to see smooth transitions as something more than smoke and mirror-like effects included for with little more motive than to dazzle and make parents go ‘uuh, snazzy’.

Earlier this year, I had the good fortune of meeting the kind, gentle and quite knowledgable Matt Webb at a conference here in Copenhagen where we were both speaking (though I will be the first to admit my little talk on Open Source Design was vastly inferior to Matt’s talk). Matt held a talk called Fixing Broken Windows (based on the Broken Windows theory), which really made an impression on me, and which I have since then referred back to several times.

You can listen to it yourself, as it’s available from Archive.org. Though since Matt’s session uses many visual examples, you’ll have to rely on your imagination for some of the examples he runs through during it. Also, I think it looses audio for a few seconds every once in a while.

Anyway, one of the things Matt talked a lot about, was how our eyes are wired to react to movement. The world doesn’t flickr. It doesn’t disappear or suddenly change and force us to look for the change. Things move smoothly in the real world. They do not pop up.

How it Works

Once the necessary files have been included, you trigger an effect by pointing it at the ID of an element. Simple as that.

Implementing the Effects

So now you know why I believe these effects have a place in your site, and that’s half the battle. Because you see, actually getting these effects up and running, is deceptively simple.

First, go and download the latest version of the library (as of this writing, it’s version 1.5 rc5). Unzip itand open it up.

Now we’re going to bypass the instructions in the readme file. Script.aculo.us can do a bunch of quite advanced things, but all we really want from it is its effects. And by sidestepping the rest of the features, we can shave off roughly 80KB of unnecessary javascript, which is well worth it if you ask me.

As with Drew’s article on Easy Ajax with Prototype, script.aculo.us also uses the Prototype framework by  Sam Stephenson. But contrary to Drew’s article, you don’t have to download Prototype, as a version comes bundled with script.aculo.us (though feel free to upgrade to the latest version if you so please).

So in the unzipped folder, containing the script.aculo.us files and folder, go into ‘lib’ and grab the ‘prototype.js’ file. Move it to whereever you want to store the javascript files. Then fetch the ‘effects.js’ file from the ‘src’ folder and put it in the same place.

To make things even easier for you to get this up and running, I have prepared a small javascript snippet which does some checking to see what you’re trying to do. The script.aculo.us effects are all either ‘turn this off’ or ‘turn this on’. What this snippet does, is check to see what state the target currently has (is it on or off?) and then use the necessary effect.

You can either skip to the end and download the example code, or copy and paste this code into a file manually (I’ll refer to that file as combo.js):

Effect.OpenUp = function(element) {
     element = $(element);
     new Effect.BlindDown(element, arguments[1] || {});
 }

 Effect.CloseDown = function(element) {
     element = $(element);
     new Effect.BlindUp(element, arguments[1] || {});
 }

 Effect.Combo = function(element) {
     element = $(element);
     if(element.style.display == 'none') { 
          new Effect.OpenUp(element, arguments[1] || {}); 
     }else { 
          new Effect.CloseDown(element, arguments[1] || {}); 
     }
 }

Currently, this code uses the BlindUp and BlindDown code, which I personally like, but there’s nothing wrong with you changing the effect-type into one of the other effects available.

Now, include the three files in the header of your code, like so:

<script src="prototype.js" type="text/javascript"></script>
<script src="effects.js" type="text/javascript"></script>
<script src="combo.js" type="text/javascript"></script>

Now insert the element you want to use the effect on, like so:

<div id="content" style="display: none;">Lorem ipsum dolor sit amet.</div>

The above element will start out invisible, and when triggered will be revealed. If you want it to start visible, simply remove the style parameter.

And now for the trigger 

<a href="javascript:Effect.Combo('content');">Click Here</a>

And that, is pretty much it. Clicking the link should unfold the DIV targeted by the effect, in this case ‘content’.

Effect Options

Now, it gets a bit long-haired though. The documentation for script.aculo.us is next to non-existing, and because of that you’ll have to do some digging yourself to appreciate the full potentialof these effects.

First of all, what kind of effects are available? Well you can go to the demo page and check them out, or you can open the ‘effects.js’ file and have a look around, something I recommend doing regardlessly, to gain an overview of what exactly you’re dealing with.

If you dissect it for long enough, you can even distill some of the options available for the various effects. In the case of the BlindUp and BlindDown effect, which we’re using in our example (as triggered from combo.js), one of the things that would be interesting to play with would be the duration of the effect. If it’s too long, it will feel slow and unresponsive. Too fast and it will be imperceptible.

You set the options like so:

<a href="javascript:Effect.Combo('content', {duration: .2});">Click Here</a>

The change from the previous link being the inclusion of , {duration: .2}. In this case, I have lowered the duration to 0.2 second, to really make it feel snappy.

You can also go all-out and turn on all the bells and whistles of the Blind effect like so (slowed down to a duration of three seconds so you can see what’s going on):

<a href="javascript:Effect.Combo('content', {duration: 3, scaleX: true, scaleContent: true});">Click Here</a>

Conclusion

And that’s pretty much it. The rest is a matter of getting to know the rest of the effects and their options as well as finding out just when and where to use them. Remember the ancient Chinese saying: Less is more.

Download Example

I have prepared a very basic example, which you can download and use as a reference point.


title: Introducing UDASSS!
year: 2005
author: Dustin Diaz
author_slug: dustindiaz
published: 2005-12-18T00:00:00+00:00
url: https://24ways.org/2005/introducing-udasss/
topic: code
contents:
Okay. What’s that mean?

Unobtrusive Degradable Ajax Style Sheet Switcher!

Boy are you in for treat today ‘cause we’re gonna have a whole lotta Ajaxifida Unobtrucitosity CSS swappin’ Fun!

Okay are you really kidding? Nope. I’ve even impressed myself on this one. Unfortunately, I don’t have much time to tell you the ins and outs of what I actually did to get this to work. We’re talking JavaScript, CSS, PHP…Ajax. But don’t worry about that. I’ve always believed that a good A.P.I. is an invisible A.P.I… and this I felt I achieved. The only thing you need to know is how it works and what to do.

A Quick Introduction Anyway…

First of all, the idea is very simple. I wanted something just like what Paul Sowden put together in 
Alternative Style: Working With Alternate Style Sheets from Alistapart Magazine EXCEPT a few minor (not-so-minor actually) differences which I’ve listed briefly below:



	Allow users to switch styles without JavaScript enabled (degradable)
	Preventing the F.O.U.C. before the window ‘load’ when getting preferred styles
	Keep the JavaScript entirely off our markup (no onclick’s or onload’s)
	Make it very very easy to implement (ok, Paul did that too)


What I did to achieve this was used server-side cookies instead of JavaScript cookies. Hence, PHP. However this isn’t a “PHP style switcher” – which is where Ajax comes in. For the extreme technical folks, no, there is no xml involved here, or even a callback response. I only say Ajax because everyone knows what ‘it’ means. With that said, it’s the Ajax that sets the cookies ‘on the fly’. Got it? Awesome!

What you need

Luckily, I’ve done the work for you. It’s all packaged up in a nice zip file (at the end…keep reading for now) – so from here on out, 
just follow these instructions

As I’ve mentioned, one of the things we’ll be working with is PHP. So, first things first, open up a file called index and save it with a ‘.php’ extension.

Next, place the following text at the top of your document (even above your DOCTYPE)

<?php
 require_once('utils/style-switcher.php');
 // style sheet path[, media, title, bool(set as alternate)]
 $styleSheet = new AlternateStyles();
 $styleSheet->add('css/global.css','screen,projection'); // [Global Styles]
 $styleSheet->add('css/preferred.css','screen,projection','Wog Standard'); // [Preferred Styles]
 $styleSheet->add('css/alternate.css','screen,projection','Tiny Fonts',true); // [Alternate Styles]
 $styleSheet->add('css/alternate2.css','screen,projection','Big O Fonts',true); // // [Alternate Styles]
 $styleSheet->getPreferredStyles();
 ?>

The way this works is REALLY EASY. Pay attention closely.

Notice in the first line we’ve included our style-switcher.php file.

Next we instantiate a PHP class called AlternateStyles() which will allow us to configure our style sheets. 
So for kicks, let’s just call our object $styleSheet

As part of the AlternateStyles object, there lies a public method called add. So naturally with our $styleSheet object, we can call it to (da – da-da-da!) Add Style Sheets!

How the add() method works

The add method takes in a possible four arguments, only one is required. However, you’ll want to add some… since the whole point is working with alternate style sheets.

$path can simply be a uri, absolute, or relative path to your style sheet. $media adds a media attribute to your style sheets. $title gives a name to your style sheets (via title attribute).$alternate (which shows boolean) simply tells us that these are the alternate style sheets.

add() Tips

For all global style sheets (meaning the ones that will always be seen and will not be swapped out), simply use the add method as shown next to // [Global Styles].

To add preferred styles, do the same, but add a ‘title’.

To add the alternate styles, do the same as what we’ve done to add preferred styles, but add the extra boolean and set it to true.

Note following when adding style sheets


	Multiple global style sheets are allowed
	You can only have one preferred style sheet (That’s a browser rule)
	Feel free to add as many alternate style sheets as you like


Moving on

Simply add the following snippet to the <head> of your web document:

<script type="text/javascript" src="js/prototype.js"></script>
 <script type="text/javascript" src="js/common.js"></script>
 <script type="text/javascript" src="js/alternateStyles.js"></script>
 <?php
 $styleSheet->drop();
 ?>

Nothing much to explain here. Just use your copy & paste powers.

How to Switch Styles

Whether you knew it or not, this baby already has the built in ‘ubobtrusive’ functionality that lets you switch styles by the drop of any link with a class name of ‘altCss‘. Just drop them where ever you like in your document as follows:

<a class="altCss" href="index.php?css=Bog_Standard">Bog Standard</a>
 <a class="altCss" href="index.php?css=Really_Small_Fonts">Small Fonts</a>
 <a class="altCss" href="index.php?css=Large_Fonts">Large Fonts</a>

Take special note where the file is linking to. Yep. Just linking right back to the page we’re on. The only extra parameters we pass in is a variable called ‘css’ – and within that we append the names of our style sheets.

Also take very special note on the names of the style sheets have an under_score to take place of any spaces we might have.

Go ahead… play around and change the style sheet on the example page. Try disabling JavaScript and refreshing your browser. Still works!

Cool eh?

Well, I put this together in one night so it’s still a work in progress and very beta. If you’d like to hear more about it and its future development, be sure stop on by my site where I’ll definitely be maintaining it.

Download the beta anyway

Well this wouldn’t be fun if there was nothing to download. So we’re hooking you up so you don’t go home (or logoff) unhappy

 Download U.D.A.S.S.S | V0.8

Merry Christmas!

Thanks for listening and I hope U.D.A.S.S.S. has been well worth your time and will bring many years of Ajaxy Style Switchin’ Fun!

Many Blessings, Merry Christmas and have a great new year!


title: Debugging CSS with the DOM Inspector
year: 2005
author: Jon Hicks
author_slug: jonhicks
published: 2005-12-22T00:00:00+00:00
url: https://24ways.org/2005/debugging-css-with-the-dom-inspector/
topic: process
contents:
An Inspector Calls

The larger your site and your CSS becomes, the more likely that you will run into bizarre, inexplicable problems. Why does that heading have all that extra padding? Why is my text the wrong colour? Why does my navigation have a large moose dressed as Noel Coward on top of all the links? 

Perhaps you work in a collaborative environment, where developers and other designers are adding code? In which case, the likelihood of CSS strangeness is higher.

You need to debug. You need Firefox’s wise-guy know-it-all, the DOM Inspector. 

The DOM Inspector knows where everything is in your layout, and more importantly, what causes it to look the way it does. So without further ado, load up any css based site in your copy of Firefox (or Flock for that matter), and launch the DOM Inspector from the Tools menu.

The inspector uses two main panels – the left to show the DOM tree of the page, and the right to show you detail:



The Inspector will look at whatever site is in the front-most window or tab, but you can also use it without another window. Type in a URL at the top (A), press ‘Inspect’ (B) and a third panel appears at the bottom, with the browser view. I find this layout handier than looking at a window behind the DOM Inspector.

Step 1 – find your node!

Each element on your page – be it a HTML tag or a piece of text, is called a ‘node’ of the DOM tree. These nodes are all listed in the left hand panel, with any ID or CLASS attribute values next to them.  When you first look at a page, you won’t see all those yet. Nested HTML elements (such as a link inside a paragraph) have a reveal triangle next to their name, clicking this takes you one level further down. 

This can be fine for finding the node you want to look at, but there are easier ways. Say you have a complex rounded box technique that involves 6 nested DIVs? You’d soon get tired of clicking all those triangles to find the element you want to inspect. Click the top left icon © – “Find a node to inspect by clicking on it” and then select the area you want to inspect. Boom! All that drilling down the DOM tree has been done for you! Huzzah!

If you’re looking for an element that you know has an ID (such as <ul id="navigation">), or a specific HTML tag or attribute, click the binoculars icon (D) for “Finds a node to inspect by ID, tag or attribute” (You can also use Ctrl-F or Apple-F to do this if the DOM Inspector is the frontmost window) :



Type in the name and Bam! You’re there! Pressing F3 will take you to any other instances. Notice also, that when you click on a node in the inspector, it highlights where it is in the browser view with a flashing red border!

Now that we’ve found the troublesome node on the page, we can find out what’s up with it…

Step 2 – Debug that node!

Once the node is selected, we move over to the right hand panel. Choose ‘CSS Style Rules’ from the document menu (E), and all the CSS rules that apply to that node are revealed, in the order that they load:



You’ll notice that right at the top, there is a CSS file you might not recognise, with a file path beginning with “resource://”. This is the browsers default CSS, that creates the basic rendering. You can mostly ignore this, especially if use the star selector method of resetting default browser styles. 

Your style sheets come next. See how helpful it is? It even tells you the line number where to find the related CSS rules! If you use CSS shorthand, you’ll notice that the values are split up (e.g margin-left, margin-right etc.). 

Now that you can see all the style rules affecting that node, the rest is up to you! Happy debugging!


title: "Z's not dead baby, Z's not dead"
year: 2005
author: Andy Clarke
author_slug: andyclarke
published: 2005-12-16T00:00:00+00:00
url: https://24ways.org/2005/zs-not-dead-baby-zs-not-dead/
topic: design
contents:
While Mr. Moll and Mr. Budd have pipped me to the post with their predictions for 2006, I’m sure they won’t mind if I sneak in another. The use of positioning together with z-index will be one of next year’s hot techniques 

Both has been a little out of favour recently. For many, positioned layouts made way for the flexibility of floats. Developers I speak to often associate z-index with Dreamweaver’s layers feature. But in combination with alpha transparency support for PNG images in IE7 and full implementation of position property values, the stacking of elements with z-index is going to be big. I’m going to cover the basics of z-index and how it can be used to create designs which ‘break out of the box’.

No positioning? No Z!

Remember geometry? The x axis represents the horizontal, the y axis represents the vertical. The z axis, which is where we get the z-index, represents /depth/. Elements which are stacked using z-index are stacked from front to back and z-index is only applied to elements which have their position property set to relative or absolute. No positioning, no z-index. Z-index values can be either negative or positive and it is the element with the highest z-index value appears closest to the viewer, regardless of its order in the source. Furthermore, if more than one element are given the same z-index, the element which comes last in source order comes out top of the pile. 

Let’s take three <div>s.

<div id="one"></div>
 <div id="two"></div>
 <div id="three"></div>

 #one { 
     position: relative; 
     z-index: 3;
 }

 #two { 
     position: relative; 
     z-index: 1;
 }

 #three {
     position: relative; 
     z-index: 2;
 }



As you can see, the <div> with the z-index of 3 will appear closest, even though it comes before its siblings in the source order. As these three <div>s have no defined positioning context in the form of a positioned parent such as a <div>, their stacking order is defined from the root element <html>. Simple stuff, but these building blocks are the basis on which we can create interesting interfaces (particularly when used in combination with image replacement and transparent PNGs).

Brand building

Now let’s take three more basic elements, an <h1>, <blockquote> and <p>, all inside a branding <div> which acts a new positioning context. By enclosing them inside a positioned parent, we establish a new stacking order which is independent of either the root element or other positioning contexts on the page.

<div id="branding">
     <h1>Worrysome.com</h1>
     <blockquote><p>Don' worry 'bout a thing...</p></blockquote>
     <p>Take the weight of the world off your shoulders.</p>
 </div>

Applying a little positioning and z-index magic we can both set the position of these elements inside their positioning context and their stacking order. As we are going to use background images made from transparent PNGs, each element will allow another further down the stacking order to show through. This makes for some novel effects, particularly in liquid layouts.

(Ed: We’re using n below to represent whatever values you require for your specific design.) 

#branding {
    position: relative;
    width: n;
    height: n;
    background-image: url(n);
 }

 #branding>h1 {
    position: absolute;
    left: n;
    top: n;
    width: n;
    height: n;
    background-image: url(h1.png);
    text-indent: n;
 }

 #branding>blockquote {
    position: absolute;
    left: n;
    top: n;
    width: n;
    height: n;
    background-image: url(bq.png);
    text-indent: n;

 }

 #branding>p {
    position: absolute;
    right: n;
    top: n;
    width: n;
    height: n;
    background-image: url(p.png);
    text-indent: n;
 }

Next we can begin to see how the three elements build upon each other.


1. Elements outlined


2. Positioned elements overlayed to show context


3. Our final result

Multiple stacking orders

Not only can elements within a positioning context be given a z-index, but those positioning contexts themselves can also be stacked.


Two positioning contexts, each with their own stacking order

Interestingly each stacking order is independent of that of either the root element or its siblings and we can exploit this to make complex layouts from just a few semantic elements. This technique was used heavily on my recent redesign of Karova.com.

Dissecting part of Karova.com

First the XHTML. The default template markup used for the site places <div id="nav_main"> and <div id="content"> as siblings inside their container.

<div id="container">
     <div id="content">
          <h2></h2>
          <p></p>
     </div>
     <div id="nav_main"></div>
 </div>

By giving the navigation <div> a lower z-index than the content <div> we can ensure that the positioned content elements will always appear closest to the viewer, despite the fact that the navigation comes after the content in the source.

#content { 
     position: relative; 
     z-index: 2; 
 }

 #nav_main { 
     position: absolute; 
     z-index: 1; 
 }

Now applying absolute positioning with a negative top value to the <h2> and a higher z-index value than the following <p> ensures that the header sits not only on top of the navigation but also the styled paragraph which follows it.

h2 {
     position: absolute;
     z-index: 200;
     top: -n;
 }

 h2+p {
     position: absolute;
     z-index: 100;
     margin-top: -n;
     padding-top: n;
 }


Dissecting part of Karova.com

You can see the full effect in the wild on the Karova.com site.

Have a great holiday season!


title: Don't be eval()
year: 2005
author: Simon Willison
author_slug: simonwillison
published: 2005-12-07T00:00:00+00:00
url: https://24ways.org/2005/dont-be-eval/
topic: code
contents:
JavaScript is an interpreted language, and like so many of its peers it includes the all powerful eval() function. eval() takes a string and executes it as if it were regular JavaScript code. It’s incredibly powerful and incredibly easy to abuse in ways that make your code slower and harder to maintain. As a general rule, if you’re using eval() there’s probably something wrong with your design.

Common mistakes

Here’s the classic misuse of eval(). You have a JavaScript object, foo, and you want to access a property on it – but you don’t know the name of the property until runtime. Here’s how NOT to do it:

var property = 'bar';
var value = eval('foo.' + property);

Yes it will work, but every time that piece of code runs JavaScript will have to kick back in to interpreter mode, slowing down your app. It’s also dirt ugly.

Here’s the right way of doing the above:

var property = 'bar';
var value = foo[property];

In JavaScript, square brackets act as an alternative to lookups using a dot. The only difference is that square bracket syntax expects a string.

Security issues

In any programming language you should be extremely cautious of executing code from an untrusted source. The same is true for JavaScript – you should be extremely cautious of running eval() against any code that may have been tampered with – for example, strings taken from the page query string. Executing untrusted code can leave you vulnerable to cross-site scripting attacks.

What’s it good for?

Some programmers say that eval() is B.A.D. – Broken As Designed – and should be removed from the language. However, there are some places in which it can dramatically simplify your code. A great example is for use with XMLHttpRequest, a component of the set of tools more popularly known as Ajax. XMLHttpRequest lets you make a call back to the server from JavaScript without refreshing the whole page. A simple way of using this is to have the server return JavaScript code which is then passed to eval(). Here is a simple function for doing exactly that – it takes the URL to some JavaScript code (or a server-side script that produces JavaScript) and loads and executes that code using XMLHttpRequest and eval().

function evalRequest(url) {
     var xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState==4 && xmlhttp.status==200) {
               eval(xmlhttp.responseText);
          }
     }
     xmlhttp.open("GET", url, true);
     xmlhttp.send(null);
 }

If you want this to work with Internet Explorer you’ll need to include this compatibility patch.


title: Improving Form Accessibility with DOM Scripting
year: 2005
author: Ian Lloyd
author_slug: ianlloyd
published: 2005-12-03T00:00:00+00:00
url: https://24ways.org/2005/improving-form-accessibility-with-dom-scripting/
topic: code
contents:
The form label element is an incredibly useful little element – it lets you link the form field unquestionably with the descriptive label text that sits alongside or above it. This is a very useful feature for people using screen readers, but there are some problems with this element.

What happens if you have one piece of data that, for various reasons (validation, the way your data is collected/stored etc), needs to be collected using several form elements?

The classic example is date of birth – ideally, you’ll ask for the date of birth once but you may have three inputs, one each for day, month and year, that you also need to provide hints about the format required. The problem is that to be truly accessible you need to label each field. So you end up needing something to say “this is a date of birth”, “this is the day field”, “this is the month field” and “this is the day field”. Seems like overkill, doesn’t it? And it can uglify a form no end.

There are various ways that you can approach it (and I think I’ve seen them all). Some people omit the label and rely on the title attribute to help the user through; others put text in a label but make the text 1 pixel high and merging in to the background so that screen readers can still get that information. The most common method, though, is simply to set the label to not display at all using the CSS display:none property/value pairing (a technique which, for the time being, seems to work on most screen readers). But perhaps we can do more with this?

The technique I am suggesting as another alternative is as follows (here comes the pseudo-code):


	Start with a totally valid and accessible form
	Ensure that each form input has a label that is linked to its related form control
	Apply a class to any label that you don’t want to be visible (for example superfluous)


Then, through the magic of unobtrusive JavaScript/the DOM, manipulate the page as follows once the page has loaded:


	Find all the label elements that are marked as superfluous and hide them
	Find out what input element each of these label elements is related to
	Then apply a hint about formatting required for input (gleaned from the original, now-hidden label text) – add it to the form input as default text
	Finally, add in a behaviour that clears or selects the default text (as you choose)


So, here’s the theory put into practice – a date of birth, grouped using a fieldset, and with the behaviours added in using DOM, and here’s the JavaScript that does the heavy lifting. 

But why not just use display:none? As demonstrated at Juicy Studio, display:none seems to work quite well for hiding label elements. So why use a sledge hammer to crack a nut? In all honesty, this is something of an experiment, but consider the following:


	Using the DOM, you can add extra levels of help, potentially across a whole form – or even range of forms – without necessarily increasing your markup (it goes beyond simply hiding labels)
	Screen readers today may  identify a label that is set not to display, but they may not in the future – this might provide a way around
	By expanding this technique above, it might be possible to visually change the parent container that groups these items – in this case, a fieldset and legend, which are notoriously difficult to style consistently across different browsers – while still retaining the underlying semantic/logical structure


Well, it’s an idea to think about at least. How is it for you? How else might you use DOM scripting to improve the accessiblity or usability of your forms?


title: Swooshy Curly Quotes Without Images
year: 2005
author: Simon Collison
author_slug: simoncollison
published: 2005-12-21T00:00:00+00:00
url: https://24ways.org/2005/swooshy-curly-quotes-without-images/
topic: business
contents:
The problem

Take a quote and render it within blockquote tags, applying big, funky and stylish curly quotes both at the beginning and the end without using any images – at all.

The traditional way

Feint background images under the text, or an image in the markup housed in a little float. Often designers only use the opening curly quote as it’s just too difficult to float a closing one.

Why is the traditional way bad?

Well, for a start there are no actual curly quotes in the text (unless you’re doing some nifty image replacement). Thus with CSS disabled you’ll only have default blockquote styling to fall back on. Secondly, images don’t resize, so scaling text will have no affect on your graphic curlies.

The solution

Use really big text. Then it can be resized by the browser, resized using CSS, and even be restyled with a new font style if you fancy it. It’ll also make sense when CSS is unavailable.

The problem

Creating “Drop Caps” with CSS has been around for a while (Big Dan Cederholm discusses a neat solution in that first book of his), but drop caps are normal characters – the A to Z or 1 to 10 – and these can all be pulled into a set space and do not serve up a ton of whitespace, unlike punctuation characters.

Curly quotes aren’t like traditional characters. Like full stops, commas and hashes they float within the character space and leave lots of dead white space, making it bloody difficult to manipulate them with CSS. Styles generally fit around text, so cutting into that character is tricky indeed. Also, all that extra white space is going to push into the quote text and make it look pretty uneven. This grab highlights the actual character space:



See how this is emphasized when we add a normal alphabetical character within the span. This is what we’re dealing with here:



Then, there’s size. Call in a curly quote at less than 300% font-size and it ain’t gonna look very big. The white space it creates will be big enough, but the curlies will be way too small. We need more like 700% (as in this example) to make an impression, but that sure makes for a big character space.

Prepare the curlies

Firstly, remove the opening “ from the quote. Replace it with the opening curly quote character entity “. Then replace the closing “ with the entity reference for that, which is ”. Now at least the curlies will look nice and swooshy.

Add the hooks

Two reasons why we aren’t using :first-letter pseudo class to manipulate the curlies. Firstly, only CSS2-friendly browsers would get what we’re doing, and secondly we need to affect the last “letter” of our text also – the closing curly quote.

So, add a span around the opening curly, and a second span around the closing curly, giving complete control of the characters:

<blockquote><span class="bqstart">“</span>Speech marks. Curly quotes. That annoying thing cool people do with their fingers to emphasize a buzzword, shortly before you hit them.<span class="bqend">”</span></blockquote>

So far nothing will look any different, aside form the curlies looking a bit nicer. I know we’ve just added extra markup, but the benefits as far as accessibility are concerned are good enough for me, and of course there are no images to download.

The CSS

OK, easy stuff first. Our first rule .bqstart floats the span left, changes the color, and whacks the font-size up to an exuberant 700%. Our second rule .bqend does the same tricks aside from floating the curly to the right.

.bqstart {
     float: left;
     font-size: 700%;
     color: #FF0000;
 }

 .bqend {
     float: right;
     font-size: 700%;
     color: #FF0000;
 }

That gives us this, which is rubbish. I’ve highlighted the actual span area with outlines:



Note that the curlies don’t even fit inside the span! At this stage on IE 6 PC you won’t even see the quotes, as it only places focus on what it thinks is in the div. Also, the quote text is getting all spangled.

Fiddle with margin and padding

Think of that span outline box as a window, and that you need to position the curlies within that window in order to see them. By adding some small adjustments to the margin and padding it’s possible to position the curlies exactly where you want them, and remove the excess white space by defining a height:

.bqstart {
     float: left;
     height: 45px;
     margin-top: -20px;
     padding-top: 45px;
     margin-bottom: -50px;
     font-size: 700%;
     color: #FF0000;
 }

 .bqend {
     float: right;
     height: 25px;
     margin-top: 0px;
     padding-top: 45px;
     font-size: 700%;
     color: #FF0000;
 }

I wanted the blocks of my curlies to align with the quote text, whereas you may want them to dig in or stick out more. Be aware however that my positioning works for IE PC and Mac, Firefox and Safari. Too much tweaking seems to break the magic in various browsers at various times. Now things are fitting beautifully:

I must admit that the heights, margins and spacing don’t make a lot of sense if you analyze them. This was a real trial and error job. Get it working on Safari, and IE would fail. Sort IE, and Firefox would go weird.

Finished

The final thing looks ace, can be resized, looks cool without styles, and can be edited with CSS at any time. Here’s a real example (note that I’m specifying Lucida Grande and then Verdana for my curlies):

 “Speech marks. Curly quotes. That annoying thing cool people do with their fingers to emphasize a buzzword, shortly before you hit them.”

Browsers happy

As I said, too much tweaking of margins and padding can break the effect in some browsers. Even now, Firefox insists on dropping the closing curly by approximately 6 or 7 pixels, and if I adjust the padding for that, it’ll crush it into the text on Safari or IE. Weird. Still, as I close now it seems solid through resizing tests on Safari, Firefox, Camino, Opera and IE PC and Mac. Lovely.

It’s probably not perfect, but together we can beat the evil typographic limitations of the web and walk together towards a brighter, more aligned world. Merry Christmas.


title: Broader Border Corners
year: 2005
author: Patrick Griffiths
author_slug: patrickgriffiths
published: 2005-12-14T00:00:00+00:00
url: https://24ways.org/2005/broader-border-corners/
topic: design
contents:
A note from the editors:  Since this article was written the CSS border-radius property has become widely supported in browsers. It should be preferred to this image technique.
                
                
                      
                A quick and easy recipe for turning those single-pixel borders that the kids love so much into  into something a little less right-angled.

Here’s the principle: We have a box with a one-pixel wide border around it. Inside that box is another box that has a little rounded-corner background image sitting snugly in one of its corners. The inner-box is then nudged out a bit so that it’s actually sitting on top of the outer box. If it’s all done properly, that little background image can mask the hard right angle of the default border of the outer-box, giving the impression that it actually has a rounded corner.

Take An Image, Finely Chopped



Add A Sprinkle of Markup

<div id="content">
    <p>Lorem ipsum etc. etc. etc.</p>
</div>

Throw In A Dollop of CSS

#content { 
     border: 1px solid #c03;
}

#content p {
     background: url(corner.gif) top left no-repeat;
     position: relative;
     left: -1px;
     top: -1px;
     padding: 1em;
     margin: 0;
}

Bubblin’ Hot


	The content div has a one-pixel wide red border around it.
	The paragraph is given a single instance of the background image, created to look like a one-pixel wide arc.
	The paragraph is shunted outside of the box – back one pixel and up one pixel – so that it is sitting over the div’s border. The white area of the image covers up that part of the border’s corner, and the arc meets up with the top and left border.
	Because, in this example, we’re applying a background image to a paragraph, its top margin needs to be zeroed so that it starts at the top of its container.


Et voilà. Bon appétit.

Extra Toppings


	If you want to apply a curve to each one of the corners and you run out of meaningful markup to hook the background images on to, throw some spans or divs in the mix (there’s nothing wrong with this if that’s the effect you truly want – they don’t hurt anybody) or use some nifty DOM Scripting to put the scaffolding in for you.
	Note that if you’ve got more than one of these relative corners, you will need to compensate for the starting position of each box which is nested in an already nudged parent.
	You’re not limited to one pixel wide, rounded corners – the same principles apply to thicker borders, or corners with different shapes.


title: An Explanation of Ems
year: 2005
author: Richard Rutter
author_slug: richardrutter
published: 2005-12-02T00:00:00+00:00
url: https://24ways.org/2005/an-explanation-of-ems/
topic: design
contents:
Ems are so-called because they are thought to approximate the size of an uppercase letter M (and so are pronounced emm), although 1em is actually significantly larger than this. The typographer Robert Bringhurst describes the em thus:


	The em is a sliding measure. One em is a distance equal to the type size. In 6 point type, an em is 6 points; in 12 point type an em is 12 points and in 60 point type an em is 60 points. Thus a one em space is proportionately the same in any size.


To illustrate this principle in terms of CSS, consider these styles:

#box1 {
     font-size: 12px;
     width: 1em;
     height: 1em;
     border:1px solid black;
}

#box2 {
     font-size: 60px;
     width: 1em;
     height: 1em;
     border: 1px solid black;
}

These styles will render like:

 M

and

 M

Note that both boxes have a height and width of 1em but because they have different font sizes, one box is bigger than the other. Box 1 has a font-size of 12px so its width and height is also 12px; similarly the text of box 2 is set to 60px and so its width and height are also 60px.


title: Splintered Striper
year: 2005
author: Patrick Lauke
author_slug: patricklauke
published: 2005-12-15T00:00:00+00:00
url: https://24ways.org/2005/splintered-striper/
topic: code
contents:
Back in March 2004, David F. Miller demonstrated a little bit of DOM scripting magic in his A List Apart article Zebra Tables.

His script programmatically adds two alternating CSS background colours to table rows, making them more readable and visually pleasing, while saving the document author the tedious task of manually assigning the styling to large static data tables.

Although David’s original script performs its duty well, it is nonetheless very specific and limited in its application. It only:


	works on a single table, identified by its id, with at least a single tbody section
	assigns a background colour
	allows two colours for odd and even rows
	acts on data cells, rather than rows, and then only if they have no class or background colour already defined


Taking it further

In a recent project I found myself needing to apply a striped effect to a medium sized unordered list. Instead of simply modifying the Zebra Tables code for this particular case, I decided to completely recode the script to make it more generic.

Being more general purpose, the function in my splintered striper experiment is necessarily more complex. Where the original script only expected a single parameter (the id of the target table), the new function is called as follows:

striper('[parent element tag]','[parent element class or null]','[child element tag]','[comma separated list of classes]')

This new, fairly self-explanatory function:


	targets any type of parent element (and, if specified, only those with a certain class)
	assigns two or more classes (rather than just two background colours) to the child elements inside the parent
	preserves any existing classes already assigned to the child elements


See it in action

View the demonstration page for three usage examples. For simplicity’s sake, we’re making the calls to the striper function from the body’s onload attribute. In a real deployment situation, we would look at attaching a behaviour to the onload programmatically — just remember that, as we need to pass variables to the striper function, this would involve creating a wrapper function which would then be attached…something like:

function stripe() {
    striper('tbody','splintered','tr','odd,even');
}

window.onload=stripe;

A final thought

Just because the function is called striper does not mean that it’s limited to purely applying a striped look; as it’s more of a general purpose “alternating class assignment” script, you can achieve a whole variety of effects with it.


title: CSS Layout Starting Points
year: 2005
author: Rachel Andrew
author_slug: rachelandrew
published: 2005-12-04T00:00:00+00:00
url: https://24ways.org/2005/css-layout-starting-points/
topic: code
contents:
I build a lot of CSS layouts, some incredibly simple, others that cause sleepless nights and remind me of the torturous puzzle books that were given to me at Christmas by aunties concerned for my education. However, most of the time these layouts fit quite comfortably into one of a very few standard formats. For example:


	Liquid, multiple column with no footer
	Liquid, multiple column with footer
	Fixed width, centred


Rather than starting out with blank CSS and (X)HTML documents every time you need to build a layout, you can fairly quickly create a bunch of layout starting points, that will give you a solid basis for creating the rest of the design and mean that you don’t have to remember how a three column layout with a footer is best achieved every time you come across one! 

These starting points can be really basic, in fact that’s exactly what you want as the final design, the fonts, the colours and so on will be different every time. It’s just the main sections we want to be able to quickly get into place. For example, here is a basic starting point CSS and XHTML document for a fixed width, centred layout with a footer.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Fixed Width and Centred starting point document</title>
     <link rel="stylesheet" type="text/css" href="fixed-width-centred.css" />
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="wrapper">
     <div id="side">
          <div class="inner">
               <p>Sidebar content here</p>
          </div>
     </div>
     <div id="content">
          <div class="inner">
               <p>Your main content goes here.</p>
          </div>
     </div>
     <div id="footer">
          <div class="inner">
               <p>Ho Ho Ho!</p>
          </div>
     </div>
</div>
</body>
</html>

 body {
     text-align: center;
     min-width: 740px;
     padding: 0;
     margin: 0;
 }

 #wrapper {
     text-align: left;
     width: 740px;
     margin-left: auto;
     margin-right: auto;
     padding: 0;
 }

 #content {
     margin: 0 200px 0 0;
 }

 #content .inner {
     padding-top: 1px;
     margin: 0 10px 10px 10px;
 }

 #side {
     float: right;
     width: 180px;
     margin: 0;
 }

 #side .inner {
     padding-top: 1px;
     margin: 0 10px 10px 10px;
 }

 #footer {
     margin-top: 10px;
     clear: both;
 }

 #footer .inner {
     margin: 10px;
 }

9 times out of 10, after figuring out exactly what main elements I have in a layout, I can quickly grab the ‘one I prepared earlier’, mark-up the relevant sections within the ready-made divs, and from that point on, I only need to worry about the contents of those different areas. The actual layout is tried and tested, one that I know works well in different browsers and that is unlikely to throw me any nasty surprises later on. In addition, considering how the layout is going to work first prevents the problem of developing a layout, then realising you need to put a footer on it, and needing to redevelop the layout as the method you have chosen won’t work well with a footer.

While enjoying your mince pies and mulled wine during the ‘quiet time’ between Christmas and New Year, why not create some starting point layouts of your own? The css-discuss Wiki, CSS layouts section is a great place to find examples that you can try out and find your favourite method of creating the various layout types.


title: The Attribute Selector for Fun and (no ad) Profit
year: 2005
author: Andy Budd
author_slug: andybudd
published: 2005-12-11T00:00:00+00:00
url: https://24ways.org/2005/the-attribute-selector-for-fun-and-no-ad-profit/
topic: code
contents:
If I had a favourite CSS selector, it would undoubtedly be the attribute selector (Ed: You really need to get out more). For those of you not familiar with the attribute selector, it allows you to style an element based on the existence, value or partial value of a specific attribute.

At it’s very basic level you could use this selector to style an element with particular attribute, such as a title attribute.

<abbr title="Cascading Style Sheets">CSS</abbr>

In this example I’m going to make all <abbr> elements with a title attribute grey. I am also going to give them a dotted bottom border that changes to a solid border on hover. Finally, for that extra bit of feedback, I will change the cursor to a question mark on hover as well. 

abbr[title] {
     color: #666;
     border-bottom: 1px dotted #666;
 }

 abbr[title]:hover {
     border-bottom-style: solid;
     cursor: help;
 }

This provides a nice way to show your site users that <abbr> elements with title tags are special, as they contain extra, hidden information.

Most modern browsers such as Firefox, Safari and Opera support the attribute selector. Unfortunately Internet Explorer 6 and below does not support the attribute selector, but that shouldn’t stop you from adding nice usability embellishments to more modern browsers.

Internet Explorer 7 looks set to implement this CSS2.1 selector, so expect to see it become more common over the next few years.

Styling an element based on the existence of an attribute is all well and good, but it is still pretty limited. Where attribute selectors come into their own is their ability to target the value of an attribute. You can use this for a variety of interesting effects such as styling VoteLinks.

VoteWhats?

If you haven’t heard of VoteLinks, it is a microformat that allows people to show their approval or disapproval of a links destination by adding a pre-defined keyword to the rev attribute.

For instance, if you had a particularly bad meal at a restaurant, you could signify your dissaproval by adding a rev attribute with a value of vote-against.

<a href="http://www.mommacherri.co.uk/" rev="vote-against">Momma Cherri's</a>

You could then highlight these links by adding an image to the right of these links.

a[rev="vote-against"]{
     padding-right: 20px;
     background: url(images/vote-against.png) no-repeat right top;
}

This is a useful technique, but it will only highlight VoteLinks on sites you control. This is where user stylesheets come into effect. If you create a user stylesheet containing this rule, every site you visit that uses VoteLinks will receive your new style.

Cool huh?

However my absolute favourite use for attribute selectors is as a lightweight form of ad blocking. Most online adverts conform to industry-defined sizes. So if you wanted to block all banner-ad sized images, you could simply add this line of code to your user stylesheet.

img[width="468"][height="60"],
img[width="468px"][height="60px"]  {
     display: none !important;
}

To hide any banner-ad sized element, such as flash movies, applets or iFrames, simply apply the above rule to every element using the universal selector.

*[width="468"][height="60"], *[width="468px"][height="60px"]  {
     display: none !important;
}

Just bare in mind when using this technique that you may accidentally hide something that isn’t actually an advert; it just happens to be the same size.

The Interactive Advertising Bureau lists a number of common ad sizes. Using these dimensions, you can create stylesheet that blocks all the popular ad formats. Apply this as a user stylesheet and you never need to suffer another advert again.

Here’s wishing you a Merry, ad-free Christmas.


title: Transitional vs. Strict Markup
year: 2005
author: Roger Johansson
author_slug: rogerjohansson
published: 2005-12-13T00:00:00+00:00
url: https://24ways.org/2005/transitional-vs-strict-markup/
topic: code
contents:
When promoting web standards, standardistas often talk about XHTML as being more strict than HTML. In a sense it is, since it requires that all elements are properly closed and that attribute values are quoted. But there are two flavours of XHTML 1.0 (three if you count the Frameset DOCTYPE, which is outside the scope of this article), defined by the Transitional and Strict DOCTYPEs. And HTML 4.01 also comes in those flavours.

The names reveal what they are about: Transitional DOCTYPEs are meant for those making the transition from older markup to modern ways. Strict DOCTYPEs are actually the default – the way HTML 4.01 and XHTML 1.0 were constructed to be used.

A Transitional DOCTYPE may be used when you have a lot of legacy markup that cannot easily be converted to comply with a Strict DOCTYPE. But Strict is what you should be aiming for. It encourages, and in some cases enforces, the separation of structure and presentation, moving the presentational aspects from markup to CSS. From the HTML 4 Document Type Definition:


	This is HTML 4.01 Strict DTD, which excludes the presentation attributes and elements that W3C expects to phase out as support for style sheets matures. Authors should use the Strict DTD when possible, but may use the Transitional DTD when support for presentation attribute and elements is required.


An additional benefit of using a Strict DOCTYPE is that doing so will ensure that browsers use their strictest, most standards compliant rendering modes.

Tommy Olsson provides a good summary of the benefits of using Strict over Transitional in Ten questions for Tommy Olsson at Web Standards Group:


	In my opinion, using a Strict DTD, either HTML 4.01 Strict or XHTML 1.0 Strict, is far more important for the quality of the future web than whether or not there is an X in front of the name. The Strict DTD promotes a separation of structure and presentation, which makes a site so much easier to maintain.


For those looking to start using web standards and valid, semantic markup, it is important to understand the difference between Transitional and Strict DOCTYPEs. For complete listings of the differences between Transitional and Strict DOCTYPEs, see XHTML: Differences between Strict & Transitional, Comparison of Strict and Transitional XHTML, and XHTML1.0 Element Attributes by DTD.

Some of the differences are more likely than others to cause problems for developers moving from a Transitional DOCTYPE to a Strict one, and I’d like to mention a few of those.

Elements that are not allowed in Strict DOCTYPEs


	center
	font
	iframe
	strike
	u


Attributes not allowed in Strict DOCTYPEs


	align (allowed on elements related to tables: col, colgroup, tbody, td, tfoot, th, thead, and tr)
	language
	background
	bgcolor
	border (allowed on table)
	height (allowed on img and object)
	hspace
	name (allowed in HTML 4.01 Strict, not allowed on form and img in XHTML 1.0 Strict)
	noshade
	nowrap
	target
	text, link, vlink, and alink
	vspace
	width (allowed on img, object, table, col, and colgroup)


Content model differences

An element type’s content model describes what may be contained by an instance of the element type. The most important difference in content models between Transitional and Strict is that blockquote, body, and form elements may only contain block level elements. A few examples:


	text and images are not allowed immediately inside the body element, and need to be contained in a block level element like p or div
	input elements must not be direct descendants of a form element
	text in blockquote elements must be wrapped in a block level element like p or div


Go Strict and move all presentation to CSS

Something that can be helpful when doing the transition from Transitional to Strict DOCTYPEs is to focus on what each element of the page you are working on is instead of how you want it to look.

Worry about looks later and get the structure and semantics right first.


title: Naughty or Nice? CSS Background Images
year: 2005
author: Derek Featherstone
author_slug: derekfeatherstone
published: 2005-12-20T00:00:00+00:00
url: https://24ways.org/2005/naughty-or-nice-css-background-images/
topic: code
contents:
Web Standards based development involves many things – using semantically sound HTML to provide structure to our documents or web applications, using CSS for presentation and layout, using JavaScript responsibly, and of course, ensuring that all that we do is accessible and interoperable to as many people and user agents as we can.

This we understand to be good. 

And it is good. 

Except when we don’t clearly think through the full implications of using those techniques.

Which often happens when time is short and we need to get things done.

Here are some naughty examples of CSS background images with their nicer, more accessible counterparts.

Transaction related messages

I’m as guilty of this as others (or, perhaps, I’m the only one that has done this, in which case this can serve as my holiday season confessional)  We use lovely little icons to show status messages for a transaction to indicate if the action was successful, or was there a warning or error? For example:

“Your postal/zip code was not in the correct format.”

Notice that we place a nice little icon there, and use background colours and borders to convey a specific message: there was a problem that needs to be fixed. Notice that all of this visual information is now contained in the CSS rules for that div:

<div class="error">
     <p>Your postal/zip code was not in the correct format.</p>
 </div>

 div.error {
     background: #ffcccc url(../images/error_small.png) no-repeat 5px 4px;
     color: #900;
     border-top: 1px solid #c00;
     border-bottom: 1px solid #c00;
     padding: 0.25em 0.5em 0.25em 2.5em;
     font-weight: bold;
 }

Using this approach also makes it very easy to create a div.success and div.warning CSS rules meaning we have less to change in our HTML.

Nice, right?

No. Naughty. 

Visual design communicates

The CSS is being used to convey very specific information. The choice of icon, the choice of background colour and borders tell us visually that there is something wrong. 

With the icon as a background image – there is no way to specify any alt text for the icon, and significant meaning is lost. A screen reader user, for example, misses the fact that it is an “error.” 

The solution? Ask yourself: what is the bare minimum needed to indicate there was an error? Currently in the absence of CSS there will be no icon – which (I’m hoping you agree) is critical to communicating there was an error.

The icon should be considered content and not simply presentational.

The borders and background colour are certainly much less critical – they belong in the CSS.

Lets change the code to place the image directly in the HTML and using appropriate alt text to better communicate the meaning of the icon to all users:

<div class="bettererror">
     <img src="images/error_small.png" alt="Error" />
     <p>Your postal/zip code was not in the correct format.</p>
 </div>

 div.bettererror {
     background-color: #ffcccc;
     color: #900;
     border-top: 1px solid #c00;
     border-bottom: 1px solid #c00;
     padding: 0.25em 0.5em 0.25em 2.5em;
     font-weight: bold;
     position: relative;
     min-height: 1.25em;
 }

 div.bettererror img {
     display: block;
     position: absolute;
     left: 0.25em;
     top: 0.25em;
     padding: 0;
     margin: 0;
 }

 div.bettererror p {
     position: absolute;
     left: 2.5em;
     padding: 0;
     margin: 0;
 }

Compare these two examples of transactional messages

Status of a Record

This example is pretty straightforward. Consider the following: a real estate listing on a web site. There are three “states” for a listing: new, normal, and sold. Here’s how they look:

Example of a New Listing

Example of A Sold Listing

If we (forgive the pun) blindly apply the “use a CSS background image” technique we clearly run into problems with the new and sold images – they actually contain content with no way to specify an alternative when placed in the CSS.

In this case of the “new” image, we can use the same strategy as we used in the first example (the transaction result). The “new” image should be considered content and is placed in the HTML as part of the <h2>...</h2> that identifies the listing.

However when considering the “sold” listing, there are less changes to be made to keep the same look by leaving the “SOLD” image as a background image and providing the equivalent information elsewhere in the listing – namely, right in the heading.

For those that can’t see the background image, the status is communicated clearly and right away. A screen reader user that is navigating by heading or viewing a listing will know right away that a particular property is sold.

Of note here is that in both cases (new and sold) placing the status near the beginning of the record helps with a zoom layout as well.

Better Example of A Sold Listing

Summary

Remember: in the holiday season, its what you give that counts!! Using CSS background images is easy and saves time for you but think of the children. And everyone else for that matter… 

CSS background images should only be used for presentational images, not for those that contain content (unless that content is already represented and readily available elsewhere).


title: Practical Microformats with hCard
year: 2005
author: Drew McLellan
author_slug: drewmclellan
published: 2005-12-06T00:00:00+00:00
url: https://24ways.org/2005/practical-microformats-with-hcard/
topic: code
contents:
You’ve probably heard about microformats over the last few months. You may have even read the easily digestible introduction at Digital Web Magazine, but perhaps you’ve not found time to actually implement much yet. That’s understandable, as it can sometimes be difficult to see exactly what you’re adding by applying a microformat to a page. Sure, you’re semantically enhancing the information you’re marking up, and the Semantic Web is a great idea and all, but what benefit is it right now, today? 

Well, the answer to that question is simple: you’re adding lots of information that can be and is being used on the web here and now. The big ongoing battle amongst the big web companies if one of territory over information. Everyone’s grasping for as much data as possible. Some of that information many of us are cautious to give away, but a lot of is happy to be freely available. Of the data you’re giving away, it makes sense to give it as much meaning as possible, thus enabling anyone from your friends and family to the giant search company down the road to make the most of it.

Ok, enough of the waffle, let’s get working.

Introducing hCard

You may have come across hCard. It’s a microformat for describing contact information (or really address book information) from within your HTML. It’s based on the vCard format, which is the format the contacts/address book program on your computer uses. All the usual fields are available – name, address, town, website, email, you name it.

If you’re running Firefox and Greasemonkey (or if you can, just to try this out), install this user script. What it does is look for instances of the hCard microformat in a page, and then add in a link to pass any hCards it finds to a web service which will convert it to a vCard. Take a look at the About the author box at the bottom of this article. It’s a hCard, so you should be able to click the icon the user script inserts and add me to your Outlook contacts or OS X Address Book with just a click.

So microformats are useful after all. Free microformats all round!

Implementing hCard

This is the really easy bit. All the hCard microformat is, is a bunch of predefined class names that you apply to the markup you’ve probably already got around your contact information. Let’s take the example of the About the author box from this article. Here’s how the markup looks without hCard:

<div class="bio">
     <h3>About the author</h3>
     <p>Drew McLellan is a web developer, author and no-good swindler from 
     just outside London, England. At the 
     <a href="http://www.webstandards.org/">Web Standards Project</a> he works 
     on press, strategy and tools. Drew keeps a 
     <a href="http://www.allinthehead.com/">personal weblog</a> covering web 
     development issues and themes.</p>
</div>

This is a really simple example because there’s only two key bits of address book information here:- my name and my website address. Let’s push it a little and say that the Web Standards Project is the organisation I work for – that gives us Name, Company and URL.

To kick off an hCard, you need a containing object with a class of vcard. The div I already have with a class of bio is perfect for this – all it needs to do is contain the rest of the contact information.

The next thing to identify is my name. hCard uses a class of fn (meaning Full Name) to identify a name. As is this case there’s no element surrounding my name, we can just use a span. These changes give us:

<div class="bio vcard">
     <h3>About the author</h3>
     <p><span class="fn">Drew McLellan</span> is a web developer...

The two remaining items are my URL and the organisation I belong to. The class names designated for those are url and org respectively. As both of those items are links in this case, I can apply the classes to those links. So here’s the finished hCard.

<div class="bio vcard">
     <h3>About the author</h3>
     <p><span class="fn">Drew McLellan</span> is a web developer, author and 
     no-good swindler from just outside London, England. 
     At the <a class="org" href="http://www.webstandards.org/">Web Standards Project</a> 
     he works on press, strategy and tools. Drew keeps a 
     <a class="url" href="http://www.allinthehead.com/">personal weblog</a> covering web 
     development issues and themes.</p>
</div>

OK, that was easy. By just applying a few easy class names to the HTML I was already publishing, I’ve implemented an hCard that right now anyone with Greasemonkey can click to add to their address book, that Google and Yahoo! and whoever else can index and work out important things like which websites are associated with my name if they so choose (and boy, will they so choose), and in the future who knows what. In terms of effort, practically nil.

Where next?

So that was a trivial example, but to be honest it doesn’t really get much more complex even with the most pernickety permutations. Because hCard is based on vCard (a mature and well thought-out standard), it’s all tried and tested. Here’s some good next steps.


	Play with the hCard Creator
	Take a deep breath and read the spec
	Start implementing hCard as you go on your own projects – it takes very little time


hCard is just one of an ever-increasing number of microformats. If this tickled your fancy, I suggest subscribing to the microformats site in your RSS reader to keep in touch with new developments.

What’s the take-away?

The take-away is this. They may sound like just more Web 2-point-HoHoHo hype, but microformats are a well thought-out, and easy to implement way of adding greater depth to the information you publish online. They have some nice benefits right away – certainly at geek-level – but in the longer term they become much more significant. We’ve been at this long enough to know that the web has a long, long memory and that what you publish today will likely be around for years. But putting the extra depth of meaning into your documents now you can help guard that they’ll continue to be useful in the future, and not just a bunch of flat ASCII.


