HTML5 Doctor » Oli Studholme http://html5doctor.com helping you implement HTML5 today Wed, 02 Mar 2016 08:08:54 +0000 en-US hourly 1 Comparing and contrasting ins, del, and s https://stevefaulkner.github.io/html5doctored/ins-del-s/ https://stevefaulkner.github.io/html5doctored/ins-del-s/#comments Tue, 20 Aug 2013 13:30:34 +0000 http://html5doctor.com/?p=5086 Since the mists of HTML 2 we’ve been able to semantically indicate added or removed information using the elements <ins> and <del> respectively. While seemingly simple on the surface these elements have hidden depths. I’ll also compare and contrast <del> with <s>, recently out of font style rehab and back in HTML5. Let’s start with <ins> and <del>…

]]>
Since the mists of HTML 2 we’ve been able to semantically indicate added or removed information using the elements <ins> and <del> respectively. While seemingly simple on the surface these elements have hidden depths. I’ll also compare and contrast <del> with <s>, recently out of font style rehab and back in HTML5. Let’s start with <ins> and <del>…

Using ins and del

These two elements have very simple definitions:

The ins and del elements represent edits to the document.

The ins element represents an addition to the document.

The del element represents a removal from the document.

— WHATWG HTML Living Specification

So what kind of edits are we talking about? You could use these elements to:

  • Record changes to an official document, such as meeting minutes or a law
  • Note changes to an article — in addition to journalistic corrections, this helps to maintain editorial integrity and avoid charges of “rewriting history”
  • Indicate the changes between two versions of a document (a diff), for example to indicate editorial changes
  • Indicate a signficant addition or removal of content that people accessing the document would benefit from knowing about

While some uses require recording changes exactly, when you’re just highlighting a change I think minor editing for clarity or grammar is fine — as long as the meaning isn’t changed. If necessary consider adding a note describing the change, perhaps in a footer or aside. Also, keep in mind that it rapidly becomes impractical (or impossible) to mark up all edits — only use these elements when there’s a benefit in explicitly indicating them.

“Implied paragraph bondaries”

<ins> and <del> are unusual in that they can contain contain phrasing content or flow content (in HTML 4-speak, they can be inline or block-level). For example, here’s an inserted paragraph that contains a phrasing content deletion:

<!-- block-level ins -->
<ins>
  <!-- inline del -->
  <p>Today I saw <del>flying monkeys</del> the doctor. The prognosis was not good.</p>
</ins>

Note that browsers will style these elements as inline by default, and you’ll need to include display: block; if you want to apply block-level styling. We’ll cover this later in the article.

The spec warns that the elements “should not cross implied paragraph boundaries”. These occur when there’s phrasing content (= text or inline elements) without a block-level element wrapper as a sibling of a block-level element. For example:

<div>
  <p>This text is in a block-level element.</p>
  <!-- implied paragraph boundary here -->
  Oh snap! Someone forgot the paragraph tags!
</div>

Of course, we always wrap our text, so this would never happen to us! But still, now you know ^_^

We also need to make sure each <ins> or <del> element is either inline or block-level, but not both. For example, don’t start in the middle of one paragraph and end in the middle of the next.

<!-- This is wrong -->
<p>Flying monkeys are <del>a common hazard.</p>
<p>Protect yourself by</del> screeching loudly.</p>

<!-- del as inline -->
<p>Flying monkeys are <del>a common hazard.</del></p>
<p><del>Protect yourself by</del> screeching loudly.</p>

<!-- del as block-level -->
<del>
  <p>Flying monkeys are a common hazard.</p>
  <p>Protect yourself by screeching loudly.</p>
</del>
<p>Flying monkeys are screeching loudly.</p>

datetime and cite attributes

The <ins> and <del> elements can also take two optional attributes, datetime and cite. You’ll be familiar with datetime from our article on the <time> element, and it works just the same here. Use it to record the date (and optionally the time) of the edit:

<p><del datetime="2012-09-13">Todo: add a datetime example here.</del>  <ins datetime="2012-09-14T10:21:44+09:00">This inserted text has the date and time it was added indicated via the datetime attribute.</ins></p>

cite will also be familiar if you’ve read our article Quoting and citing with blockquote, q, cite, and the cite attribute. It contains a URL linking to more information about the change.

<!-- Reference or in-page links are URLs too -->
<ins cite="#ins-1">This inserted text has a cite attribute, with a link to more information.</ins>

As this is generally hidden data, there’s a strong chance of it becoming metacrap. You can help avoid this by exposing cite with CSS:

<style>
ins[cite]:after,
del[cite]:after {
  content: " (" attr(cite) ")";
  font-size: 75%;
  line-height: 0;
  color: #888;
}
</style>
…
<ins cite="https://stevefaulkner.github.io/html5doctored/more-info/123">[Inserted text…] More information is available about this addition.</ins>

[Inserted text…] More information is available about this insertion.

Example CSS to append the cite attribute’s value as generated content.

Even better, consider adding this link as content, for example:

<ins>This is an article update<a href="#ins-1">¹</a>.</ins>
…
<footer>
  <h2>Article changes</h2>
  <ol>
    <li id="ins-1">This addition was added on <time datetime="2012-09-14T10:21:44+09:00">14th September 2012</time> by Oli Studholme.</li>
  </ol>
</footer>

Finally, make sure when using <del> that this is a removal from the document you want/need to indicate. Other options include commenting the content out using <!-- -->, or deleting it from the HTML source.

The s element

The specification describes the <s> thus:

The s element represents contents that are no longer accurate or no longer relevant.

— WHATWG HTML Living Specification

Historically <s> (and the obsolete <strike>) were font style elements, and they were deprecated in HTML 4, then dropped in HTML5. However, a couple of semantic use cases have seen <s> return. These include marking up the original price when something is on sale, and indicating a time limit that has passed, such as early bird tickets for an event. This is content that provides useful information so we don’t want to delete it, but it’s not accurate and we want to indicate this. Other uses include any outdated but still relevant information that isn’t the result of an edit. The <s> element could even arguably be used for indicating sarcasm, or for marking up examples of Sous rature for all you Jacques Derrida fans out there. Well… maybe ;-).

As an example, if Kickstarter used <s>, it might look like this:

Using the <s> element to semantically indicate when a limited pledge is full

s vs del: fight!

The <s> element seems dangerously close to stepping on the semantic toes of <del>, as I’m sure someone will helpfully point out in the comments :) However, there is a subtle but significant difference. <ins> and <del> are for showing editorial changes, generally to an already published page. The <s> element is for indicating information that is no longer relevant or accurate, but still provides some value, and is generally used to create a document with both old and new information at the same time.

Hixie describes the difference in this way:

[T]o put it another way, with <del> there is usually a view of the document that doesn’t include the <del> text. But with <s> there is no version of the document without the <s> text, because the <s> text is part of the document still, it’s just that it’s marked as old.

— Ian Hickson in the WHATWG IRC channel

Styling ins, del, and s

The browser default styles are:

  • <ins>: text-decoration: underline (default inserted content)
  • <del>: text-decoration: line-through (default deleted content)
  • <s>: text-decoration: line-through (default strikethrough content)

By using underline, the default <ins> styling is very similar to a visited link, a classic usability blunder. Worse, the default <del> and <s> styles are identical (although it’s rare that you’ll use them together). However, as long as <s> is visually distinct from <del>, I’ve found the default text-decoration: strikethrough; style of <s> ends up being what you generally want.

Phrasing ins and del styling

Here are some styles I’ve used for <ins> and <del> in the past:

ins styling

  • Normal text with green underline (example inserted content)

    ins {
      border-bottom: 1px solid #47ad09;
      text-decoration: none;
    }
  • Green text with faint underline (example inserted content)

    ins {
      border-bottom: 1px solid #ccc;
      text-decoration: none;
      color: #388807;
    }
  • Normal text with a light green background color (example inserted content)

    ins {
      text-decoration: none;
      background-color: #d4fcbc;
    }

del styling

  • Gray text (example deleted content)

    del {
      text-decoration: none;
      color: #777;
    }
  • Red text (example deleted content)

    del {
      text-decoration: none;
      color: #91081f;
    }
  • Normal or gray text with a light red background color (example deleted content)

    del {
      text-decoration: none;
      background-color: #fbb6c2;
      color: #555;
    }

Check your <ins> styling can’t be mistaken for a link. Make sure that if you only use color to differentiate, that these are easily distinguished, even for the colorblind. Avoid hiding <del> content with display: none; — if it’s no longer content remove it or comment it out. Differentiate <del> from <s> if you use both elements.

Finally, I prefer to avoid using text-decoration: line-through; for <del>, as it makes the text hard to read. When it comes to <s> however, this default style seems to be the best fit, which is just as well because nothing else seems appropriate.

Flow ins and del styling

By default, <ins> and <del> are treated as inline elements by browsers, and styled as such. If you want to use block-level CSS, you’ll need to apply display: block;. Also, even the nicer styles above can be a little strong for whole paragraphs of text, not to mention useless for e.g. a block-level image. I style <ins> and <del> for phrasing use, and use classes with overrides for block-level use:

  • Block-level <ins> with green left border
.ins-block {
  display: block;
  margin-left: -1em;
  border-left: 0.5em solid #47ad09;
  /* styles to override inline ins style, e.g.
  text-decoration: none; */
  padding-left: 0.5em;
}

Alice was beginning to get very tired of sitting by her sister on the bank and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, “and what is the use of a book,” thought Alice, “without pictures or conversations?”

  • Block-level <del> with red left border and faded text
.del-block {
  display: block;
  margin-left: -1em;
  border-left: 0.5em solid #91081f;
  /* styles to override inline del style, e.g.
  text-decoration: none; */
  padding-left: 0.5em;
  color: #777;
}

So she was considering, in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.

You could also append a label:

  • Block-level <ins>: Green border with generated content label
.labeled-ins-block {
  display: block;
  margin-left: -1.25em;
  border-left: 0.75em solid #47ad09;
  padding-left: 0.5em;
}
.labeled-ins-block:before {
  position: relative;
  display: block;
  content: "Addition";
  left: -1.55em; /* adjust to fit */
  top: 5em; /* adjust to fit */
  width: 0;
  height: 0;
  font: 0.6em/0 "Helvetica Neue", Arial, Helvetica, sans-serif;
  letter-spacing: 1px;
  color: #fff;
  -webkit-transform: rotate(270deg);
  -moz-transform: rotate(270deg);
  -ms-transform: rotate(270deg);
  -o-transform: rotate(270deg);
  transform: rotate(270deg);
}

The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down what seemed to be a very deep well.

Finally, WordPress users should note that my nemesis wpautop will laugh at your attempts to use block-level <ins> and <del>. Make sure you use “Format this post with: No Formatting”.

Conclusion

So to sum up, we recommend you use <ins> and <del> for edits to an existing document, but only when indicating these changes is beneficial for those using the page. Use <s> to indicate information that is no longer relevant or accurate, but removing that information would negatively affect the meaning. Make sure to carefully style these elements to avoid confusion with links (for <ins>), and each other (for <del> and <s>). Finally note that <ins> and <del> can be ued for inline or block-level content (although not both at the same time), but <s> can only be used for inline content.

I’ve noticed a trend towards not having dates as part of the article’s URL, with authors then making a concious effort to keep articles up-to-date. If you do this, <del> and <ins> change from being rarely used to quite useful for indicating your edits. On the other hand, <s> seems destined to remain one of those obscure but useful elements that you’ll hardly ever need, but will be glad to have available when you do.

So what do you think? Do you use these elements? Will you use them now? Do you have any other ways you like to style them? Let us know in the comments!

Comparing and contrasting ins, del, and s originally appeared on HTML5 Doctor on August 20, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/ins-del-s/feed/ 12
The ol Element and Related Attributes: type, start, value, and reversed https://stevefaulkner.github.io/html5doctored/ol-element-attributes/ https://stevefaulkner.github.io/html5doctored/ol-element-attributes/#comments Tue, 21 Feb 2012 14:30:52 +0000 http://html5doctor.com/?p=4397 The <ol> element has a new attribute reversed in HTML5. In addition, a couple of related attributes purged in HTML 4 have made a return, namely start and type for <ol>, and value for <li>. Making things more interesting, the returning attributes were removed from HTML 4 for being presentational. So why are they back? Let’s investigate…

]]>
The <ol> element has a new attribute reversed in HTML5. In addition, a couple of related attributes purged in HTML 4 have made a return, namely start and type for <ol>, and value for <li>. Making things more interesting, the returning attributes were removed from HTML 4 for being presentational. So why are they back? Let’s investigate…

Presentational and semantic?

As we all know, presentational stuff belongs in CSS, not HTML. In HTML 4.01, the type attribute was replaced by list-style-type, and the start and value attributes were dropped, with only the potential (although fiddly) replacement in some cases of CSS generated content-based counters. So why would we want to specify “presentational” stuff like a list’s style in our HTML?

The type Attribute

While an ordered list’s counter style is generally presentational, in some documents it can be a part of the document’s meaning, as the specification for the type attribute notes:

The type attribute can be used to specify the kind of marker to use in the list, in the cases where that matters (e.g. because items are to be referenced by their number/letter).
— HTML: Living Standard, WHATWG

Examples of this include legal or technical documents, which can contain references to non-decimal list items in prose:

Obligations of the Company – Tranche One
Subject to satisfaction of clause 3.2(a), on Tranche One Completion the Company will:
(a) Purchase a foosball table for staff use
(b) …
Mockup of an example legal document with a highlighted reference to a non-decimal list item

We can specify the list’s style using the type attribute, with the following values:

type attribute values and their corresponding list counter types
<ol type=""> valuesEquivalent list-style-type
type="1"decimal (default style)
type="a"lower-alpha
type="A"upper-alpha
type="i"lower-roman
type="I"upper-roman

Further emphasising that this is not a general alternative to list-style-type, only these five list styles are available, whereas CSS 2.1 defines eleven <ol> list styles. If you’re not referring to list counters in your prose, or even if you are but you’re just using the default decimal list counters, then you should use CSS over the type attribute. However, if the list counter type has a semantic meaning, HTML is the place to put it. Note that CSS list-style-type will override HTML type attribute values, so they’ll only work if you haven’t specified a list-style-type in your CSS.

The start and value Attributes

The start attribute lets us set a list’s first counter. It’s handy for lists that must be split over several <ol> elements, by allowing us to continue the list item numbering from where the previous list left off. The related value attribute is used on an <li> element, and lets us manually number list items. value on the first list item also overrides start. A subsequent <li> element without value will increment the previous value by one.

The first item in the list has the ordinal value given by the ol element’s start attribute, unless that li element has a value attribute with a value that can be successfully parsed, in which case it has the ordinal value given by that value attribute.
— HTML: Living Standard, WHATWG

Here’s an example of how you could use start or value to continue a list, which also demonstrates type:

<!-- Continuing a previous list with value="" -->
<ol type="I">
  <li value="7">seventh item</li>
  <li>eighth item</li>
  <li>ninth item</li>
</ol>
<!-- Continuing a previous list with start="" -->
<ol type="I" start="7">
  <li>seventh item</li>
  <li>eighth item</li>
  <li>ninth item</li>
</ol>
  1. seventh item (using <li value="7">)
  2. eighth item
  3. ninth item
  1. seventh item (using <ol start="7">)
  2. eighth item
  3. ninth item
Using value and start to continue a previous list of six items

While both of these attributes give us more control, they unfortunately also mean adding or removing list items can make your start or value-based numbering appear broken, so in general you’ll probably want to avoid them and investigate CSS generated content counters instead. You’ll need to use generated content counters if you want to make “1.1.1”-style nested list counters too.

Counting It Down with reverse

The new attribute reverse allows us to make ordered lists that count down rather than up. If you’re coding a top ten countdown or you’re a space junkie, it’s the attribute you’ve always wanted.

The reversed attribute is a boolean attribute. If present, it indicates that the list is a descending list (..., 3, 2, 1).
— HTML: Living Standard, WHATWG

By default, <ol reversed> starts from the total number of list items and counts down to one, so there’s no need to also specify start unless you want something different to happen. Unfortunately, as we’ll see in the browser support table in just a moment, none of them do yet, so in the meantime you can make a reversed list by manually specifying each list item’s number with value (as you can see in the following example) or via CSS counters.

<!-- default list -->
<ol>
  <li>three</li>
  <li>two</li>
  <li>one</li>
</ol>
<!-- using the reversed attribute (will look the same as the third list in a supporting browser) -->
<ol reversed>
  <li>three</li>
  <li>two</li>
  <li>one</li>
</ol>
<!-- using value attributes on li -->
<ol>
  <li value="3">three</li>
  <li value="2">two</li>
  <li value="1">one</li>
</ol>
  1. three
  2. two
  3. one
  1. three
  2. two
  3. one
  1. three
  2. two
  3. one
A normal ordered list, an ordered list with reversed, and an ordered list with each list item numbered manually via value

Browser support table

Browsers support the start, type, and value attributes as part of supporting legacy content (HTML 3.2 represent!), so we can use them now.

Browser support for type, start, value, and reversed attributes
Attribute IE Firefox Safari Chrome Opera
<ol type=""> ✔ ✔ ✔ ✔ ✔
<ol start=""> ✔ ✔ ✔ ✔ ✔
<li value=""> ✔ ✔ ✔ ✔ ✔
<ol reversed> ¹ ✘ ✘ ² 5.2 ³ 18 ³ ✘
  1. We can use a JavaScript polyfill to get around the lack of native support for the reversed attribute, such as the , or Titani’s polyfills, which both use the value attribute.
  2. It’s bug 601912, but there’s no progress as yet
  3. Chrome 18 (in the dev channel at the time of writing) has support for reversed (thanks Philip Tellis), as does Safari 5.2 Developer Release (thanks Sam Rayner)
<!-- default (unsupported) reversed attribute -->
<ol reversed>
  <li>three</li>
  <li>two</li>
  <li>one</li>
</ol>
<!-- using a reversed attribute polyfill -->
<ol class="polyfill-me" reversed>
  <li>three</li>
  <li>two</li>
  <li>one</li>
</ol>
  1. three (default list with reversed)
  2. two
  3. one
  1. three (list with polyfilled reversed)
  2. two
  3. one
Our earlier reversed example using a tweaked version of Titani’s <ol reversed> polyfill

You can detect for browser support using Modernizr, via the Community add-on “lists-reversed”. If your polyfill was called reversed.js you could load it using the following code:

yepnope({
  test : Modernizr.olreversed,
  nope : ['reversed.js']
});

The custom Modernizr build for doing this would be:

  • Extra > Modernizr.load
  • Extensibility > Modernizr.addTest
  • Community add-ons > lists-reversed

Conclusion

These attributes aren’t ones you’ll use often, but sometimes they’ll be just the ticket. They’ll help you avoid adding list item numbering as part of your content (leading to double numbering if your CSS with list-style-type: none; is disabled), or ugly hacks like height:0; on a bunch of filler <li> elements to get the right start value. Even better, type, start, and value are supported and ready to use now.

As usual, just make sure you are only using them where appropriate:

  • Only use type if the list style for counters is semantic, and the document’s meaning will change if your CSS (containing the equivalent list-style-type values) didn’t load.
  • For start, consider whether your lists could be combined.
  • Avoid value if at all possible, as it’s less fragile and error-prone to let the browser number list items for you.
  • Unfortunately, the current lack of browser support means you’ll need to polyfill reversed if you want to use it for now.

So what do you think of these new attributes? Have you needed them in the past? Have you actually used some of them back in the day to rock some old-skool HTML 3.2? Will you use them in the future? Let us know in the comments!

Updates

  1. I’ve added more browser support information and corrections from the comments. Thanks!

The ol Element and Related Attributes: type, start, value, and reversed originally appeared on HTML5 Doctor on February 21, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/ol-element-attributes/feed/ 16
Goodbye time, datetime, and pubdate. Hello data and value. https://stevefaulkner.github.io/html5doctored/time-and-data-element/ https://stevefaulkner.github.io/html5doctored/time-and-data-element/#comments Wed, 02 Nov 2011 16:53:08 +0000 http://html5doctor.com/?p=4071 While HTML5 is stable and being implemented we’re still not past losing (or gaining) an element, as demonstrated by the removal of <time> and the addition of <data>. Rather than jumping into the ensuing brouhaha, we’ve spent some time figuring out what this really means. In short? Well… it’s complicated.

]]>
Please note that since this was written, <time>, datetime and (possibly) pubdate have been reinstated, and made more powerful. Doctor Bruce has the low-down in his blogpost The best of <time>s. We preserve this merely to show our grandchildren that we played a role in the Time Wars.

We’ve come a long way in the HTML5 specification’s steady march towards ratification and implementation. The WHATWG’s energy has recently been more on post-HTML5 features that are being added to “HTML The Living Standard”, plus tidying up HTML5 for Last Call. However we’re still not past losing (or gaining) an element, with last week seeing the removal of <time> and the addition of <data>.

: As per the HTML Working Group Chairs request, the W3 HTML5 Editor’s Draft spec has been reverted to include <time>. Note this means it no longer includes <data>. The WHATWG HTML: Living Standard spec is currently the opposite, still retaining <data> but with no <time>. According to Anne Van Kesteren’s post on the WHATWG Weblog, <time> will return to the WHATWG spec taking into account new use cases on the WHATWG Wiki.

TL;DR — it looks like <time> will remain, probably with more permissive datetimes, and <data> will also remain, but it’ll take a little while before the dust settles.

<time> was originally added to allow dates and times to be machine readable, via the datetime attribute. This gives us human-readable content (“yesterday”) plus hidden machine-readable content (“2011-11-02”) with no accessibility problems. It allows for e.g. browsers to offer to localise dates. The pubdate attribute indicating an article’s date of publication was added for HTML to Atom conversion (also removed from HTML5 in this change), and would make it easy for search engines to sort by date. Having permitted dates and times specified in HTML5 (a subset of ISO 8601) allows a validator to check a datetime value is valid.

<time> has been one of the easier elements to understand for authors, as it’s semantically obvious. By comparison the microformats Class-Value pattern for datetimes is clunky.

HTML5 <time> element:

<time class="dtstart" datetime="2011-10-05T09:00Z">9am on October 5</time>

Microformats Value-Class pattern:

<span class="dtstart"><abbr class="value" title="09:00">9am</abbr> on <abbr class="value" title="2011-10-05">October 5</abbr></span>

<time> has been pretty widely used for weblog article publication dates, and has made it into WordPress and Drupal plus being used by Google for search results.

The issues raised about <time> by authors were mainly that it didn’t do everything: it didn’t cover ancient and vague times, time durations, and there was no “last updated” attribute equivalent to pubdate. The other problem is there are a bunch of other less common but similar kinds of data that would also benefit from being machine readable and validatable, such as weights and prices. Minting a new element for each one would (arguably) be a lot of work, so Ian Hickson has added a generic element for these use cases instead — the <data> element, with a required value attribute.

The data element represents its contents, along with a machine-readable form of those contents in the value attribute.

The value attribute contains the machine-readable equivalent of the element’s content. The <data> element can be used as-is as an element equivalent of data-* for marking up private data for scripts (although without the dataset API). It can also be used in conjunction with microdata vocabularies (and potentially microformats), in which case the format of the value attribute is specified by the vocabulary.

This is a welcome addition as it gives us an easy way to duplicate microformats’ Value-Class pattern for more than just the datetimes <time> allowed. However as part of introducing <data>, <time> together with datetime and pubdate have been dropped.

This is controversial, with :

I think this is a bad decision

Steve Faulkner has requested this change be reverted, and comments on the Twitters and blogs (Bruce, WebMonkey, Zeldman) have been mostly ranging from shock to outrage.

This is because while <time> is semantically obvious, <data> is seen as an equivalent to <div> or <span>. However, “semantics for the sake of it” isn’t enough to justify being in the spec, despite the benefits. Another reason for the dismay is many people have had trouble pushing to use HTML5, and having an element removed gives fuel to anyone arguing HTML5 isn’t suitable for production.

What’s wrong with this picture

In On Semantics in HTML, Jens Meiert lists five types of semantics in HTML markup, ordered from most to least meaningful:

  • Standards bodies: elements, attributes
  • Communities: microdata and microformats vocabularies, POSH formats
  • Common sense: functional ID and class names
  • Generic names
  • Obfuscated, random, or presentational names

Demoting datetimes from spec-specified to vocabulary-specified has several effects. For one, it’s more complex. Compare these two examples using <time> and <data> respectively:

Using <time>:

<article>
 …
 <footer>Published <time pubdate datetime="2011-11-03">today</time>.</footer>
</article>

Using <data> plus the BlogPosting schema.org microdata vocabulary:

<article itemscope itemtype="http://schema.org/BlogPosting">
 …
 <footer>Published <data itemprop="datePublished" value="2011-11-03">today</data>.</footer>
</article>

While Google would no doubt love everyone to start using schema.org vocabularies, it’s a big increase in complexity. Adding <time datetime="…" pubdate> is fairly straightforward — learning and implementing microdata plus an appropriate schema.org vocabulary … not so much. Because of this fewer people will implement machine-readable article published dates.

To make matters worse, Google’s Rich Snippets Testing Tool (so presumably Google Search too) understandably does not yet know about <data>. This means if you use <data> to replace <time> now, Google will only see the human-readable text. <data itemprop="datePublished" value="2011-11-03">today</data> is interpreted as datePublished = today, not datePublished = 2011-11-03.

Also, now that specifying a datetime is not part of HTML5 we (presumably) can no longer validate datetime values using the HTML5 validator. Instead our only option is currently doing the two-step with Google’s Rich Snippets Testing Tool. Ironically as schema.org defined dates using ISO 8601, the imprecise dates and durations requested for <time> are now valid for datePublished, even though pubdate is the one usage of datetime everyone agreed on.

Pros & Cons

Ian Hickson and, it seems, browser makers in general are for this change, whereas authors are in general against it (ahem, priority of constituencies). A couple of options would be:

  1. Scrap <data> and allow the value attribute on any element
  2. Add a type attribute to <data> to make it more semantic
  3. Bring back <time>

Unfortunately there are pros and cons for each of these options:

Allow value on any element

This conflicts with microdata, where the values of some elements are their URLs rather than their content. For example, currently <img itemprop="photo" src="http://oli.jp/photo.jpg"> gives the microdata output of photo = "http://oli.jp/photo.jpg". Adding value to the mix means there’d be two machine-readable values, so authors would need to know which elements couldn’t accept value.

Add a type attribute to <data>

This means the HTML5 specification has to specify each approved type value. While not as much work for implementers as a new element for each type of data, it’s still a bunch of work if the browsers actually do anything with that knowledge (like auto-converting type="money" into your currency). If type is required it also limits <data> to the types that are defined.

Bring back <time>

The easiest way to make everyone happy is to keep <time> in addition to adding <data>. However the cons for this are we’d have two confusingly similar but not always interchangeable ways to mark up datetimes, potentially with different rules on what’s a valid datetime. For example, we’d need to mark up an article’s published date and updated date using different syntax. Special cases and exceptions make things harder to teach and learn.

Conclusion

While our private conversation between doctors about this has tended towards the WTF end of the spectrum, I’m personally up in the air about it. Despite the easy response (“bring back <time>!”), this is one of those thorny problems where there’s no simple right answer. WHATWG is performing a delicate balancing act: pragmatically adding only features that have a lot of value, and removing any that don’t make the grade. In this case Hixie decided the cons of <time> (and of removing it from HTML5) outweighed the pros, and <data> is the result.

The one thing that bothers me about Hixie’s argument is that while datetimes are similar to other types of data that <data> now lets us mark up, they’re orders of magnitude more common on the web. Regardless of how it’s marked up, almost all weblog posts have the published date, and the majority of sites have a copyright date in the footer. In these use cases <time> was perfect, and definitely covered the 80%.

In my ideal world I’d like <time> to return, with the addition of a “pubupdate” attribute, and for all dates and times that fall inside HTML5’s definition to use <time>. For datetimes that <time> currently doesn’t cover, and for general use, we’d have <data>. Then again, I’m not sure I’d want to try teaching such intricacies to someone.

What do you think about this? While you’re welcome to just jump on the hogpile, I’d be interested to hear people consider all the pros and cons, and try to come up with a better (or less problematic) solution.

Goodbye time, datetime, and pubdate. Hello data and value. originally appeared on HTML5 Doctor on November 2, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/time-and-data-element/feed/ 60
The return of the u element https://stevefaulkner.github.io/html5doctored/u-element/ https://stevefaulkner.github.io/html5doctored/u-element/#comments Tue, 25 Oct 2011 14:00:37 +0000 http://html5doctor.com/?p=3862 The <u> element was deprecated in HTML 4 and non-conforming in HTML5, but a couple of use cases have seen it return from the dead. Are the use cases enough to persuade you that it’s a phoenix not a zombie?

]]>
Presentational elements like <i>, <b>, <small> and <hr> have been redefined in HTML5 with semantic meanings, or, in a couple of cases, made non-conforming. The <u> element had been in the non-conforming camp, but a couple of semantic use cases led it back into the fold. While most of us will never need it (and some will jeer), on the odd occasion, it might be just the element you need.

Before HTML5, <u> was solely for applying a presentational style of underlining to text. HTML 4 discouraged “font-style” or presentational elements, and even deprecated <u>, advising us to use CSS instead. Even before this, <u> was frowned upon as underlines are the browser default for links, and making normal text look like links gives users a bad case of clicky-clicky frustration. <u> was initially non-conforming in HTML5.

There are, however, a couple of non-link places where text is traditionally underlined to convey meaning, as the HTML5 specification’s definition mentions:

The u element represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelt.

Before we get to them, let’s quickly cover an unarticulated, though explicitly rendered, non-textual annotation. This means <u> is for when you are annotating something, but not explicitly saying what it is (WHATWG IRC, Ian Hickson) — the annotation’s meaning is implied by context.

Chinese proper name marks

And what exactly are those you ask? I had to ask Wikipedia myself:

In Chinese writing, a proper name mark (Simplified Chinese: 专名号, zhuānmínghào; Traditional Chinese: 專名號) is an underline used to mark proper names, such as the names of people, places, dynasties, organizations. … This method of recognizing proper names in text is similar to the English use of a capital letter.

Wikipedia gives the following example, which I’ve formatted using <u>:

<u class="pnm">屈原</u>放逐,乃賦<cite class="bnm">離騒</cite>。<u class="pnm">左丘</u>失明,厥有<cite class="bnm">國語</cite>。(司馬遷 《<cite>報任安書</cite>》)

屈原放逐,乃賦離騒。左丘失明,厥有國語。(司馬遷 《報任安書》)

Qu Yuan was exiled, and thus composed the Li Sao. Zuo Qiu lost his sight, hence there is the Guo Yu. (Sima Qian, “Letter to Ren'an”)

Using <u> for Chinese proper name marks where appropriate

If you’re using Firefox 6+ you’ll also see the appropriate wavy underline for a Chinese book name mark on the quote’s source, courtesy of CSS3’s text-decoration-style: wavy;. I’ve used <cite> for book name marks as it’s more appropriate than <u>. You can find out more about wavy in CSS Text Level 3.

Using <u> for spell-checking feedback

While you’re probably not marking up classical Chinese prose, a more familiar use case is for a spell-checker to indicate incorrect text. The default formatting in word processors is typically a red underline for spelling errors, and a green underline for grammatical errors:

.spelling-error {
  text-decoration: none;
  border-bottom: 1px dashed red;
}
.grammatical-error {
  text-decoration: none;
  border-bottom: 1px dashed green;
}
<p>hello doctor i am having a huge body <u class="spelling-error">oder</u> <u class="grammatical-error">it is smell really bad</u></p>

hello doctor i am having a huge body oder it is smell really bad

Using <u> for annotating spell checker feedback

While we’ve turned off the default text-decoration style, <u> will back us up if CSS is disabled, and potentially provide more information for assistive technology. After all, if it’s semantic it should be in HTML, not CSS.

Some word processors use wavy underlines. This CSS would have the same effect in a supporting browser:

.spelling-error {
  text-decoration-line: underline;
  text-decoration-style: wavy;
  text-decoration-color: red;
}
.grammatical-error {
  text-decoration-line: underline;
  text-decoration-style: wavy;
  text-decoration-color: green;
}

Or, using text-decoration as a shorthand property, and adding a default declaration for non-supporting browsers:

.spelling-error {
  text-decoration: underline; /* for backwards compatibility */
  text-decoration: underline wavy red;
}
.grammatical-error {
  text-decoration: underline; /* for backwards compatibility */
  text-decoration: underline wavy green;
}

Again, you can read more about the upgraded text-decoration properties in CSS Text Level 3.

Using <u> for indicating family names

Another use for <u> is to annotate a family name when this might be confusing — Chinese, Japanese, Korean and Vietnamese (among others) all traditionally write names in a different order than the western-centric “given-name family-name”. While applying a blanket western ordering is fairly common (especially when publishing in English), it’s good form to use culturally appropriate ordering. If the audience might misunderstand, the family name can be underlined, capitalised, or otherwise annotated to make the name order explicit. For example, the CIA’s World Fact Book capitalises the family name:

After World War II, the Communists under MAO Zedong established an autocratic socialist system …

This ties in nicely with the hCard microformat, as the “implied n optimisation” doesn’t work with these non-western ordered names, and we need a wrapper element to indicate each part of the name anyhow.

<style>
  .family-name {text-decoration: underline;}
</style>
<p>
  <span class="vcard" lang="ja-latn">
    <span class="fn n">
      <u class="family-name">Son</u> <span class="given-name">Goku</span>
    </span>
  </span>
   is the main protagonist in 
  <span class="vcard" lang="ja-latn">
    <span class="fn n">
      <span class="given-name">Akira</span> <u class="family-name">Toriyama</u>
    </span>
  </span>’s <i lang="ja-latn">manga</i> “Dragon Ball”.
</p>

Son Goku is the main protagonist in Akira Toriyama’s manga “Dragon Ball”.

Using <u> to indicate the family name in non-western names via underlining

Of course you can then change the style via CSS, for example

.family-name {
  text-decoration: none;
  text-transform: uppercase;
}

Son Goku is the main protagonist in Akira Toriyama’s manga “Dragon Ball”.

Using <u> to indicate the family name in non-western names via capitalisation

The benefit of using <u> for this is the family name will be indicated even when CSS is disabled, ensuring the annotation isn’t lost. Assistive technology may also be able to inform the user of this in the future.

But do we need <u>?

A lot of people bitten by the web standardista bug have somewhat of an allergic reaction to ex-presentational elements in HTML5, after influential articles like Tantek Çelik’s “<b>ed and <br>eakfast markup”. Given <u>’s ignoble past, I expect the reaction to its return will also lead to some poo-pooing. As we already mentioned, however, if it imparts meaning, it should be in HTML. These use cases involve semantic meaning, and even without assistive technology support, <u> conveys some meaning to sighted users via the browser-default style text-decoration: underline;.

Regardless of whether an element is deprecated (HTML 4, XHTML 1) or non-conforming (HTML5) or just plain uncool, browser makers still have to support it for backward compatibility with all those awesome web pages from the days when <blink> was hawt. Because of this, if there’s a semantic use case for an ex-presentational element, it’s definitely better to reform it rather than minting a new element with no backward compatibility. You might think <mark> sounds pretty similar, but the default browser styling would be completely wrong for proper name marks, and semantically less appropriate for spelling errors too.

As Ian Hickson explains:

The presentational markup that was <u>, <i>, <b>, <font>, <small>, etc, is gone. However, there are certain use cases that did not yet have elements yet were important enough to warrant us supporting them. By reusing existing elements, we are able to support them without having to wait for new elements to be implemented. By doing so in a way that closely matches how those elements were actually used in practice (at least to the same extent as other elements have been correctly used in practice) we can not only have older UAs support these new elements automatically, but we can do so in a way that does not introduce an undue volume of invalid pages.

Conclusion

Given the potential to confuse underlined text with links, using text-decoration: underline; on anything other than <a> is bad pretty much all the time. Generally <u> is not the element you’re looking for, even for Chinese book name marks (<cite> would be more appropriate). However, for at least these three use cases, it’s good to have a semantic option, something better than <span>.

So…in a hypothetical world where you did need to code for one of these situations, would you use <u> or something else like <span>? Let us know in the comments!

The return of the u element originally appeared on HTML5 Doctor on October 25, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/u-element/feed/ 37
Dive into HTML5… on HTML5 Doctor https://stevefaulkner.github.io/html5doctored/dive-into-html5-doctor/ https://stevefaulkner.github.io/html5doctored/dive-into-html5-doctor/#comments Mon, 17 Oct 2011 12:50:57 +0000 http://html5doctor.com/?p=3886 We were surprised and saddened when Mark Pilgrim decided to retire from the internet and take his writing, including “Dive into HTML5” with him. However the interwebs have your back. We’re adding a mirror of the book here to add to the growing list, and plan to help keep it updated. So long Mark, and thanks for all the <>!

]]>
Last week, we were surprised and saddened when Mark Pilgrim, long time educator, raconteur, and writer of note, decided to retire from the internet. Unfortunately, he also decided to 410: gone all of his writing, including Dive into HTML5.

Mark provided this book for free on the web (under a Creative Commons By 3.0 license), in addition to a published, for-sale version entitled HTML5: Up and Running from O’Reilly. This is a very unusual setup, but one we’ve collectively benefitted from. Many HTML5 Doctor articles feature links to this book, and the sudden loss of this valuable resource was a little shocking.

The interwebs soon mobilised, however, and now there are several copies of this book, including:

There are also several partial translations, including:

(Please leave a comment if you know of any others!)

Jonathan Neal is coordinating diveintohtml5.info and diveinto.org, and has added the following to the book’s title page:

Mark Pilgrim has stopped maintaining this project, and we want it to continue. We’re not just patching broken links and updating APIs. We plan to actively maintain it; refreshing, updating, and reflecting the relevant and current state of HTML5, just as it had been during Mark’s tenure.

We doctors feel the same way and plan to help keep the book updated. To that end, we’ve set up a mirror at diveinto.html5doctor.com, and we’ll be experimenting with using GitHub to contribute.

We’d like to publicly thank Mark Pilgrim for both writing this wonderful reference on HTML5 (and all his other writing over the years), and for making Dive into HTML5 available under a CC-By license that makes it possible for us to mirror it here. We’re interested to see where this brave new world of distributed community editing collectively takes us, and we invite you to pitch in.

Dive into HTML5… on HTML5 Doctor originally appeared on HTML5 Doctor on October 17, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/dive-into-html5-doctor/feed/ 7
Quoting and citing with <blockquote>, <q>, <cite>, and the cite attribute https://stevefaulkner.github.io/html5doctored/blockquote-q-cite/ https://stevefaulkner.github.io/html5doctored/blockquote-q-cite/#comments Tue, 28 Jun 2011 13:30:21 +0000 http://html5doctor.com/?p=3373 Given HTML’s roots in the academic world, it should be no surprise that quoting is well-accomodated in the elements blockquote and q, with their optional cite attribute. In addition, there’s the cite element, which over the last nine years went from ‘semantic orphan element made good’ to one of the more contentious elements in HTML5. Let’s power up the endoscope and examine the scarring, starting with blockquote.

]]>
NOTE: (6/11/2013) The definitions of cite and blockquote in HTML have changed. For the latest advice on using these elements refer to cite and blockquote – reloaded

Given HTML’s roots in the academic world, it should be no surprise that quoting is well-accommodated in the elements <blockquote> and <q>, with their optional cite attribute. In addition, there’s the <cite> element, which over the last nine years went from ‘semantic orphan element made good’ to one of the more contentious elements in HTML5. Let’s power up the endoscope and examine the scarring, starting with <blockquote>.

Quoting with <blockquote>

We’ve become pretty familiar with <blockquote> here, as most of our articles feature excerpts from the HTML5 specification. Look, here’s one right now:
The blockquote element represents a section that is quoted from another source.
Easy peasy, right? Nothing has really changed. Remember that as <blockquote> is a ‘block-level element’ (flow content) we can put most anything in it, including headers, images and tables, in addition to the usual paragraphs of text. There are a couple of slight differences in HTML5 though. <blockquote> is a sectioning root, meaning that any <h1>-<h6> elements it contains don’t become part of the document’s outline. Also, adding a single paragraph of text with no enclosing <p> tags is now completely kosher. Here are some simple <blockquote> examples (apologies for the fake content):
<blockquote>This is a short block quote — look Ma, no paragraph tags!</blockquote>
This is a short block quote — look Ma, no paragraph tags!
<blockquote><p>This is a longer block quote.</p>
  <p>It uses paragraph elements.</p>
</blockquote>
This is a longer block quote. It uses paragraph elements.
<blockquote><h1>OMG a heading!</h1>
  <ul><li>Block quotes can contain more than just paragraphs…</li></ul>
</blockquote>

OMG a heading!

  • Block quotes can contain more than just paragraphs…
Historically, adding the source of a <blockquote> was a semantic conundrum. If you add it as content of the <blockquote>, then semantically it would become part of the quote, right? <blockquote> (and <q>) have a cite attribute for the URL of the quote’s source, to provide context. That’s hidden data, however, and despite the potential for exposing the cite attribute via CSS and/or JS, that’s not as useful as a visible link.
  It seems our long-running convention at HTML5 Doctor of using <footer> for attribution inside a <blockquote> is actually non-conforming. However the phrase in the spec that prevents it also prevents other common block quoting patterns, so the spec will probably change. Read my article <blockquote> problems and solutions, and submit feedback via the WHATWG email list, the comments here or to be via Twitter (@boblet) — your feedback will influence how the spec changes! I’ll update this article after the change, but until then be aware <footer> for attribution in a <blockquote> isn’t strictly valid, and may not be in the future either. The spec currently recommends including attribution in content surrounding the <blockquote>.

Hixie has given his feedback on my email, and it seems like our <footer> citations are still invalid. The official recommendation is to put the blockquote in a figure and add attribution in <figcaption>. Read the whole thread as there are some interesting comments. I’ll wait for the dust to settle a little yet…

HTML5 comes to our rescue with the <footer> element, allowing us to add semantically separate information about the quote. For example:
<blockquote>
  <p>You know the golden rule, don’t you boy? Those who have the gold make the rules.</p>
  <footer>— Crazy hunch-backed old guy from the movie Aladdin</footer>
</blockquote>
You know the golden rule, don’t you boy? Those who have the gold make the rules.
— Crazy hunch-backed old guy from the movie Aladdin
Because of this semantically sound way to show the quote’s source, if you’re going to add a cite attribute on <blockquote>, only do so in addition to visible attribution.
<blockquote cite="http://www.imdb.com/character/ch0000672/quotes">
<p>You know the golden rule, don’t you boy? Those who have the gold make the rules.</p>
<footer>— <a href="http://www.imdb.com/character/ch0000672/quotes">Crazy hunch-backed old guy in Aladdin</a></footer>
</blockquote>
You’ve heard of the golden rule, haven’t you? Whoever has the gold makes the rules.
Even then, the cite attribute is probably only worth it if you can automate it (or you're just crazy OCD ;). We’ll return to <blockquote> in a bit, but let’s first probe into <q>.

Inline quotations with <q>

<q> is for quoting something inline within a section of prose:
The q element represents some phrasing content quoted from another source.
This means we can’t use <q> for sarcasm or other non-quotation uses of quote marks (“”). In those cases, add punctuation manually. The spec continues:
Quotation punctuation (such as quotation marks) that is quoting the contents of the element must not appear immediately before, after, or inside q elements; they will be inserted into the rendering by the user agent.
As with <blockquote>, you can also add a cite attribute with a URL for the quotation’s source (subject to the above caveats against hidden data). If you’re not using these extra features though, it’s a toss-up as to whether <q> is any better than just adding punctuation characters like “” as you type. Okay, let’s see some specimens:
Nested quotations:
<p>Luke continued, <q>And then she called him a <q>scruffy-looking nerf-herder</q>! I think I’ve got a chance!</q> The poor naive fool…</p>
Luke continued, And then she called him a scruffy-looking nerf-herder! I think I’ve got a chance! The poor naive fool…
Language-appropriate quotations (example updated, thanks Zev, Bertil, & Janus):
<ul>
<li lang="ja">彼女は<q>日本語に猫は『にゃん』と鳴く</q>と言った。</li>
<li><i lang="ja-latn">Kanojo wa <q>Nihongo ni neko wa ‘nyan’ to naku</q> to itta.</i></li>
<li>She said <q>In Japanese cats say <i lang="ja-latn">nyan</i></q>.</li>
</ul>
  • 彼女は猫は『にゃん』と鳴くと言った。
  • Kanojo wa Nihongo ni neko wa ‘nyan’ to naku to itta.
  • She said In Japanese cats say nyan.
A quotation using the cite attribute. Note that I’ve also included the cite attribute’s link in content so it’s accessible:
<p><a href="http://www.imdb.com/character/ch0000672/quotes">The Aladdin character Jafar</a> presents an eloquent treatise on the recent global economic meltdown when he states <q cite="http://www.imdb.com/character/ch0000672/quotes">You know the golden rule, don’t you boy? Those who have the gold make the rules.</q></p>
The Aladdin character Jafar presents an eloquent treatise on the recent global economic meltdown when he states You know the golden rule, don’t you boy? Those who have the gold make the rules.
Let’s examine how to style these elements next.

Styling <q> and <blockquote>

Historically, browser support has been patchy for controlling the punctuation used by <q>. Things have settled down now, so we can define nested, language-specific and even author-defined punctuation via CSS.
Browser support for styling quotes
IE Firefox Safari Chrome Opera
Default <q> punctuation¹ 8.0 “” ‘’ 1.5 “” ‘’ 2.0 "" 4.0? "" '' 1.0? "" '' 4.0 “” ‘’
quotes with Unicode escapes 8.0 1.5 5.1² 11.0² 4.0³
quotes with glyphs 8.0 1.5 5.1² 11.0² 4.0³
  1. Default <q> support requires on :before and :after
  2. Webkit support has been weak, with "" and '' hard-coded until Safari 5.1 and Chrome 11. Ref: WebKit bugs 6503 (fixed) and 3234 (new).
  3. Opera is buggy if you nest <q> to a greater depth than quote pairs in your quotes property (test case)
“Correct” punctuation is an intricate topic and varies depending on language, but it generally involves these characters:
Quote punctuation characters
Glyph Description Unicode escape Entity Mac Windows Linux
“ Left double quotation mark \201C &ldquo; Option-[ Alt+0147 AltGr+V
” Right double quotation mark \201D &rdquo; Option-Shift-[ Alt+0148 AltGr+B
‘ Left single quotation mark \2018 &lsquo; Option-] Alt+0145 AltGr+Shift+V
’ Right single quotation mark \2019 &rsquo; Option-Shift-] Alt+0146 AltGr+Shift+B
« Double left-pointing angle quotation mark \00AB &laquo; Option-\ Alt+174 AltGr+[
» Double right-pointing angle quotation mark \00BB &raquo; Option-Shift-\ Alt+175 AltGr+]
‹ Single left-pointing angle quotation mark \2039 &lsaquo; Option-Shift-3 Alt+0139 -
› Single right-pointing angle quotation mark \203A &rsaquo; Option-Shift-4 Alt+0155 -
„ Double low-9 quotation mark \201E &bdquo; Option-Shift-W Alt+0132 -
‚ Single low-9 quotation mark \201A &sbquo; - - -
Narrow no-break space \202F &#8239; - - -

If you’re using the charset UTF-8 (and you should be), we recommend you use the actual characters if possible, rather than the Unicode escapes in CSS or the entities in HTML. You can enter most of these using the keyboard — e.g. “ is Opt-[ on Mac, Alt + 0147 on Windows, and AltGr + V on Linux. Avoid using ", ' or ` in place of “” and ‘’. The “narrow no-break space” is used inside French guillemets.

Most languages alternate between two kinds of punctuation as quotes are nested, such as “” and ‘’ in English. To specify nested quote pairs in CSS, we would write this:
q {quotes: '“' '”' '‘' '’';} /* opening followed by closing quote pairs */
/* The equivalent using Unicode escapes:
  q {quotes: '\201C' '\201D' '\2018' '\2019';} */
q:before {content: open-quote;}
q:after {content: close-quote;}
Unfortunately, browsers use the last quote pair in the quotes property for more deeply nested quotations. In addition, Opera will use the wrong quote characters if you have more nested <q> than your quotes property defines quoting levels for (Opera quotes bug test case). Make sure you have enough levels by repeating quote pairs as necessary:
/* four levels of nested quotes */
q {quotes: '“' '”' '‘' '’' '“' '”' '‘' '’';}
WebKit had "" and '' hard-coded in the browser stylesheet until Safari 5.1 and Chrome 11, which prevented q:before {content: open-quote;} and q:after {content: close-quote;} from working. The workaround is to define opening and closing punctuation manually, then override with open-quote and close-quote. While it’s a little more involved, that’s why we use this CSS on HTML5 Doctor:
/* for two levels of nested quotations */
q {quotes: '“' '”' '‘' '’';}
 /* extra content definitions for pre-2011 WebKit */
q:before {content: '“'; content: open-quote;}
q:after {content: '”'; content: close-quote;}
q q:before {content: '‘'; content: open-quote;}
q q:after {content: '’'; content: close-quote;}
  /* q in blockquote */
blockquote q:before {content: '‘'; content: open-quote;}
blockquote q:after {content: '’'; content: close-quote;}
blockquote q q:before {content: '“'; content: open-quote;}
blockquote q q:after {content: '”'; content: close-quote;}
  /* blockquote hanging opening quote */
blockquote:before {display: block; height: 0; content: "“"; margin-left: -.95em; font: italic 400%/1 Cochin,Georgia,"Times New Roman",serif; color: #999;}
A more traditional English <blockquote> style uses an opening quote character before each paragraph of the quotation and a closing quote character on the last paragraph. You can do that with this CSS, but you’ll need to use <p> for the <blockquote>’s content.
/* alternative blockquote style */
blockquote {quotes: '“' '”';}
blockquote p:before {content: '“'; content: open-quote;}
blockquote p:after {content: ''; content: no-close-quote;}
blockquote p:last-child:after {content: '”'; content: close-quote;}

When quoting a foreign language, we use the quotation marks of the surrounding language, so a Japanese quote in an English sentence still uses English quotation marks:

All he knows how to say in Japanese is 「わかりません」 “わかりません” (I don’t understand).

If you’re dealing with multilingual content, you can specify the quotes property per-language:
/* quotes for French, German (two kinds) and Japanese */
:lang(fr) > q {quotes: '« ' ' »' '“' '”';}
:lang(de) > q {quotes: '„' '“' '‚' '‘';}
:lang(de) > q {quotes: '»' '«' '›' '‹';} /* alternative style */
:lang(ja) > q {quotes: '「' '」' '『' '』';}
You can learn more about this CSS in the specification: CSS Generated Content Module Level 3. Okay, it’s time to put the rubber gloves on: <cite> is up next.

The rise and fall of <cite>

<cite>’s rise to stardom as the semantic super-element

In HTML 2 <cite> was used to indicate the title of a book or other citation. But in HTML 3.2 and HTML 4.01, <cite> was more loosely defined as
Cite: Contains a citation or a reference to other sources
We can define “citation” as:
  • a reference to authority or precedent,
  • a quotation that’s being cited, or
  • a mention of someone or something
And “a reference to other sources” is even less specific [cue Jaws music]. The HTML 4.01 spec’s examples were:
As <CITE>Harry S. Truman</CITE> said… More information can be found in <CITE>[ISO-0000]</CITE>
Sadly, an example of an academic-style citation wasn’t included. Some standardistas enthusiastically adopted <cite> for its semantics, with the high point being Mark Pilgrim’s epic “Posts by citation” (the results of which are now sadly 404’ed). In those heady days, <cite> was used in three main ways:
  1. To refer to a person, generally in connection with some reference or as the source of a quote:
    <!-- Not valid usage of cite in HTML5! -->
    <p>As <cite>George R. R. Martin</cite> wrote in…</p>
  2. To contain the title of a work being referred to or quoted from (what <cite> is now used for in HTML5 — thanks Dylan!):
    <p><cite>A Game of Thrones</cite>, by George R. R. Martin</p>
  3. To contain a full academic-style citation (title plus author, and maybe bibliographic information):
    <!-- Not valid usage of cite in HTML5! -->
    <p><cite>A Game of Thrones, by George R. R. Martin</cite></p>
    • Historically this might also be marked up as:
      <!-- Not valid usage of cite in HTML5! -->
      <p><cite class="book-title">A Game of Thrones</cite>, by <cite class="author">George R. R. Martin</cite></p>
    • or as Wikipedia does (with <cite> set to font-style: normal;):
      <!-- Not valid usage of cite in HTML5! -->
      <p><cite>George R. R. Martin, <i>A Game of Thrones</i></cite></p>
“Wow, what an all-rounder!” I hear you say. “Is there anything <cite> can’t do?” The dirty secret of all this is the <cite> element has historically been semantics for the sake of semantics. So far, the only non-site-specific application of <cite> is browser default stylesheets, which format it with font-style: italic;. This is not a bad thing, as using <cite> consistently on your own site allows you to do all kinds of fun stuff (as Pilgrim demonstrated). But in the past, it’s been used to refer to three related but quite different types of data: titles, full citations, and names. This makes web-wide use, such as by a search engine, tricky.

<cite> snorts too much semantics, checks into rehab

So, in HTML5 this semantic over-achiever has ended up with a more … prosaic definition:
The cite element represents the title of a work (e.g. a book, a paper, an essay, a poem, a score, a song, a script, a film, a TV show, a game, a sculpture, a painting, a theatre production, a play, an opera, a musical, an exhibition, a legal case report, etc). This can be a work that is being quoted or referenced in detail (i.e. a citation), or it can just be a work that is mentioned in passing. A person's name is not the title of a work — even if people call that person a piece of work — and the element must therefore not be used to mark up people's names
This restriction has been somewhat … unpopular. Arguments for using <cite> for names (now summarised on the WHATWG wiki) were addressed by Ian Hickson, who decided that historical use wasn’t enough to justify the wooly definition. Jeremy Keith’s 24 Ways article “Incite A Riot” called for civil disobedience and HTML 4.01-style <cite>-ing, but the HTML5 spec has not changed. The in<cite>rs are irate that there are two use cases that <cite>’s new definition leaves semantically unfilled — to mark up speakers in a transcript or dialog, and to indicate the speaker or author of an inline quote (<q>). The HTML5 spec adds semantic insult to injury by saying:
In some cases, the <b> element might be appropriate for names; e.g. in a gossip article … In other cases, if an element is really needed, the <span> element can be used.
By better defining <cite>, we increase the odds of getting usable data from it, though we now need different methods to cover these other uses. For now, it seems that these use cases aren’t specific enough to warrant new elements. Note that <cite> was never a general-purpose element for marking up a person. The still-born HTML 3.0 did try to introduce the <person> element, but if you’ve ever used hCard to semantically mark up a person’s name, you’ll know that we’d need way more than just one element to do names justice. The POSH way of marking up a name is to use hCard (in microformats, microdata or RDFa), or just with a plain old link.

Get ex<cite>d and quote stuff

History and encouraging angry comments aside, let’s suture up and see some examples of HTML5-style <cite> action:
Use <cite> for a movie title:
<p><cite>Aladdin</cite> is a great movie, even after 73 viewings. Aren’t kids great?</p>
Aladdin is a great movie, even after 73 viewings. Aren’t kids great?
Even better, use <cite> with a link:
<p><cite><a href="http://en.wikipedia.org/wiki/Aladdin_(1992_Disney_film)">Aladdin</a></cite> is a great movie, even after 73 viewings. Aren’t kids great?</p>
Aladdin is a great movie, even after 73 viewings. Aren’t kids great?
Use <cite> for the title of a book (but not the author’s name):
<p><cite>A Game of Thrones</cite>, by George R. R. Martin</p>
A Game of Thrones, by George R. R. Martin
If you wanted to semantically indicate the author, you could use microformats, microdata or RDFa:
<p><cite>A Game of Thrones</cite>, by <span class="hcard"><span class="fn n"><span class="given-name">George</span> <span class="additional-name">R. R.</span> <span class="family-name">Martin</span></span></span></p>
A Game of Thrones, by George R. R. Martin
In this example, the author and book title are only connected by proximity. You could connect them more explicitly using the hProduct microformat, RDFa’s GoodRelations, or to really bleed on the edge even Schema.org. Note that you can’t use the now-Google-approved rel="author" attribute here, as George R. R. Martin is being referred to and isn’t writing the article. If you just wanted to style the author’s name, you could use <b class="author"> (gossip column style) or <span class="author"> with whatever CSS you like.

All together now

Oay, let’s start mixing things up on the operating table and show some examples of <cite> with <blockquote> and <q>:
A movie <blockquote> with <cite>:
<blockquote>
<p>You know the golden rule, don’t you boy? Those who have the gold make the rules.</p>
<footer>— Crazy hunch-backed old guy in <cite><a href="http://en.wikipedia.org/wiki/Aladdin_(1992_Disney_film)">Aladdin</a></cite></footer>
</blockquote>
You know the golden rule, don’t you boy? Those who have the gold make the rules.
— Crazy hunch-backed old guy in Aladdin
Adding the cite attribute to a <blockquote> (and its <footer>):
<blockquote cite="http://www.imdb.com/character/ch0000672/quotes">
<p>You know the golden rule, don’t you boy? Those who have the gold make the rules.</p>
<footer>— <a href="http://www.imdb.com/character/ch0000672/quotes">Crazy hunch-backed old guy</a> in <cite><a href="http://en.wikipedia.org/wiki/Aladdin_(1992_Disney_film)">Aladdin</a></cite></footer>
</blockquote>
You know the golden rule, don’t you boy? Those who have the gold make the rules.
A quote from a specification:
<p>I wonder if feedback on <code>&lt;cite&gt;</code> prompted this:</p>
<blockquote><p>A person's name is not the title of a work — even if people call that person a piece of work</p>
<footer><cite><a href="http://developers.whatwg.org/text-level-semantics.html#the-cite-element">HTML5 for Web Developers</a></cite></footer>
</blockquote>
I wonder if feedback on <cite> prompted this:
A person's name is not the title of a work — even if people call that person a piece of work
An academic-style journal citation:
<ol>
<li>The information capacity of the human motor system in controlling the amplitude of movement, Paul M. Fitts (1954). <cite>Journal of Experimental Psychology</cite>, volume 47, number 6, June 1954, pp. 381–391</li>
</ol>
  1. The information capacity of the human motor system in controlling the amplitude of movement, Paul M. Fitts (1954). Journal of Experimental Psychology, volume 47, number 6, June 1954, pp. 381–391
An academic-style book citation:
<blockquote>
<p>Citations … all include the following: author (or editor, compiler, or translator standing in place of the author), title (and usually subtitle), and date of publication.</p>
<footer><cite><a href="http://www.chicagomanualofstyle.org/">The Chicago Manual of Style</a></cite>, 15th Edition (Chicago: University of Chicago Press, 2003), 596</footer>
</blockquote>
Citations … all include the following: author (or editor, compiler, or translator standing in place of the author), title (and usually subtitle), and date of publication.

Conclusion

If you’ve made it this far, congratulations! You’ve now learned more about citing and quoting in HTML5 than you wanted to know ;) But don’t keep the knowledge to yourself — let us know in the comments what you think. We’d also love to hear how you’re using <blockquote>, <q>, and <cite> in HTML5. If you share your code snippets, remember to escape them!

Updates

  1. : It seems our long-running convention at HTML5 Doctor of using <footer> for attribution inside a <blockquote> is in keeping with the <footer> part of the spec, but not with the <blockquote> part. We’re investigating…
  2. : Hixie confirmed that our use of <footer> is currently non-conforming — <footer> can currently only be included in <blockquote> if it’s quoted content. However, the phrase “content inside a blockquote must be quoted from another source” also forbids other common changes and additions to block quotes, so I’m going to see if it can be changed.
  3. : I wrote an article <blockquote> problems and solutions about these problems, and initial feedback from Hixie is that there are legitimate issues, and he’ll review feedback via the WHATWG email list. So, please do that! You can also leave feedback in the comments here or ping me on Twitter (@boblet). Also, don’t miss Jeremy Keith’s excellent commentary “Citation needed” on the issue (watch out for those <cite>s though ;) )
  4. : I’ve added keyboard shortcuts for punctuation characters to the punctuation table, for default (typically US) keyboards.
  5. Added a note about Hixie’s reply to the article.

Quoting and citing with <blockquote>, <q>, <cite>, and the cite attribute originally appeared on HTML5 Doctor on June 28, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/blockquote-q-cite/feed/ 69
HTML5 for Web Developers https://stevefaulkner.github.io/html5doctored/html5-for-web-developers/ https://stevefaulkner.github.io/html5doctored/html5-for-web-developers/#comments Fri, 25 Feb 2011 14:30:09 +0000 http://html5doctor.com/?p=3061 While they’re essential reading material for our job, W3C specifications tend to make for poor reading material. One intrepid developer set out to change this for himself — “HTML5 for Web Developers” is the fruit of his labours. In addition to introducing this awesome new resource, we make a delicious fruit salad for you by comparing it to the other HTML(5) specs.

]]>
An HTML5 spec for the rest of us -->

While they’re essential reading material for our job, the W3C specifications are not exactly George R. R. Martin-level reading material. To make matters worse, the often-dry text (written for implementors, not authors) and…colourful illustrations come wrapped in a design straight out of 1999. While the W3C homepage got some lovin’ in 2009 from the dynamic duo of Happy Cog and Airbag Industries, the actual specifications are still only slightly above the baseline of browser defaults. So what’s a caring developer to do?

Ben Schwarz, a developer in Melbourne, Australia, took matters into his own hands with a userscript to give W3C specs some readability. Around the same time Mike™ Smith — the W3C team contact for HTML Working Group amongst other things — was looking for CSS help for HTML5: The Markup Language Reference, his cut-down reference version of the HTML5 spec. I was able to introduce Mike™ and Ben, and the result was HTML5 Edition for Web Authors. But this was only the start.

Ben then got on the WHATWG IRC channel:

Within 10 minutes of joining the WHATWG IRC channel Ian Hickson had granted me approval to continue with my own build of the spec, targeted for web developers.

After a lot of hard work, with input and encouragement from the web’s finest (including Dr Bruce), Ben has released HTML5 for Web Developers.

HTML5 for Web Developers screenshot
HTML5 for Web Developers

The focus of this specification is readability and ease of access. Unlike the full HTML specification, this “web developer edition” removes information that only browser vendors need know.

In addition to streamlining the content, it boasts all manner of freshly implemented buzzwords and technical trickery through the magicks of JavaScript and CSS:

  • find-as-you-type search (type “/”)
  • offline access
  • alternate styles for mobile devices
  • technical references pulled inline
  • beautiful typography
  • …and design

It’s been well received, with more than 20,000 uniques in the first 24 hours, and the Pied Piper of HTML5 remarking:

Enjoying the gorgeously readable presentation of http://developers.whatwg.org/ Nice work, @benschwarz.

The files to build HTML5 for Web Developers are on GitHub, so if you have any problems or suggestions add an issue. You can also fork the project and help out — I have!

…but what spec should I use?

In our previous article on “HTML as a Living Standard”, guest author John Foliot voiced a valid concern that with several versions of the HTML5 specification, you might end up on a different one than you expected, so let’s have a look at the different versions. Using the W3C nomenclature, “implementors” are browser and tool makers, and “authors” are web developers, and I’ve linked to Editor’s Drafts rather than Working Drafts, as HTML5 is still in flux.

The heavyweight specs

HTML5 — A vocabulary and associated APIs for HTML and XHTML by W3C

The HTML5 spec on the W3C site. It’s smaller than the other specs because several parts (including Microdata, Canvas 2D Context, and Web Messaging) have been turned into their own specifications.

HTML5 specification screenshot
The HTML5 specification (on w3.org)

I recommend this spec if you don’t follow HTML5 developments — e.g., if you’re not a reader of HTML5 Doctor. This is the specification being prepared for Last Call in May 2011, and it shouldn't change much from here on.

HTML — Living Standard by WHATWG

The HTML spec on the WHATWG site. It’s a superset of the HTML5 spec, including some things that the W3C has split into separate specs (see above). It also includes post-HTML5 features such as Web Video Text Tracks (WebVTT), but it doesn’t include non-HTML-specific specs like Web Storage, Web Sockets API, and Server-sent Events.

HTML — Living Standard specification screenshot
HTML — Living Standard specification (on whatwg.org)

I recommend this spec if you are interested in HTML5 (and beyond) and wish to be actively involved. While it’s more liable to change (especially the new bits), it’s also likely to include improvements that haven’t made it into HTML5. It’s also what browser makers are looking at. You can also get to it quickly with the link http://whatwg.org/html.

Web Applications 1.0

This is everything the WHATWG is working on, including non-HTML-specific material (see above). It’s introduced with a photo of a kitchen sink ;)

Web Applications 1.0 specification screnshot
Web Applications 1.0 specification (on whatwg.org)

While this is pretty much the same as HTML — Living Standard, I don’t recommend it because it doesn’t have the ability to hide implementor details. However you’ll need it if you’re interested in Web Storage, Web Sockets API, and Server-sent Events. You can get to it quickly with the link http://whatwg.org/C.

Cut-down versions specifically for authors (us)

HTML5: The Markup Language Reference

A quick reference for authors describing the syntax, structure, and semantics of HTML5. It's intended to be as concise and readable as possible. From the legend and self-styled W3C HTML5 jackass himself, Mike™ Smith, who also gets bonus points for the initialism “H:TML”.

HTML5: The Markup Language Reference screenshot
HTML5: The Markup Language Reference (on w3.org)

I recommend this as a quick reference or cheat sheet to remind yourself of the essentials (well, in addition to the HTML5 Doctor glossary, of course ;-). It doesn’t have the depth of guidance or the examples in the other specs (or the implementor details), but it has info links to HTML5 for Web Developers, so you can easily get more detailed information.

HTML5 (Edition for Web Authors)

HTML5 for Web Authors was Mike™ and Ben’s first collaboration. It removes the implementation details intended for browser makers and adds some style, and it’s more in line with W3C’s HTML5 in that it doesn’t include microdata. For the time being, it’s been superseded by HTML5 for Web Developers.

HTML5 for Web Authors screenshot
HTML5 for Web Authors (on w3.org)

I recommend this for JavaScripters, as it includes more API information than HTML5 for Web Developers. Currently it’s not as up-to-date as HTML5 for Web Developers, but I expect it to receive some love in the future.

HTML5 for Web Developers

HTML5 for Web Developers also removes the implementation details intended for browser makers, but includes some parts like microdata that have been cut from W3C’s HTML5 spec. I’m very impressed with the functionality and design, and I expect it to keep improving.

HTML5 for Web Developers screenshot
HTML5 for Web Developers (on whatwg.org)

I recommend this for anyone wanting a beautiful, readable version of HTML5. With local storage, it’s also perfect for adding to an iPad home screen. As it’s on GitHub, it’s also the only spec where you can easily contribute to the design and functionality.

There’s a bunch of other related Editor’s drafts linked to in the HTML Working Group sidebar which may interest you. Lachlan Hunt’s HTML 5 Reference — a learning rather than reference-focused version of the HTML5 spec — is unfortunately currently out-of-date and on ice, so I don’t recommend it.

In Summary

I think these specs all have their place. Personally I’ve been mainly using the HTML — Living Standard version, but expect to use HTML5 for Web Developers a lot now too. The differences between these different versions of HTML5 (except for H:TML) can be broken down into two groups: the extra modules they include, and whether they include the option to show/hide implementor details — the HTML5 and HTML specs both do.

One fear John Foliot expressed is that you might accidentally end up using something that was highly likely to change. The WHATWG HTML and Web Applications specs, however, have annotations indicating the status of each item in the margin.

WHATWG annotations widget screenshot
An example of the WHATWG’s annotation notes

Handy!

Addendum — a call to arms

More generally, Ben also recently wrote an article encouraging everyone to get involved in the web standards process. WHATWG and W3C are actively seeking feedback and suggestions regarding their work (as is Ben), and you can participate in various ways:

  • Read the spec and send comments via the HTML WG and/or WHATWG mailing lists
  • Contribute feedback directly on the HTML5 and HTML — Living Standard specs via the feedback widget
  • Contribute feedback via the W3 bug tracker (you’ll need a free account)
  • Join the HTML WG as a (self-)invited expert
  • Join the WHATWG IRC chat room or forum
  • Use recently implemented features in personal sites and give feedback
  • Write about your experiences using new features
  • Make demos to show new features (or, for the truly gifted, JavaScript mockups of proposed features)
  • Or, you know, just create a whole new way to view the spec

Here at HTML5 Doctor, we’re doing our bit. I really hope you’re inspired by the backstory of HTML5 for Web Developers and see how low the barrier of entry is — inspired into action! We can (and should) all contribute to the future of the web.

I’ll leave the last words to Ben himself, who, a day after launching, said:

I'm thrilled to have it out, see good community support, and I hope that it becomes a reference for people to use every day

— Ben Schwarz

HTML5 for Web Developers originally appeared on HTML5 Doctor on February 25, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/html5-for-web-developers/feed/ 14
Extending HTML5 — Microdata https://stevefaulkner.github.io/html5doctored/microdata/ https://stevefaulkner.github.io/html5doctored/microdata/#comments Tue, 23 Nov 2010 15:00:14 +0000 http://html5doctor.com/?p=2643 For those who like (to argue about) semantics, HTML5 is fantastic. Old presentational elements now have new semantic meanings, there’s a slew of new semantic elements for us to argue about, and we've even in<cite>d a riot or two. But that's not all! Also in HTML5 is microdata, a new lightweight semantic meta-syntax. Using attributes, we can define nestable groups of name-value pairs of data, called microdata, which are generally based on the page’s content. It gives us a whole new way to add extra semantic information and extend HTML5.

]]>
For those who like (to argue about) semantics, HTML5 is fantastic. Old presentational elements now have new semantic meanings, there’s a slew of new semantic elements for us to argue about, and we've even in<cite>d a riot or two. But that's not all! Also in HTML5 is microdata, a new lightweight semantic meta-syntax. Using attributes, we can define nestable groups of name-value pairs of data, called microdata, which are generally based on the page’s content. It gives us a whole new way to add extra semantic information and extend HTML5.

Sometimes, it is desirable to annotate content with specific machine-readable labels, e.g. to allow generic scripts to provide services that are customised to the page, or to enable content from a variety of cooperating authors to be processed by a single script in a consistent manner.

For this purpose, authors can use the microdata features described in this section. Microdata allows nested groups of name-value pairs to be added to documents, in parallel with the existing content.

Instead of elements, these name-value pairs are defined via attributes:

  • itemscope — defines a group of name-value pair(s), called an item
  • itemprop="property-name" — adds a property to a microdata item. The name of the property can be a word or URL, and the value is the ‘content’ of the element with this attribute:
    • For most elements, the value is the element’s text content (not including any HTML tags)
    • For elements with a URL attribute, the value is the URL (<img src="">, <a href="">, <object data="">, etc.)
    • For the <time> element, the value is the datetime="" attribute
    • For <meta itemprop="" content="">, the value is the content="" attribute
  • itemref="" — allows a microdata item to include non-descendent properties by referring to the ids of element(s) containing them
  • itemtype="" — defines the item’s type when used on the same element as itemscope. The itemtype value is a URL that acts as an identifying vocabulary name.
  • itemid="" — allows a vocabulary to define a global identifier for a microdata item, for example an ISBN number on a book. Use itemid on the same element as the item’s itemscope and itemtype attributes.

Let’s go through these new attributes and see how to use them in practice with everyone’s favourite example band, Salter Cane.

Microdata syntax

itemscope and itemprop

<p itemscope>I’m going to the <span itemprop="name">Salter Cane</span> gig next week.
Excited!</p>

The presence of itemscope on the <p> element makes it into a microdata item. The attribute itemprop on a descendent element defines a property of this item (in this case, name) and associates it with the value Salter Cane (the <span>’s content). An item must have at least one itemprop to be valid.

itemprop names can be words or URL strings. Using URLs makes the name globally unique. If you use words, it’s best to use a vocabulary and the names defined in the vocabulary, which also makes the names unique. We cover this in the section Typed items and globally unique names.

itemprop value from an attribute

For some elements, an itemprop’s value comes from an attribute of the element, not the element’s text. This applies to values from attributes containing URLs, the datetime attribute, and the content attribute.

<p itemscope>I’m going to the <a itemprop="url"
  href="http://www.saltercane.com/">Salter Cane</a> gig 
  <time itemprop="date" datetime="2010-07-18">next week</time>. Excited!</p>

This defines an item with the properties url and date containing the values http://www.saltercane.com/ and 2010-07-18, respectively.

Note that the link’s itemprop="url" value is http://www.saltercane.com/ and not the element’s “Salter Cane” text content. In microdata, the following elements contribute their URLs as values:

  • <a href="">
  • <area href="">
  • <audio src="">
  • <embed src="">
  • <iframe src="">
  • <img src="">
  • <link href="">
  • <object data="">
  • <source src="">
  • <video src="">

Similarly, the <time> element’s value is 2010-07-18 and not its text content (i.e., “next week”).

Conversely, the URL-containing attributes of these HTML5 elements are not used as property values:

  • <base href="">
  • <script src="">
  • <input src="">

It's still possible to use the text of one of these elements as its value — e.g., <a href="">desired value</a>. We just need to add an additional itemprop:

<p itemscope>I’m going to the <a itemprop="url" href="http://www.saltercane.com/"><span itemprop="name">Salter Cane</span></a> gig <time itemprop="date" datetime="2010-02-18">next week</time>. They’re gonna rawk!</p>

This defines an item with three properties: the url is http://www.saltercane.com/, the name is Salter Cane, and the date is 2010-07-18.

We’ll return to the <meta> element’s content attribute in just a moment.

Nested items

We can make a property into a nested item by adding itemscope to an element with itemprop.

<p itemscope>The <span itemprop="name">Salter 
  Cane</span> drummer is <span itemprop="members"
  itemscope><span itemprop="name">Jamie
  Freeman</span>.</span></p>

This defines an item with two properties, name and members. The name is Salter Cane, and the members is a nested item, containing the property name with the value Jamie Freeman. Note that members doesn’t have a text value.

Items that aren’t part of other items (i.e., anything with itemscope but not itemprop, or the child of an element with itemprop) are called top-level microdata items. The microdata API returns top-level microdata items and their properties, which includes nested items.

Multiple properties

Items can have multiple properties with the same name and different values:

<span itemprop="members" itemscope>The band members are
  <span itemprop="name">Chris Askew</span>,
  <span itemprop="name">Jeremy Keith</span>,
  <span itemprop="name">Jessica Spengler</span> and
  <span itemprop="name">Jamie Freeman</span>.</span>

This defines the property name with four values, Chris Askew, Jeremy Keith, Jessica Spengler and Jamie Freeman.

One element can also have multiple properties (multiple itemprop="" names separated by spaces) with the same value:

<p itemscope><span itemprop="guitar vocals">Chris Askew</span>
  is so dreamy.</p>

This defines the properties guitar and vocals, both of which have the value Chris Askew.

In-page references via itemref

Items can use non-descendant properties (name-value pairs that aren’t children of the itemscope element) via the attribute itemref="". This attribute is a list of the IDs of properties or nested items elsewhere on the page.

<p itemscope itemref="band-members">I’m going to the
  <a itemprop="url" href="http://www.saltercane.com/">
  <span itemprop="name">Salter Cane</span></a> gig
  <time itemprop="date" datetime="2010-07-18">next 
  week</time>. Excited!</p>
  …
  <p>Salter Cane are <span id="band-members"
  itemprop="members" itemscope>
  <span itemprop="name">Chris Askew</span>, 
  <span itemprop="name">Jeremy Keith</span>, 
  <span itemprop="name">Jessica Spengler</span>
  and <span itemprop="name">Jamie Freeman</span>.</span></p>

This defines the properties url, name, and date. Additionally, it references the ID band-members, which contains the item members with four name properties, each of which have a different value.

Using <meta> to add content via attributes

If the text you want to add isn’t already part of the page’s content, you can use the content attribute on the <meta> element (<meta itemprop="" content="">) to add it.

<p itemscope><span itemprop="name" itemscope>Jessica Spengler
  <meta itemprop="likes" content="Mameshiba"></span>’s fans are always
  really raucous.</p>

Unfortunately, some current browsers move <meta> elements into the document's <head>. The elegant workaround is to use an in-page reference via itemref, so it’ll be included by tools that understand microdata even if the browser has moved it.

<p itemscope><span itemprop="name" itemscope itemref="meta-likes">
  Jessica Spengler<meta id="meta-likes" itemprop="likes" content="Mameshiba">
  </span>’s fans are always really raucous.</p>

Both of these code snippets define the property name with the value Jessica Spengler and the nested property likes with the value Mameshiba.

While microdata is best suited for annotating your existing content, by using <meta>-based or hidden values, microdata doesn’t have to be tied to a page’s content. In general, adding hidden content to a page is a bad idea. It’s easy to forget about and not keep up-to-date. If the information would be useful to some users, add it to the page’s content. If it’s inconvenient to add the content inside an item, consider putting it in a <footer> and including via an in-page reference.

Typed items (itemtype) and globally unique names

We can tie an item to a microdata vocabulary by giving it a type, specified via the attribute itemtype="" on an element with itemscope. The itemtype="" value is a URL representing the microdata vocabulary. Note that this URL is only a text string that acts as unique vocabulary identifier — it doesn’t actually need to link to an actual webpage (although it’s nice when it does). After doing this, we can use names in the vocabulary as itemprop names to apply vocabulary-defined semantics.

<p itemscope itemtype="http://schema.org/MusicGroup"> I went to
  hear <a itemprop="url" href="http://saltercane.com/"><span itemprop="name">
  Salter Cane</span></a> last night. They were great!</p>

This example defines the property url with the value http://saltercane.com/ and the property name with the value Salter Cane according to the http://schema.org/MusicGroup vocabulary (MusicGroup is a specialised kind of Organization vocabulary on schema.org).

Alternatively, you can use URLs for itemprop names. In this case, there’s no need to use itemtype as the vocabulary information is already contained in the name. These are referred to as globally unique names. While vocabulary-based names must be used inside a typed item to have the vocabulary-defined meaning, you can use a URL itemprop name anywhere.

Let’s rewrite the above example using URL-based names:

<p itemscope>I went to hear <a
  itemprop="http://schema.org/MusicGroup/url"
  href="http://saltercane.com/"><span
  itemprop="http://schema.org/MusicGroup/name">Salter Cane</span>
  </a> last night. They were great!</p>

This allows you to use multiple vocabularies in the same code snippet, even if they use the same property names.

Global identifiers with itemid

Sometimes an item may be identified by a unique identifier, such as a book by its ISBN number. This can be done in microdata using a global identifier via the attribute itemid="", if specified by the vocabulary. itemid can only appear on an element with both itemscope and itemtype="", and must be a valid URL.

<p itemscope itemtype="http://vocab.example.com/book"
  itemid="urn:isbn:0321687299">
  <!-- book info… -->
</p>

This defines an item containing information about a book identified by the ISBN number 0321687299, as long as the http://vocab.example.com/book vocabulary defines global identifiers like this.

This example uses a theoretical example from the spec, as schema.org Book vocabulary currently only defines ISBN as an itemprop, although they’ve mentioned plans to add itemid global identifiers to their vocabularies in the future. Global identifiers are defined for the WHATWG vocabularies for vCard and vEvent, with values like UID:19950401-080045-40000F192713-0052 and UID:19970901T130000Z-123401@host.com respectively.

Microdata in action

So now that we know how, why would we want to use microdata?

One use is adding extra semantics or data that we can manipulate via JavaScript in a similar way to custom data attributes (data-*). But if we use a vocabulary via itemtype or URL-based itemprop names, microdata becomes considerably more powerful.

While microdata is machine-readable without needing to know the vocabulary, using a vocabulary means others can know what our properties mean. This allows the data to take on a life of its own. Say what? Well, in effect, using a vocabulary makes microdata a lightweight API for your content.

If you visited someone’s homepage, wouldn’t it be great if you could add their contact information to your address book automatically? The same is true for adding an event you’re attending to your calendar. As the syntax examples were a bit example-y, let’s see how to do that using a real-world example — an upcoming event I’m organising (well, it was upcoming!):

<section>
  <h3><a href="http://atnd.org/events/5181" title="WDE-ex Vol11『iPad
  のウェブデザイン:私たちがみつけたこと 』 : ATND">WDE-ex Vol.11 — Designing
  for iPad: Our experience so far</a></h3>
  <p>On <time datetime="2010-07-21T19:00:00+09:00">July 21st 19:00
  </time>-<time datetime="2010-07-21T20:00:00+09:00">20:00</time>
  at <a href="http://www.apple.com/jp/retail/ginza/map/">Apple Ginza</a>,
  <a href="http://informationarchitects.jp/" title="iA">Oliver Reichenstein,
  CEO of iA</a>, will share the lessons they’ve learned while creating
  three iPad apps and one iPad website.</p>
</section>

WDE-ex Vol.11 — Designing for iPad: Our experience so far

On - at Apple Ginza, Oliver Reichenstein, CEO of iA, will share the lessons they’ve learned while creating three iPad apps and one iPad website.

A Web Directions East event — in code and displayed

Now we could start making up our own itemprop names on an ad-hoc basis, but this effectively prevents anyone else from using our data. By using a vocabulary and following its rules, others can also use our data. It’s a good idea to use a vocabulary, so where do we find one?

Using schema.org vocabularies

The schema.org vocabularies have now superseded the old Google vocabularies, so I’ve updated the article to reflect this.

Bing, Google and Yahoo have collaborated on a set of microdata vocabularies under the name schema.org. By using these vocabularies we can convey semantic information in our content in a way these search engines can understand. While adding semantics using these vocabularies won’t affect your search ranking, the included data may be shown in search results. The main vocabularies schema.org offers are:

  • Creative works: CreativeWork, Book, Movie, MusicRecording, Recipe, TVSeries…
  • Embedded non-text objects: AudioObject, ImageObject, VideoObject
  • Event
  • Organization
  • Person
  • Place, LocalBusiness, Restaurant…
  • Product, Offer, AggregateOffer
  • Review, AggregateRating

They’re the cross-search engine successors to Google’s earlier Rich Snippets vocabularies. Unlike Rich Snippets, which came in microformats and RDFa versions, schema.org vocabularies controversially only support microdata at the moment.

Taking our fairly standard HTML5 code for Oliver’s iPad event above, let’s add some microdata pixie dust using the schema.org vocabularies. First, the speaker (using the http://schema.org/Person vocabulary) and the venue (using the http://schema.org/Organization vocabulary):

<section>
  <h3><a href="http://atnd.org/events/5181" title="WDE-ex Vol11『iPad
  のウェブデザイン:私たちがみつけたこと 』 : ATND">WDE-ex Vol.11 — Designing
  for iPad: Our experience so far</a></h3>
  <p>On <time datetime="2010-07-21T19:00:00+09:00">July 21st 19:00
  </time>-<time datetime="2010-07-21T20:00:00+09:00">20:00</time> at
  <span itemscope itemtype="http://schema.org/Organization">
  <a itemprop="url" href="http://www.apple.com/jp/retail/ginza/map/">
  <span itemprop="name">Apple Ginza</span></a></span>,
  <span itemscope itemtype="http://schema.org/Person">
  <a itemprop="url" href="http://informationarchitects.jp/" title="iA">
  <span itemprop="name">Oliver Reichenstein</span>, CEO of iA</a>
  </span>, will share the lessons they’ve learned while creating three
  iPad apps and one iPad website.</p>
</section>
Adding schema.org microdata attributes for the speaker and location (ref: standalone file). Because they’re attributes, there is no change in how the HTML is displayed

While this content will still look the same, adding these microdata items means the following information is now machine readable:

  • A company’s name (name)
  • That company’s URL (url on <a>)
  • A person’s name (name)
  • A URL associated with that person (url on <a>)

In JSON (ref: Live Microdata) this would be:

{
  "items": [
    {
      "type": "http://schema.org/Organization",
      "properties": {
        "url": [
          "http://www.apple.com/jp/retail/ginza/map/"
        ],
        "name": [
          "Apple Ginza"
        ]
      }
    },
    {
      "type": "http://schema.org/Person",
      "properties": {
        "url": [
          "http://informationarchitects.jp/"
        ],
        "name": [
          "Oliver Reichenstein"
        ]
      }
    }
  ]
}

So we now have a semantic association between a company and a URL and between a person and a URL. With the right tool, we could add this information to an address book automatically.

Next, let’s add microdata attributes to the event data, using the http://schema.org/Event vocabulary:

<section itemscope itemtype="http://schema.org/Event">
  <h3><a itemprop="url" href="http://atnd.org/events/5181" title="WDE-ex
  Vol11『iPad のウェブデザイン:私たちがみつけたこと 』 : ATND"><span
  itemprop="summary">WDE-ex Vol.11 — Designing for iPad: Our experience so
  far</span></a></h3>
  <p itemprop="description">On <time itemprop="startDate"
  datetime="2010-07-21T19:00:00+09:00">July 21st 19:00</time>-
  <time itemprop="endDate" datetime="2010-07-21T20:00:00+09:00">20:00
  </time> at <span itemprop="location" itemscope
  itemtype="http://schema.org/Organization"><a itemprop="url"
  href="http://www.apple.com/jp/retail/ginza/map/"><span itemprop="name">
  Apple Ginza</span></a></span>, <span itemscope
  itemtype="http://schema.org/Person"><a itemprop="url"
  href="http://informationarchitects.jp/" title="iA"><span itemprop="name">
  Oliver Reichenstein</span>, CEO of iA</a></span>, will share
  the lessons they’ve learned while creating three iPad apps and
  one iPad website.</p>
</section>

On - at , , will share the lessons they’ve learned while creating three iPad apps and one iPad website.

A code sample with microdata describing an event (ref: standalone file). Adding the microdata attributes doesn’t change how the HTML is displayed.

Now things are a lot more interesting! We can extract the following data:

  • Event details
    • Event name (summary)
    • Event start and end time (startDate and endDate)
    • Event summary (summary)
    • Event URL (url on <a>)
    • Event location (location), which is represented by:
      • Company name (name)
      • Company URL (url on <a>)
  • Speaker details (well, someone connected with the event, although this connection isn’t explicit)
    • A person’s name (name)
    • That person’s associated URL (url)

Google provides a Rich Snippet testing tool, which shows what data it can extract from the schema.org microdata:

Data extracted from schema.org microdata by the Rich Snippet testing tool

Google could use this additional data in search results as follows:

Google Rich Snippet testing tool preview, showing data we marked up using microdata

The summary (linked to the event URL) and the date and venue are included. Nice! Just by using a vocabulary, Google (or a script supporting microdata) can discover lots of useful data about our event without needing one of those pesky natural language interpreters (otherwise known as humans).

Anyone who has used microformats before will also notice these vocabularies look very similar to hCard and hCalendar, although there are a couple of name changes — e.g., hCalendar’s class="dtstart" becomes itemprop="startDate".

While the schema.org vocabularies are all the search engines are promising to support, you can extend these vocabularies yourself. The safest ways to do this would be via:

Using Google’s Rich Snippets vocabularies

Google also has some basic vocabularies (precursors of schema.org vocabularies) for the following kinds of data, under the moniker of Rich Snippets:

  • people
  • businesses and organizations
  • events
  • products
  • reviews
  • recipes

These vocabularies support microformats and RDFa, two other ways to add extra semantics to our content, in addition to microdata. Apart from this difference, they’re basically identical to the matching schema.org vocabularies, except they use www.data-vocabulary.org instead of schema.org in the itemtype. While Google still supports them, the newer schema.org offers more vocabularies that are also supported by Bing and Yahoo, so choose schema.org vocabularies as long as you’re happy with microdata. You might still want to check out the Rich Snippets documentation, as it includes code samples and is generally better than schema.org’s at the time of writing.

Using WHATWG/microformats.org vocabularies

If you’re familiar with microformats or want more properties than Google’s vocabularies, the WHATWG HTML5 specification actually contains microdata vocabularies for both the vCard and vEvent specifications that hCard and hCalendar are based on, plus a licensing vocabulary.

Let’s take our earlier example and rewrite it using these vocabularies instead:

<section itemscope
  itemtype="http://microformats.org/profile/hcalendar#vevent">
  <h3><a itemprop="url" href="http://atnd.org/events/5181" title="WDE-ex
  Vol11『iPad のウェブデザイン:私たちがみつけたこと 』 : ATND"><span
  itemprop="summary">WDE-ex Vol.11 — Designing for iPad: Our experience so
  far</span></a></h3>
  <p itemprop="description">On <time itemprop="dtstart"
  datetime="2010-07-21T19:00:00+09:00">July 21st 19:00</time>-
  <time itemprop="dtend" datetime="2010-07-21T20:00:00+09:00">20:00</time>
  at <span itemprop="location" itemscope
  itemtype="http://microformats.org/profile/hcard"><a itemprop="url"
  href="http://www.apple.com/jp/retail/ginza/map/"><span itemprop="fn org">
  Apple Ginza</span></a></span>, <span itemscope
  itemtype="http://microformats.org/profile/hcard"><a itemprop="url"
  href="http://informationarchitects.jp/" title="iA"><span itemprop="fn">
  Oliver Reichenstein</span>, CEO of iA</a></span>, will share
  the lessons they’ve learned while creating three iPad apps and one
  iPad website.</p>
</section>
An HTML code sample with microdata describing an event, using vCard- and vEvent-based vocabularies (ref: standalone file)

Currently, search engines don’t map these vocabularies to schema.org ones. It’s possible they will at some stage, so decide which vocabularies to use based on what information you want to mark up, as the data is accessible regardless.

Criticism on microformats.org

Despite these vocabularies being based on vCard and vEvent and using microformats.org as their URLs, the microformats wiki actually warns against using the vCard and vEvent microdata vocabularies, stating:

For common semantics on the web … microformats are still simpler and easier than microdata, and are already well implemented across numerous services and tools.

Personally, I think the difference is marginal. If you use the recommended microformat profile links, I’d say it’s a wash. (But of course no one does ;). Microdata is actually simpler to use for date/time data than the microformat equivalents (although it is less permissive for fuzzy or ancient antiquity times), and it's more explicit, for example, avoiding the internationalisation issues of the “implied fn optimisation”. Tool support is a valid concern, but again I expect this to change over time — microdata is relatively new after all.

Browser support

The microdata specification describes the microdata DOM API, which allows us to access top-level items and their properties. Unfortunately, no browser supports this yet. Opera has experimental support in their latest snapshot, with support expected in Opera 12. It’s also being implemented by Mozilla.

Browser support for microdata (as of )
BrowserSupport
ChromeNo
SafariNo
FirefoxWork in progress
OperaIn snapshot 12.00-1033
Internet ExplorerNo

But that’s okay because this data is still useful for search engine robots and third party tools. For example, Bing, Google, and Yahoo are using microdata with the schema.org vocabularies in search results.

Tools for making and using microdata

With the right tools, we could use this data complete with its explicit semantics to, for example, add a microdata-annotated event directly into a calendar — very handy if you were planning to attend. With the release of schema.org, tools for microdata are starting to appear, but are still somewhat thin on the ground. (No Firefox plugin?! Inconceivable!). However we have libraries for three languages now:

Live Microdata converts microdata into JSON. If you’re using WHATWG/microformats.org vocabularies for vCard or vEvent, it also produces vCard and iCal output. The PHP Microdata library allows you to parse microdata in an HTML file, returning JSON or a PHP array. Mida allows you to extract microdata as JSON, and search for or inspect items. It supports defining vocabularies, and includes schema.org vocabularies. You can even use it from the command line.

Until there is native API support in browsers, we can use these libraries to access microdata. For example, you could put microdatajs on your own server to provide vCard and iCal file downloads, to allow adding the data to an address book or calendar app.

Validator.nu will validate your use of microdata, but not whether it conforms to a vocabulary. Google’s Rich Snippets testing tool also validates microdata. In addition, if you’re using the schema.org or Rich Snippets vocabularies it should display how that data could be incorporated into search results, as we saw in the Using schema.org vocabularies examples above. At the time of writing it isn’t, possibly due to this tool being updated for schema.org vocabularies.

If you have valid microdata in these vocabularies search engines will understand that data, but currently you have to “register your interest” in having your rich snippets actually be displayed (more information).

If you’d like a simple way to create microdata, with schema.org there are now several web-based form options:

  • Schema Creator supports the schema.org vocabularies for Person, Product, Event, Organization, Movie, Book, and Review
  • Schemafied supports the schema.org vocabularies for aggregate rating, article, contact point, creative work, event, local business, media object, nutrition information, offer, organization, person, place, postal address, product, rating, recipe, and thing, and also includes relevant items from other schemas
  • Microdata Generator supports the schema.org vocabularies for Attorney, Auto Dealer, Dentist, HVAC, Local Business Schema (NAP), Locksmith, Physician, Plumber, Real Estate, and Restaurant
  • HTML5 Microdata Templates supports the WHATWG and Rich Snippets vocabularies for events, organisations, people, reviews, and content

For CMSs, there’s a Schema for WordPress plugin, and initial work on adding microdata to Drupal too.

Other vocabularies

Here's a short list of microdata vocabularies and their itemtypes:

Person
Organisation or business
Calendar
Review
License
Products and services
Atom feed
  • hAtom — http://microformats.org/wiki/hatom
Recipes

It’s also possible to use RDFa vocabularies by both specifying the itemtype and using URLs for itemprop names. Refer to schema.rdfs.org for Linked Data versions of schema.org vocabularies, and the RDF vocabulary clearing-house (“namespace lookup”) http://prefix.cc.

Making your own vocabulary

If you don’t see a suitable vocabulary, you could make your own. The microdata vocabularies in the HTML5 spec are included as examples of how to do it. Basically:

  1. Work out your vocabulary’s rules. This is a little like setting up a database — work out names for each type of data, then think what kind of data each name’s value should/must contain (URL, datetime, free text, text with restrictions…), and whether something needs to be the child of something else.
  2. Make up a URL on a domain you control, and ideally put your vocabulary specification there.
  3. Use the URL in itemtype="" to reference your vocabulary.

There are, however, very good reasons not to make your own vocabulary. They can be quite hard to create, as evidenced by the work that goes into microformats vocabularies. For truly site-specific data, you’re fine with HTML5 custom data-* attributes, or using microdata the same way. But to really get the quasi-API benefits of microdata, you need to use a vocabulary that’s on more than just your site. To make a vocabulary like that, you need to cover not just your own needs, but 80% of the needs of everyone else in the same subject area.

First, check out microformats.org to see if there’s anything in roughly the same area you can just microdata-ify. After that, try RDFa vocabularies. If you still have no luck, try collaborating on a vocabulary with other people in your subject domain. If you’re going to write your own microdata vocabulary from scratch, I’d recommend trying to write a microformat first, as you’ll get a lot of good feedback and they have good info on how to write one. It’s easy to then convert the resulting microformat vocabulary into a microdata vocabulary.

Conclusion

We’ve gone through the building blocks of microdata: a simple five-attribute combo of itemscope, itemprop="", itemref="", itemtype="", and itemid="" on most any element, plus using content on <meta>. We’ve looked at how to combine these attributes to add complex semantic annotations and relationships to your content. We’ve also looked at using common vocabularies, or even creating a vocabulary, to allow the annotated data to be reused widely. This makes creating a meta-API for your website easy enough that even a designer could do it! ;-)

But microdata is not the only way to extend the semantics of HTML5 and add extra meaning. We’ve already looked at Microformats, and RDFa is up next.

Further reading and related links

My thanks to Salter Cane for agreeing to be microdata-ified. Much obliged! Their new album Sorrow is worth checking out… ;-)

Changes

  1. Added PHP Microdata Parser to the tools section
  2. Updating article for schema.org vocabularies which are also supported by Bing and Yahoo, and supersede the Google-only Rich Snippets ones. Also updating browser support (Opera) and tools (Mida) sections
  3. Finished schema.org updates, added valicator.nu to the tools section, and rewrote itemid section for clarity, since Dr Bruce was having a spot of bother with it

Extending HTML5 — Microdata originally appeared on HTML5 Doctor on November 23, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/microdata/feed/ 53
Extending HTML5 — Microformats https://stevefaulkner.github.io/html5doctored/microformats/ https://stevefaulkner.github.io/html5doctored/microformats/#comments Tue, 17 Aug 2010 13:30:18 +0000 http://html5doctor.com/?p=2304 HTML5 contains a bunch of new semantic goodness, but sometimes we need more semantics than what’s available. This is the first article in a series looking at various ways to extend HTML5 — first up, microformats.

]]>
While HTML5 has a bunch of semantic elements, including new ones like <article> and <nav>, sometimes there just isn’t an element with the right meaning. What we want are ways to extend what we’ve got, to add extra semantics that are machine-readable — data that a browser, script, or robot can use.

Native ways to extend HTML

There were five fundamental ways we could extend HTML 4:

  • <meta> element
  • class attribute
  • rel attribute
  • rev attribute
  • profile attribute

In HTML5, rev has fallen by the wayside, becoming obsolete since hardly anyone used it correctly, and because it can be replaced by rel. profile is also obsolete, and there is no support for namespaces in HTML5. However, <meta>, class, and rel are all in HTML5. In fact, <meta> now has spec-defined names and a way to submit new name values, and rel has several new link types defined in the HTML5 specification and a way to submit more too.

Even better, WAI-ARIA’s role and aria-* attributes are allowed in HTML5, and HTML5 validators can check HTML5+ARIA. Other new methods of extending HTML5 include custom data attributes (data-*), microdata, and RDFa.

Finally there are microformats. As Dr. Bruce touched on microformats in his article on the <time> element, let’s delve a little deeper into what microformats are and how to use them in HTML5.

Introducing microformats

Microformats are a collection of vocabularies for extending HTML with additional machine-readable semantics. They are designed for humans first and machines second. This is currently accomplished via agreed-upon class, rel, rev and profile attributes, coding patterns, and nesting.

Being machine readable means a robot or script that understands the microformat vocabulary being used can understand and process the marked-up data. Each microformat defines a specific type of data and is usually based on existing data formats — like vcard (address book data; RFC2426) and icalendar (calendar data; RFC 2445) — or common coding patterns (‘paving the cowpaths’ of the web).

Despite their humble beginnings, microformats have also been a runaway success, and they're far more widely deployed than other “big S” Semantic web technologies. For example, many services, such as Twitter and Flickr, offer profile information in hCard format by default, so you may already have a microformatted profile even if you’ve never used microformats before.

Microformat specifications

There are currently 34 microformats specifications (listed below) in varying levels of completion, and you can find out more about them on the microformats wiki.

Published microformats

  • Elemental (simple) microformats
    • XFN — specify relationships with people
    • XMDP — add metadata profiles
    • VoteLinks — indicate agreement or disagreement with, or indifference to, the link’s destination
    • rel-nofollow — don’t give ‘weight’ to a link (don’t give ‘Google juice’; mainly for search engines)
    • rel-license — specify license information
    • rel-tag — add tags
  • Compound microformats
    • hCard — contact information for people and organisations
    • hCalendar — time-based information, such as events
    • XOXO — outlines

Draft microformats

  • adr
  • geo
  • hAtom
  • hAudio
  • hListing
  • hMedia
  • hNews
  • hProduct
  • hRecipe
  • hResume
  • hReview
  • rel-directory
  • rel-enclosure
  • rel-home
  • rel-payment
  • robots exclusion
  • Species
  • xFolk

Despite being drafts, many of these are in widespread use.

Microformat patterns

These common coding patterns are just best practices that are frequently used in writing plain old semantic HTML (POSH) to create microformats.

  • <abbr> design pattern
  • class design pattern
  • date design pattern
  • datetime design pattern
  • include pattern
  • value class pattern
  • rel design pattern

These specifications and patterns cover many common types of data. They’ve been created by a grass-roots organisation of interested people, and anyone is welcome to contribute or even propose a new microformat.

A lightning introduction to using microformats

For those of you that haven't used microformats before, I’ll briefly introduce some simple microformats — hopefully so simple you’ll be encouraged to use them right away!

Using rel-license for licensing information

Adding license information is quite a common activity, and while we can add a link to Creative Commons or another license easily enough, someone would have to read it to understand the content’s license:

<small>This article is licensed under a 
  <a href="http://creativecommons.org/licenses/by-nc-sa/2.0/">
  Creative Commons Attribution Non-commercial Share-alike 
  (By-<abbr>NC</abbr>-<abbr>SA</abbr>) license</a>.
</small>

If this information was machine-readable, search engines could use it to help consumers searching by license. By using the rel-license microformat to add rel="license" to the license link (indicating it’s the license for the page’s main content), we can do just that:

<small>This article is licensed under a 
  <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">
  Creative Commons Attribution Non-commercial Share-alike 
  (By-<abbr>NC</abbr>-<abbr>SA</abbr>) license</a>.
</small>

This article is licensed under a Creative Commons Attribution Non-commercial Share-alike (By-NC-SA) license.

A rel-license-formatted code sample with an example rendering

This may be so easy you don’t even realise you’ve just microformatted the link! In fact, Google already uses this data to allow us to search by license (look in , in the extra options).

Google advanced search options, showing the “Usage rights” pulldown

Using XHTML Friends Network (XFN)

Maybe we should term this one eXtensible Friends Network instead :-) XFN is a way of specifying your relationship with people — everything from “met” to “sweetheart” — using the rel attribute on a link to their homepage.

There are two main values: rel="contact" for someone you know how to get in touch with, and rel="me". The rel="me" value allows you to claim ownership of your various websites, including your accounts on social networks. For example, I could have a profile with a link to my Twitter account:

<p>Oli Studholme — <a href="http://twitter.com/boblet">follow me on
  Twitter (@boblet)</a></p>

A person can infer that @boblet is my Twitter username, but by adding rel="me" we can state this relationship in a machine-readable way.

<p>Oli Studholme — <a rel="me" href="http://twitter.com/boblet">follow me on
  Twitter (@boblet)</a></p>

In order to actually work, this would need to be on my personal homepage, with the same homepage added to my Twitter profile. By doing this, a social web app that understands XFN could confirm @boblet is me, check my friends on Twitter, check if those people are already registered, and then allow me to follow them all with one click — much easier.

For more on this idea, check out Identity consolidation and the XFN rel="me" value, the RelMeAuth proposal on the microformats wiki, and Google’s Social Graph API. It seems Facebook is supporting rel="me" too.

Rel-license and XFN are simple rel-based microformats, but even with their simplicity you can see the potential power in this machine-readable stuff. Now let’s look at microformats for contact and event information.

Using hCard for contact information

Almost every website has an about page with some contact information:

<p>Oli Studholme — <a href="http://oli.jp/">http://oli.jp</a>, or 
<a href="http://twitter.com/boblet">follow me on Twitter (@boblet)</a>.</p>

Unfortunately, adding someone’s contact information to your phone or address book generally involves a lot of copying and pasting. If the data was machine-readable, however, we could use a tool to do that. Let’s add the hCard microformat to this code snippet.

<p class="vcard"><span class="fn">Oli Studholme</span> — 
<a class="url" href="http://oli.jp/">http://oli.jp</a>, or 
<a class="url" href="http://twitter.com/boblet">follow me on Twitter 
(@<span class="nickname">boblet</span>)</a>.</p>

Oli Studholme — http://oli.jp, or follow me on Twitter (@boblet).

An hCard-formatted code sample with an example rendering

So we’ve added a bunch of classes. There’s nothing special about that, of course, until you realise they're all part of the hCard microformat. The first one is vcard on the containing <p> element, indicating that there's hCard data here. Then we have fn, which stands for full name, url for an associated homepage, and nickname for, well, a nickname.

This is a simple example, and in fact a valid hCard (generally) only requires vcard and fn. But hCard has much more depth. We can mark up all kinds of contact-related data: addresses, company information, even a profile photo. For example, we can explicitly specify a given name and family name (this is required for Chinese, Korean, Japanese and Vietnamese names), even middle names and titles.

<span class="vcard"><span class="fn n" lang="ja"><span class="family-name">
スタッドホルム</span>・<span class="given-name">オリ</span></span></span>

The additional n value is actually required, but can be inferred (the so-called “implied n optimisation”) and therefore omitted for names that follow these patterns:

  • given-name family-name
  • family-name, given-name

So what’s the benefit of this? Well, there are several tools that will convert this hCard-microformatted data into a vcard file we can download and automatically add to our address book. Nifty!

The Firefox Operator plugin’s hCard export options
The Firefox plugin Operator can save hCard-formatted content as a vcard, or add it to Yahoo Contacts

It’s also recognised by Google’s Rich Snippets and Yahoo’s SearchMonkey, useful for the contact information on any company website.

A preview of how rich snippet data may be incorporated into Google’s search results—in this example “Osaka” and “designer” Microformat hCard data extracted by the Google Rich Snippet testing tool
Google’s Rich Snippet testing tool for an hCard (Note the “Osaka - designer” in the search preview)

Organisations, addresses, and phone numbers

Smaller company websites often have the company name and contact details in the footer, so let’s briefly see how to do that.

<p class="vcard">
<a class="fn org url" href="http://www.w3.org/Consortium/contact-keio" title="Contact Information for W3C/Keio"><span class="organization-name">W3C</span>/<span class="organization-unit">Keio</span></a><br>
<span class="adr"><a class="extended-address" href="http://www.keio.ac.jp/english/about_keio/campus_info/sfc1.html">Keio University Shonan Fujisawa Campus</a><br>
<span class="street-address">5322 Endo</span>, <span class="locality">Fujisawa city</span>,<br>
<span class="region">Kanagawa prefecture</span> <span class="postal-code">252-8520</span> <b class="country">Japan</b><br>
<span class="tel">Telephone: <span class="value">+81-466-49-1170</span></span><br>
<span class="tel"><span class="type">Fax</span>: <span class="value">+81-466-49-1171</span></span></span>
</p>

W3C/Keio
Keio University Shonan Fujisawa Campus
5322 Endo, Fujisawa city,
Kanagawa prefecture 252-8520 Japan
Telephone: +81-466-49-1170
Fax: +81-466-49-1171

A microformatted example company hCard, complete with address, and a sample rendering

By using fn together with org we can create an hCard for an organisation. Each part of the address is specified (<span>licious!), and we’ve also included a phone number (tel’s default type is voice) and fax number (specifying type and using the value class pattern).

A preview of how rich snippet data may be incorporated into Google’s search results—in this example “Kanagawa Prefecture” and “W3C” Microformat hCard data extracted by the Google Rich Snippet testing tool
Google’s Rich Snippet testing tool for an organisation hCard (note the address and organisation info in the search preview)

And with Operator, we can add this hCard to our computer’s address book in one click. If you’ve ever manually added an address to your address book, you’ll love this ;-)

Exporting an hCard to your computer’s address book via Operator An hCard exported by Operator is automatically added to the address book
Adding hCard-formatted contact information to your address book with one click

Using hCalendar for event information

Let’s briefly look at marking up a simple event. Here’s one I’m involved with:

<h3><a href="http://atnd.org/events/5181">WDE-ex Vol.11 —
  Designing for iPad: Our experience so far</a></h3>
<p>July 21st 19:00-20:00 at 
<a href="http://www.apple.com/jp/retail/ginza/map/">Apple Ginza</a>.</p>

Just by reading, we understand the event name, date, time, and location. But this information is difficult for computers to extract. By using the hCard microformat, it will be machine-readable.

<div class="vevent">
  <h3><a class="url summary" href="http://atnd.org/events/5181">
  WDE-ex Vol.11 — Designing for iPad: Our experience so far</a></h3>
  <p><span class="dtstart"><abbr class="value" title="2010-07-21">
  July 21st</abbr> <span class="value">19:00</span></span>-
  <span class="dtend"><span class="value">20:00</span></span> at 
  <a class="location url" href="http://www.apple.com/jp/retail/ginza/map/">
  Apple Ginza</a></p>
</div>

WDE-ex Vol.11 — Designing for iPad: Our experience so far

July 21st 19:00-20:00 at Apple Ginza

Example hCard-formatted event, including a sample rendering

We’ve added vevent on a wrapping element to indicate this is an hCalendar. Events are required to have a summary and a starting time, so we’ve added summary and indicated the starting date and time using dtstart. While historically datetimes were indicated using <abbr title="">, the required ISO 8601 format (for example “2010-07-10T19:01:29”) is very unfriendly to screen readers. Imagine having those numbers read to you! For this reason, the hCalendar specification recommends either breaking the datetime into separate date and time pieces, using the value class pattern, or possibly doing both. The specification is also smart enough to know that if the end datetime dtend is only a time, then it’s on the same day, so we don’t need to specify the date again, although tool support for this is spotty. Finally, we’ve added some URLs, one of which is for the event’s location.

The Firefox Operator plugin’s debug window, showing information about the current hCalendar
The Firefox plugin Operator’s debug view, showing the microformat properties it has recognised

With this data now being machine-readable, we can do things with it. For example, we can add the event to a calendar app with one click.

The Firefox Operator plugin’s options for hCalendar-formatted content
Operator can save hCalendar-formatted content as an ical file (for easy importing into your address book software), or add it to various online calendars

Using microformats in HTML5

So now we’ve had a whistle-stop introduction to microformats and gotten a glimpse of the benefits they provide. The question is: Can we use them in HTML5 pages? Let’s start with the good news.

As most microformats use only class and/or rel — basic parts of HTML that remain unchanged in HTML5 — these microformats are completely fine in HTML5. Yay! However there are a few wrinkles to keep us on our toes.

The profile attribute

The profile attribute is obsolete in HTML5, as it was determined unnecessary. Currently, microformat profiles are very rarely used in the wild and are not required, so this probably won’t affect you.

Microformats specifications vs HTML5

While microformats using class and rel work fine, some of the new features in HTML5 aren’t supported yet. The Microformats in HTML5 page on the microformats wiki currently begins:

This page is to document future use of microformats in HTML 5. None of the items documented are supported now, and may change upon proper development within the microformats community, or changes in the HTML 5 specification.

This includes the nifty new <time datetime=""> element, which would be perfect for microformat times, such as dtstart and dtend in the hCalendar microformat. It’s also true for adding microformats via microdata rather than class and rel. There has been talk of a general way to map any microformat into microdata, but this hasn’t eventuated as of yet.

Microformats-consuming tools (or, the problem with HTML Tidy)

The microformats wiki’s warning about <time> brings us to another caveat: tool support. Even if <time datetime=""> was valid in the microformats spec, at present most of the microformats tools can’t get this information from the datetime="" attribute. Now, you could wrap <time datetime=""> around a microformats dtstart or dtend:

<time datetime="2010-07-21T19:00:00+09:00"><span class="dtstart">
  <abbr class="value" title="2010-07-21">July 21st</abbr>
  <span class="value">19:00
</span></span></time>

However, as the <time datetime=""> data is then not explicitly part of the microformat, doing this isn’t really getting you anywhere, except bloated code-ville.

The problem is actually way worse as many tools use the parser HTML Tidy (“last updated March 2009”!), which probably won’t be fixed for new HTML5 elements. This means any microformats classes on new HTML5 elements will be ignored. The potential alternative html5lib.php is still pretty young. You can get around this by wrapping HTML5 elements in <div>s and <spans> and applying the microformats classes to them, but that’s hardly ideal.

However, there’s a ray of sunshine here. The tool you’ll most want to use is H2VX.com — it converts hCard and hCalendar microformats into vcard and ical files for users to download and add to their address books and calendars, respectively. While h2vx.com uses Tidy, Tantek Çelik and Brian Suda (the maintainers of H2VX) have a version of H2VX that does work with HTML5 elements and <time>’s datetime attribute. We’re saved! Check it out at dev.h2vx.com.

Microformats Tool support

OperatorOptimush2vx.comdev.h2vx.com
can use classes on HTML5 elementsyesyesnoyes
supports HTML5’s <time>nononoyes
Understands the value class patternyesnoyesyes
Understands implied dtendyesnoyesyes
Understands timezonesyesyesyesyes

I didn’t expect anyone to support <time> until it became part of a microformat specification. Given how … non-micro expressing datetimes is in microformats currently, I am very thankful H2VX has in dev.h2vx.com!

Conclusion

So where does that leave us? Well, if you keep the above caveats in mind you can safely use microformats in HTML5. Google has no problem with microformats in HTML5, even on new elements, and I’m under the impression that Yahoo is the same. However, remember that if you want to offer a “click to download” link via H2VX, you’ll have to use dev.h2vx.com.

An important thing to note about microformats: as wonderful as they are, the current method of using the plain old semantic HTML tools of class, rel, and coding patterns is something of a brilliant hack. The use of class (an author playground) and the lack of use/demise of profile, combined with the complexity of coding to detect for microformats in the wild, means that native browser support is unlikely anytime soon. There was the expectation that at some stage there’d be a better way to easily add extra semantic information for others to use. In future articles, we’ll look at microdata and RDFa, and see what they have to offer over plain old semantic HTML.

If you have common types of data in your content that are covered by a microformat, and you want to make them machine-readable for others (and who wouldn’t), you should definitely consider using microformats in HTML5. Adding microformats is basically adding a lightweight API to your content, and is simple enough that even a designer can do it! This helps search engines and savvy users to more easily use your content. Check out the microformats wiki, grab the indispensable microformats cheat sheet by Brian Suda, peruse these books and DVDs on microformats, and start getting (even more) semantic!

Books and DVDs

Changes

  1. Minor copyedits and the major addition of dev.h2vx.com support, with thanks and apologies for the delay to Brian Suda and Tantek Çelik.

Extending HTML5 — Microformats originally appeared on HTML5 Doctor on August 17, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/microformats/feed/ 30
The ruby element and her hawt friends, rt and rp https://stevefaulkner.github.io/html5doctored/ruby-rt-rp-element/ https://stevefaulkner.github.io/html5doctored/ruby-rt-rp-element/#comments Tue, 11 May 2010 14:00:55 +0000 http://html5doctor.com/?p=1745 The <ruby>, <rt> and <rp> elements allow us to add ‘ruby’ phonetic annotations in languages like Japanese and Chinese. Despite the terrors of internationalisation and patchy browser support — with a little fiddling and a lot of caution — this sexy threesome with adorable accents are ready to use now.

]]>
Ruby text is a short annotation for some base text. It’s typically used to give pronunciation guidance in a phonetic script for kanji in Chinese, Japanese, and Korean (CJK) languages. It’s named after an old printers’ term for the very small size of 5.5 points.

The ruby element allows spans of phrasing content to be marked with ruby annotations.

W3C Specification

As the name implies, ruby text is small, displayed by default above the base text in horizontal text and to the right in vertical text. Browsers without <ruby> support put the ruby text inline after the base text.

These are the elements used in creating ruby text in HTML5:

  • <ruby> — an inline element that contains base text with ruby annotations
  • <rt> — ruby text, coming after the base text it defines
  • <rp> — ruby parentheses, an element used to wrap opening and closing parentheses around <rt> ruby text. These are for user agents that don’t support ruby text, so that it makes sense when displayed inline. Browsers that support <ruby> hide <rp> via {display:none;}.

Examples

If you’ve never seen ruby in action you’re probably wondering what I’m talking about, so here are some examples:

Vagabond
Furigana ruby text in the Japanese manga Vagabond
Bopomofo Newspaper
Snippet of a Taiwanese newspaper for students, with bopomofo ruby
Typical Korean usage of hanji in a Korean news website
Korean hangul followed by hanja in an editorial on Chosun.com

Browser support

As is often the way with internationalisation features, browser support is — well, sparse. In a break from your expectations, Internet Explorer has supported <ruby> since IE5 — three years before the actual 2001 W3C Ruby Annotation specification! While this specification was incorporated into XHTML 1.1, no browser ever implemented it.

<ruby> in HTML5 is based on a reverse-engineering of IE’s implementation. It also lacks Ruby Annotation’s ‘complex <ruby>’, as these can normally be accomplished via nesting. (Please submit feedback if you have a real-world example that can’t be.) Webkit added HTML5 <ruby> support at the start of 2010. At the time of writing, <ruby> has made it into Chrome but not Safari. Firefox and Opera have yet to implement <ruby> natively, although there are Firefox extensions for <ruby> support (HTML Ruby (basic ruby including HTML5) and XHTML Ruby (complex ruby)).

On the styling side, there’s the W3C CSS3 Ruby Module (2003). It’s based on Ruby Annotation’s ‘complex ruby’ and is being updated for HTML5 <ruby>. Because of this, it’s also yet to be implemented beyond the default IE-level formatting. Ruby text will be used in combination with the W3C CSS Text Layout Module Level 3 properties direction, block-flow, and writing-mode for alternative text flow (such as vertical text), but again these have .

Summary of browser support for <ruby> display & styling in the five main browsers
Browser Basic <ruby> writing-mode ‘Complex <ruby>’ CSS3 Ruby (2003)
Internet Explorer IE5.5+ IE6+* - -
Firefox (via plugin) - (via plugin) -
Chrome Chrome5+ - - -
Safari Safari5+ - - -
Opera - - - -

Note: writing-mode support in IE6 was lr-tb and tb-rl only. IE8 added support for all possible combinations.

CSS we can use

Having said that no browsers support the CSS3 Ruby module yet, there are still a few things we can do to style <ruby> and friends. Default browser styles use font-size and display, so we can safely change these to affect display in both supporting and non-supporting browsers.

If you want to de-emphasise the <rt> ruby text when it’s displayed inline in non-supporting browsers, you could do this via setting the size of <rt> and <rp>, as IE and Webkit do:

rt, rp {font-size: 60%;} /* = Webkit value */

You can also move ruby text and parentheses to after the base text, mimicking non-supporting browser rendering on supporting browsers:

rt, rp {display: inline; font-size: 100%;}

Finally, if you’re brave/foolish, you can implement ruby display yourself via CSS inline-table (CSS with explanation and demonstration (Hiragana.jp)). Note that this currently doesn’t work in Chrome because of a bug with display:inline-table on <ruby> (fixed in trunk), and as you’ll probably need per-browser style tweaks, I recommend against it.

Code samples and output

These code samples (with notes and CSS) are also available separately.

<ruby> in Japanese — furigana and rōmaji

Using <ruby> without <rp>

<ruby>攻殻<rt>こうかく</rt>機動隊<rt>きどうたい</rt></ruby>
Furigana example using ruby in a supporting browser (displayed above base text) Furigana example using ruby in a non-supporting browser (displayed inline after base text)
Using <ruby> to indicate the pronunciation of the Japanese name of the Ghost in the Shell anime series in furigana. Notice that the lack of <rp> makes it pretty unreadable in a non-supporting browser (you may have to trust me on this!).

Using <ruby> with <rp>

<ruby>攻殻<rp>(</rp><rt>こうかく</rt><rp>)</rp>機動隊<rp>(</rp><rt>きどうたい</rt><rp>)</rp></ruby>
Furigana example using ruby in a supporting browser (displayed above base text) Furigana example using ruby in a non-supporting browser (displayed inline with parentheses)
The above example with <rt> text surrounded by <rp> parentheses degrades gracefully on non-supporting browsers.

Nested <ruby> for multiple ruby texts

<ruby><ruby>攻<rp>(</rp><rt>こう</rt><rp>)</rp>殻<rp>(</rp><rt>かく</rt><rp>)</rp>機<rp>(</rp><rt>き</rt><rp>)</rp>動<rp>(</rp><rt>どう</rt><rp>)</rp>隊<rp>(</rp><rt>たい</rt><rp>)</rp></ruby><rp>(</rp><rt>Kōkakukidōtai</rt><rp>)</rp></ruby>
Two ruby texts in a supporting browser (both displayed above base text) Two ruby texts in a non-supporting browser (displayed inline in source order)
The scope of <rt> depends on the amount of base text before it, from one character to an entire phrase. <ruby> can also be nested to provide multiple ruby texts for one base text — in this case furigana and rōmaji. Although per-kanji <ruby> is more informative, it degrades somewhat poorly in non-supporting browsers. Copy & paste support is also poor, as browsers just use source order, for example “攻こう殻かく機き動どう隊たい Kōkakukidōtai”. It’s also a PITA to code :-|

Japanese glossary

Furigana is the name given to using hiragana phonetic script beside words written in kanji to aid reading. It’s used extensively in education for learners of Japanese, and in reading material for children. It’s also sometimes used when writing kanji a literate adult may not be able to read.

Rōmaji is the romanisation of Japanese into the latin alphabet. Rōmaji is generally used for those who don’t know Japanese, especially in signage and tourism information.

<ruby> in Chinese — Pīnyīn and zhùyīn fúhào (bopomofo)

Ruby is used to some extent in China (pīnyīn), and more so in Taiwan (zhùyīn fúhào), especially in textbooks and signage.

Pīnyīn

<p>The <b>Grass mud horse</b> — <ruby>草泥馬<rp>(</rp><rt>Cǎo Ní Mǎ</rt><rp>)</rp></ruby> — is … characterised as “lively, intelligent and tenacious”. However, their existence is said to be threatened by the “river crabs” — <ruby class="styled">河蟹<rp> (</rp><rt>héxiè</rt><rp>) </rp></ruby> — which are invading their habitat.</p>
Ruby text in a paragraph of text in a supporting browser, leading to significant line-height differences Ruby text in a non-supporting browser, with font-size set on rt and rp elements for the second ruby instance
In this example of pinyin you can see how <ruby> significantly affects the leading (<line-height>) of text blocks in supporting browsers. Setting font-size for <rt> and <rp> can de-emphasise ruby text in non-supporting browsers, as demonstrated in the second <ruby> in the second image.

Zhùyīn fúhào

<ruby><ruby>世<rp>(</rp><rt>ㄕˋ</rt><rp>)</rp>上<rp>(</rp><rt>ㄕㄤˋ</rt><rp>)</rp>無<rp>(</rp><rt>ㄨˊ</rt><rp>)</rp>難<rp>(</rp><rt>ㄋㄢˊ</rt><rp>)</rp>事<rp>(</rp><rt>ㄕˋ</rt><rp>)</rp>只<rp>(</rp><rt>ㄓˇ</rt><rp>)</rp>怕<rp>(</rp><rt>ㄆㄚˋ</rt><rp>)</rp>有<rp>(</rp><rt>ㄧㄡˇ</rt><rp>)</rp>心<rp>(</rp><rt>ㄒㄧㄣ</rt><rp>)</rp>人<rp>(</rp><rt>ㄖㄣˊ</rt><rp>)</rp></ruby><rp> (</rp><rt>Anything can be done with enough perseverance</rt><rp>)</rp></ruby>
How this bopomofo *should* look in a supporting browser (which doesn’t exist as far as I know) This bopomofo example in Chrome This bopomofo example in Firefox
Unfortunately, no browser can render this example of Zhùyīn fúhào (bopomofo) ruby on horizontal Mandarin Chinese correctly. I’ve included an ideal rendering and how it appears in both a browser supporting simple ruby (with incorrectly rendered bopomofo) and a non-supporting browser.

Chinese glossary

Pīnyīn is a romanised phonetic system for Chinese, generally written above or after the word. Bopomofo (Zhùyīn fúhào) is a phonetic script for transcribing Chinese, especially Mandarin. It is generally written (in both horizontal and vertical scripts) vertically to the right of each hanzi character.

Korean ruby

While the use of hanja (kanji) is decreasing in South Korea, they are still used for disambiguation and proper names.

<ruby>한자<rp>(</rp><rt>漢字</rt><rp>)</rp></ruby>
Hangul followed inline by hanja in brackets
Current Korean ruby use is to have the hangul coming before the hanja in parentheses (the opposite way from the default fallback style). For styling use: rt, rp {display: inline; font-size: 100%;}. This formatting is also used when foreign words such as English are included in Korean text.

Korean glossary

Hangul is the Korean script, and hanja is Korean for Chinese characters. Traditionally written Korean used hanja, but now it’s mainly used in academic texts and occasionally for disambiguation.

Using <ruby> for English

Not everyone is using East Asian languages, but any short annotation is (theoretically) applicable. While English doesn’t typically have pronunciation guidance, phonetic annotations are used in dictionaries:

<ruby><strong>cromulent</strong> <rp>(</rp><rt>crôm-yü-lənt</rt><rp>)</rp></ruby>
Displaying ruby text after the base text for an English dictionary
Using ruby text for a dictionary definition by displaying the ruby text inline after the base text

<ruby>: to use or not to use

The main use case of <ruby> is marking up pronunciation in Asian writing, such as bopomofo for traditional Chinese and furigana for Japanese. I don’t know whether Arabic diacritics like Taškīl, Hebrew Niqqud, or other non-CJK languages would use <ruby> for marking up phonetic annotations or diacritics. The WHATWG specification says:

Ruby annotations are short runs of text presented alongside base text, primarily used in East Asian typography as a guide for pronunciation or to include other annotations

As someone who uses tools like Popjisyo to add pop-up readings and translations to kanji, I definitely see <ruby> as semantic (and valuable) for ‘phonetic annotation,’ in the same way that <abbr> provides extra information on potentially confusing content. Outside of this usage, however, <ruby> could be seen as a presentational hack. Oh noes! I believe the Korean and English examples above are valid uses, but much like <q> some people think the extra code of using <ruby> is not justified when the default presentation is the same as plain text.

To further muddy the waters, the 2001 W3 Ruby specification included an abbreviated word marked up with a visible definition via <ruby>, and a use-by date where the day, month, and year are added via <ruby>. These uses seem like presentational hacks to me, and while they’re not forbidden, the lack of such examples in HTML5 indicate they’re not exactly blessed either ;-)

In conclusion…

The most important thing is that the <ruby>, <rt>, and <rp> elements are valid HTML5, and even if they’re not officially supported, they will by default display as if they were <span>s in non-supporting browsers. Because of this, if you actually need to use <ruby>, especially for phonetic annotations, do it! It might not look perfect yet in non-supporting browsers, but this will change, and hey, at least you don’t have IE support to worry about! ;-)

For non-phonetic annotation, consider using <abbr> to give an expanded reading via mouse-over for an abbreviation or acronym, unless displaying the reading by default is important. Consider <small> for phrasing content-level side comments, if the comment placement is not important and the association with the relevant content doesn’t need to be explicit.

Further reading

Feedback please!

So what do you think of <ruby> and friends? Let us know in the comments! If you know about the use of annotations like this in other languages, or have used <ruby>, tell us about it too!

The ruby element and her hawt friends, rt and rp originally appeared on HTML5 Doctor on May 11, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/ruby-rt-rp-element/feed/ 31