Yelotofu

Yelotofu ~ “In building standards compliant sites we are creating a better Web for the future.”

Targeting Safari 3

Found this CSS hack for Safari 3 today which can be handy from time to time:

 
@media screen and (-webkit-min-device-pixel-ratio:0){
    /* Safari 3 specific styles go here */
}
 

Most of the time if something looks good in Firefox 2 there's a 99% chance it will in Safari 3 too. So use this hack sparingly and only when absolutely necessary.

Oops, stripped too early!

I'm sure no one noticed but Yelotofu got naked for about 1 hour today because the CSS Naked Day plugin I had installed last year thought today was the day to strip off!

Well, this years' CSS Naked Day will be held on the 9th of April. This time Yelotofu will be getting butt naked for 48 hours!

Come on, Join in the fun!

CSS Diagnostics

What is CSS diagnostics? It's a method of applying styles to elements in your markup to catch standards compliance issues. A way of ensuring you don't leave any serious accessibility holes and a visual deterrent for web authors editing pages with diagnostics switched on.

Here are some resources I found useful in understanding the practicality of this pioneering concept:

The only problem with CSS diagnostics is that it relies on the CSS capabilities of a browser to find issues. So if your browser is less capable, meaning it doesn't understand the diagnostic styles, then it negates the idea totally. Mind you, we're at a point in CSS support whereby this is becoming less and less a problem but it is still a potential one.

Luckily CSS diagnostics isn't the be all and end all of diagnostics. We have the king of diagnostics — Firebug, Web Inspector for Safari and more recently the much improved IE8 Developer Toolbar. And if you're looking for a cross-browser solution there's always the brilliant XRAY. Oh, how spoilt we all are!

7 Ways To Write “Better” HTML

BarCamp came and went, I'm still experiencing the aftermath; making new connections on Facebook daily and checking the BarCamp Hong Kong 2007 Flickr Group constantly for new photos! Anyway, It's about time I catalogued my talk before it's too late! The original presentation slide show was created with S5 (a standards compliant and accessible slide show system). Feel free to run that side-by-side whilst reading this article as it's segmented to match the presentation. Warning: This post is pretty long! I hope I don't bore you.

Introduction

HTML is an age old topic which I'm sure you're already very familiar with and has been talked about zillions of times. However, I think there is room for such a topic given the apparent lack of knowledge of Web Standards among the general web populous in Hong Kong. Hopefully by the end of this post I will of at least spark some interest in writing better, and by better I mean, semantically rich and standards compliant HTML.

1. Use a DOCTYPE declaration

If you're using a HTML editor to create HTML then chances are a DOCTYPE is added to your pages automatically, so generally we tend to not take much notice of it. There are several DOCTYPE flavours however. A Strict DTD is used when you want clean markup free from presentational elements. A Transitional DTD when you want to add some presentational features to your HTML. There is also a Frameset DTD used for laying out pages with framesets, however you should never need this one; you shouldn't be using frames!

It's always good practice to add a DOCTYPE to the top of each and every HTML page because it enables what we call DOCTYPE switching. There are essentially two basic modes “quirks mode” and “standards mode”. In quirks mode the browser will behave like old browsers of the late 90's and standards mode will follow the W3C recommendations. A browser will work in quirks mode if there is no DOCTYPE to be found. Internet Explorer will even switch to quirks mode if the first line of your HTML has no DOCTYPE, a blank line counts too! The most famous effect of switching to “standards mode” is the change in the Box model and problems with the old IE model. There is also a third "almost-standards mode" which is available in Mozilla and Firefox browsers. The almost-standards mode is activated by a transitional DTD and doesn't follow the W3C cell height specification. So next time you create a new HTML file give yourself a second to think about the DOCTYPE you're using.

OK, which DOCTYPE should you use? It depends on the situation. Jeffrey Zelman wrote a great article to help Fix Your Site With the Right DOCTYPE and Henri Sivonen wrote in detail about Activating the right layout mode using the DOCTYPE. Generally, if you're starting out on a new project with a blank canvas I'd recommend using a strict DTD which helps to facilitate adherence to standards, obviously make the effort to validate as well to ensure compliance!

2. Don't Abuse the Good!

HTML is very simple to learn. In fact it's so easy anyone could pretty much pick it up, as well as be proficient, in about 3 days. For that reason it's a “language” that's prone to exploitation as most learn from bad examples. There are only a handful of tags and only 30 are frequently used. The most exploited of them all are the table and blockquote elements.

The biggest step to writing better markup is to throw away your tables, but not all of them, only those being used for layout purposes. Think of tables as “data tables” and you're on the right track. This is something that could prove difficult for those used to creating tables for layout. I myself started building websites in the era of table dominance and found it difficult to switch at first. I know how difficult it could be to unlearn bad habits, but believe me you will benefit immensely and it will open many doors. I would never go back to tables for layout now that I've mastered CSS layouts. Still not convinced? Pop open a new browser and read this interestingly animated article by Merikallio & Pratt on Why tables for layout is stupid.

By definition a blockquote is a BLOCK of QUOTEs, hence a blockquote should always start with a p, but blockquote elements are often mis-used as indenter's. Example of the write way to use a blockquote:

<p><cite>Eric Meyer</cite> wrote:</p>
<blockquote cite="http://meyerweb.com/eric/thoughts/2005/03/11/social-protocols/">
<p>What's so interesting to me is that the guys who
decided to\focus on the positive went out and did something;
those who want to mix in the negative seem to have
nothing to offer except complaints.</p>
</blockquote>
<p>An excellent contrast between those who want to
build new things and those who want to tear them down.</p>

Example taken from The Elements of Meaningful XHTML by Tantek Çelik

3. Use the Right Tag for the Right Job

Like a carpenter won't use his screwdriver to hammer a nail into a piece of wood so the p element should not be used to break a line! However WYSIWYG editors tend to exploit the p element by using it as a line-break rather than a wrapper for a paragraph of text. Don't do this in your hand crafted master piece!

There are 6 heading levels (h1, h2, h3, h4, h5, h6) – h1 being most important, and h6 least important. Headings are used to section a page into logical chunks.

The em element is used to give a word or sentence emphasis, it does not mean italic text even though that's what it looks like in a browser. Again WYSIWYG editors often exploit this fact, by producing an em element when users click on the I icon.

The strong element is also in a similar situation being mistaken as bold text. The strong element should only be used when a stronger emphasis than the em element is needed. And em's can be nested to give further emphasis.

Lastly there is ul, ol, and dl. Only use the ol when you have a list of items in which changing the order of an item will change the meaning of that list. A ul is for general lists and dl elements could be used for definitions or key-value pairs.

4. Avoid Bed and BReakfast markup

<b>ed and <br>eakfast markup is a term coined by Tantek Çelik to describe the way people mis-use b and br elements for headings and paragraphs respectively. B & BR is bad practice because it adds presentational markup and takes away what could have been an opportunity for more semantic meaning in a piece of text. See presentation slide 18-20 for example.

5. Headings are important

As previously mentioned there are six heading levels. Where you start the first h1 element is crucial to the overall structure and accessibility of a page. It's usually best to have one h1 only and that's usually the site name. However, if you have a page of article listings (like a blog home page) then you might decide that the title of each article is far more important than the site name, hence it's also possible to use h1 elements as the title of each article. In which case you will end up with multiple h1 elements. It's also important not to skip levels in the page structure as it will mess up page quality. Sectioning a page into meaningful headings will also aid some screen readers and browsers to quickly navigate the page content by jumping from heading to heading. Finally headings are good for SEO, Accessibility and much better than div or span elements. A word of advice is to use headings where ever it makes sense and keep meaningless markup to a minimum.

6. Don't forget ALT text!

Bad: <img src=”car_photo.jpg”>
Acceptable: <img src=”car_photo.jpg” alt=””>
Good: <img src=”car_photo.jpg” alt=”my dream car”>

It is a basic requirement of the WAI Level 1 guidelines that all img elements should have an accompanying ALT text. Now there may not seem any point there but what if your image is a link to another section of the site? An image link for example:

Bad example:

<a href="portfolio.html"><img src="screenshot.jpg" /></a>

Users who navigate your site with images turned off or use screen readers will not be able to make sense of the above. Worse still are images used as the main navigation without an ALT text for people to follow. An ALT text should be descriptive and give the user an idea of the context of the image. Sometimes it means explaining visual aspects; sometimes it's a case of spelling out embedded copy. Make an effort to remove any decorative images from HTML and place inside CSS. If a decorative image cannot be avoided then either use blank ALT text or better still, let the user know it's a decorative image and place it at the very bottom of your HTML source output.

7. Use CSS for presentation

It's hard not to talk about CSS when talking about HTML. CSS complements HTML so well. I will only go briefly into CSS here but I'd recommend research into this topic if you're really interested in writing “better” HTML. A good book to grab hold of is CSS Mastery by Andy Budd. Another good way to learn more about CSS is to view the CSS source of other people, see how they are doing things, learn from the experts! Blueprint and YUI have built CSS frameworks and is a good starting point for improving your own CSS skills. I don't recommend using a framework per se but use it as a learning tool! Blueprint's typography CSS is especially good. Investigate, learn and integrate.

Though CSS is used for presentation class names should not be based on presentational cues. Use semantic-class-names at all times. Example:

BAD: redtext, boldtext, smallIcon and leftnav.
GOOD: note, important, attachments and subnav

+7 Ways It Will Benefit Your Online Business

OK, so all this talk about writing "better" HTML seems like a waste of time. Why concentrate on this when you could work on more important aspects of your site? Such as a better design, cool Ajax features, and marketing! Well HTML is important and is one of the most important ones to get right! Here are 7 reasons why writing better HTML will benefit your business. (It's not just for the sake of ego and beauty or keeping your geeks busy!)

  • Your pages will load faster

    Because you removed much of the clutter of TABLE and spacer GIFs your pages will load faster.

  • Lower your hosting costs

    Due to the reduced mark-up the total weight of your web page will be lower hence lowering payload, bandwidth and ultimately hosting and data transfer costs

  • Lower the cost of a redesign

    Your website no longer contains presentational mark-up hence it's more receptive to change. A change of design mostly consists of graphic and CSS modifications. The underlying HTML structure doesn't have to change much and in some cases it doesn't have to change at all!

  • Maintain visual consistency

    Again, all presentational aspects have been moved to CSS so the write once use everywhere approach is used. In that CSS templates are created and applied across the board, hence it's much easier to keep branding and design consistency.

  • Get better search engine results

    Reduced clutter means your content can dominate the page and moved higher to the top of the HTML source output. Hence it is more favourable with search engines. Plus, by providing a document outline via headings you are giving a page more keyword relevance. Therefore, cleverly thought out headings that include relevant keywords will improve search engine rankings.

  • More accessible to all viewers

    As we've now removed all clutter and provided section headings, alt text, and link titles pages become more accessible instantaneously. Not only to humans but to search engines alike. Remember, Google is blind! Google does not understand JavaScript (yet), it relies on headings to determine relevance, it reads the alt text to understand image content and it follows links of interest.

  • It's a winner!

    The Web Standards war has been won. So it's here to stay whether you like it or not and will only grow in force as time goes by. If you don't take note of it now your business will lose out in the long run and you will be playing catch-up. So get on the Web Standards bandwagon now! And write better HTML!

Further reading:

Form Layout using Definition Lists

As you may well know, using a definition list (DL) to layout forms with labels and fields side-by-side could be a bit flaky at times; forms don't seem to scale nicely and numerous layout problems could occur with dynamic content. Typical pitfalls are situations where a label or field takes up two or more lines or a BR tag in the DD column breaking things. After some playing around and testing I finally came to an elegant and bulletproof solution.

dl {clear:both;}
dt {float:left; clear:left;}
dd {overflow:hidden; clear:right; height:1%;}

The above CSS snippet will float the DT tag to the left. Then the DD tag will snug nicely to the right of it. The clever thing is if the content within the DD tag spans more than one line it will be indented by the width of the DT column. Try it!

However, our form looks a bit messy at the moment as the width of the DT column is determined by its content. Hence form fields and labels don't align properly. To resolve this all we do is add a fixed width to the DT column.

dt {width:10em;}

Now, we're faced with yet another problem. If the contents of the DT tag spans more than two lines it will occupy the space of the DT tag below it, pushing all the other DTs down causing misalignment of the DT - DD rows. To resolve this we add an additional empty DD tag for clearing, which we place below the actual DD containing content.

dd.x-form-clear {clear:both;}

To complete this post here's an example form layout using definition lists.

Building an Unobtrusive, Accessible and Standards Compliant Numeric Stepper

First off, if you're looking for a quick solution feel free to skip directly to the download link at the end of this article. For those who are interested in the intricate details please read on...

What is a Numeric Stepper?

Well, the answer is simple. It's a form control and looks like this...

A Numeric Stepper

It has an intuitive look that does not require much brain power to figure out how to use. The name itself suggests it's restricted to numeric values. The plus and minus signs indicate an ability to step up or down. The steps must be of equal size maintaining consistency. The great thing about Numeric Steppers is users can either enter a value or use the plus and minus buttons to arrive at a target value.

Flash UI developers have long since enjoyed this form control. In fact, it wasn't until Flash came out with their UI components before I even heard of a Numeric Stepper!

What is it used for?

Numeric Steppers are not always useful. They are designed to solve a specific UI problem. Scenarios where Numeric Steppers would be of use are:

  • In shopping baskets; so users can quickly change quantities.
  • When choosing number of years experience in a skill or profession. Some forms may contain many such questions so Numeric Steppers will facilitate quick mouse action.
  • When choosing number of children or family members. There is no logical upper limit to this question so a drop down is out of the question. A simple input box will serve well but means the user will have to leave their mouse; find the correct keyboard key; then enter a value. With a Numeric Stepper they'd simply click the mouse button a few times in succession to obtain their target value.

These are just but a handful of scenarios. I'm sure there are much more good usage examples out there.

Pity they didn't think of it earlier?

There is no equivalent HTML form control for the Numeric Stepper. I guess when forms were conceived there was no urgent need for them or the concept just didn't exist back then. The rise of Ajax and rich UI interfaces have boosted the industry's appetite for greater interactivity in forms. The chances of a Numeric Stepper playing more useful roles in forms is much greater now.

With that thought in mind we start our journey on building our own...

Building the Numeric Stepper

With help from JavaScript and a few basic form controls we can easily create our very own Numeric Stepper. The ingredients are: a standard text input, two buttons, a container to wrap it all up; and JavaScript to handle the associated events.

The HTML

<span class="numeric-stepper">
<input name="ns_textbox" size="2" type="text" />
  <button type="submit" name="ns_button_1" value="1" class="plus">+</button>
  <button type="submit" name="ns_button_2" value="-1" class="minus">-</button>
</span>

Example 1: The HTML structure

You may notice submit buttons are used rather than "button" buttons. This is so if JavaScript is not available the Numeric Stepper will degrade gracefully. Clicking on the buttons will cause a form submit hence allowing developers to take event handling to the backend. I won't go into details of how to do the backend as it's out of the scope of this article.

I must stress that form submit on button click is NOT what we are after for JavaScript enabled browsers. Using unobtrusive Javascript we want to increment/decrement the input box value by a step size on button click. We also want the JavaScript to restrict it to numerical values only; and apply an upper and lower limit. The code is too much to present here so I'm only going to show the important parts:

The JavaScript

var NumericStepper = {
  register : function(name, minValue, maxValue, stepSize){
    ...
    textbox.onkeypress = function(e){
      if(window.event){
        keynum = e.keyCode;
      } else if(e.which){
        keynum = e.which;
      }
      keychar = String.fromCharCode(keynum);
      numcheck = /[0-9-]/;
      if (keynum==8)
        return true;
      else
        return numcheck.test(keychar);
    };
    ...
  }
  ...
  ,stepper:function(textbox, val){
    if (textbox == undefined)
      return false;
    if (val == undefined || isNaN(val))
      val = 1;
      if (textbox.value == undefined || textbox.value == '' || isNaN(textbox.value))
        textbox.value = 0;
      textbox.value = parseInt(textbox.value) + parseInt(val);
      if (parseInt(textbox.value) &lt; NumericStepper.minValue)
        textbox.value = NumericStepper.minValue;
      if (parseInt(textbox.value) &gt;NumericStepper. maxValue)
        textbox.value = NumericStepper.maxValue;
    }
  ...
}

Example 2: Numeric Stepper; no clothes

Our Numeric Stepper is nearly complete. It doesn't look much like one at the moment; but with a little help from CSS we can give our Numeric Stepper some clothes.

The CSS

.numeric-stepper {
  width:3.425em;
  height:1.6em;
  display:block;
  position:relative;
  overflow:hidden;
  border:1px solid #555;
}
 
.numeric-stepper input {
  width:75%;
  height:100%;
  float:left;
  text-align:center;
  vertical-align:center;
  font-size:125%;
  border:none;
  background:none;
}
 
.numeric-stepper button {
  width:25%;
  height:50%;
  font-size:0.5em;
  padding:0;
  margin:0;
  z-index:100;
  text-align:center;
  position:absolute;
  right:0;
}
.numeric-stepper button.minus {
  bottom:0;
}

The final product: Unobtrusive, Accessible and Standards compliant.

The idea of clothes/skins is fascinating for our Numeric Stepper as it allows us to change its look and feel with some CSS trickery. Take a look at this graphical example.

The Source Code

You can get hold of version 0.1 of the Numeric Stepper source code by following this download link.

I have tested it on FF2, Opera 8.5, IE5.5, IE6, IE7 and Safari. Works well but the buttons look a little weird in Safari though still usable.

Bugfixes, code enhancements, feature requests & improvements are welcome. Please do let me know if you use this code though and if you find it at all useful!

Update: version 0.1.2 adds some accessibility enhancements.

Proof that IE6 is crap

I have more than often had to fire-up IE6 out from the "un-loved" software repository to get kicked right back in the face with weird CSS bugs. I believe those reading this must be aware of at least one CSS quirk in the IE6 browser. For example, the PNG Alpha Transparency bug, fixed by Microsoft's proprietary AlphaImageLoader or the strangely named Peek-a-boo bug requiring a position relative on the buggy floated element. These are just two out of what must be endless lists of problems. At the top of the annoyance list though must be the IE6 Background Flicker bug. When viewing a site using background images as hover/un-hover states IE6 will re-load a fresh image every event change on that element. The effect is a brief flicker on hover. By the way, this happens locally too but it's too quick for the naked eye to notice. Firefox, Safari, Opera, Flock and probably any other browser on the planet does not have this problem! Worst still the fix is so simple, you wonder why the problem existed in the first place.To fix the IE6 Background Flicker bug use the document.execCommand method. In your CSS file add the following:

html {
  filter:expression(
    document.execCommand("BackgroundImageCache", false, true)
  );
}

Yes, it's that simple! I found this fix at Ajaxian.com. You'd probably want to implement some sort of sniffer to wrap around this fix. I used an IE conditional which serves the purpose nicely. For more solutions refer to the Ajaxian link above. Believe it or not, before finding this fix I looked into image caching, server cache control, CSS trickery and smashing the keyboard!

Lastly, apologies if anyone is offended by the title of this post. I'm venting my frustration after wasting many hours fixing perfectly valid CSS to cater for silly IE6 bugs.

CSS Drop Down Menus

Recently, I've been having fun creating pure* CSS drop down menus for Lemon, see: example 1, example 2 . These things really get the brain juices going. These menus are fully Accessible and supports IE6, IE7, Firefox, Flock, Opera, Netscape 8 and Safari. I'm going to keep at improving the code to make it re-usable, re-skinable with more browser support!I will release this to the open source community when I feel it's ready to withstand scrutiny. It also depends on whether there's enough interest! Time will tell...

*IE6 browsers require JS intervention due to the lack of support for the CSS :hover pseudo-class on LI elements.