tm

Anatomy of an HTML5 WordPress theme

This site has been written in HTML5 and used to use WordPress to manage the content. I’ll explain why I used HTML5, describe the structure of the theme templates, and show some of the ways I tried to tame WordPress’s tendency to add mess to the source code.

As this is my personal site I wanted to experiment with using HTML5, CSS3, and WAI-ARIA. All these documents are currently working drafts and subject to change. However, the web documents and applications of the future are going to be written in HTML5 and I wanted to see the benefits of using it to markup static documents. Using CSS 2.1, let alone the CSS3 selectors and properties that some browser vendors have implemented, has many advantages for controlling the presentation of semantically coded documents. For this reason I am not going to avoid using basic CSS 2.1 selectors just to faithfully reproducing this site’s design in IE6. However, I have tried to accommodate IE 7 and IE 8 users by using an HTML5 enabling script so that the new HTML5 elements can be styled in those browsers if users have Javascript enabled.

HTML5 templates

I started with a static prototype of this site developed on my local server. WordPress makes it very easy to create your own templates and, therefore, it is no problem to use HTML5. This theme only has 3 main templates: index, single, and archive. There are of course templates for 404s, attachments, comments, etc., but I won’t discuss them as they are all based on the 3 main templates. All the templates include ARIA roles as an accessibility aide.

The single.php template has this rough structure:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="default.css">
</head>

<body>
  <header role="banner"></header>
  <nav role="navigation"></nav>
  <article role="main">
    <header>
      <time datetime="YYYY-MM-DD"></time>
      <h1></h1>
    </header>
    <footer></footer>
  </article>
  <nav></nav>
  <aside role="complementary"></aside>
  <footer role="contentinfo">
    <small></small>
  </footer>
</body>
</html>

The first line of the document is the HTML5 DOCTYPE. The new <article> element contains the content of each post. The same structure is used for the index.php template except that there are several articles displayed on each page and the ARIA role value of main is not used. In contrast, the archive.php template houses all the article excerpts in a <section> element with the ARIA role of main because the list of archived posts is itself the main content of the document.

A clean theme

WordPress tends to add classes, elements, and other bits of code in certain places. I haven’t used any of the WordPress functions that add class names to the body and to elements wrapping a post and also wanted to avoid cluttering the source code with any other unnecessary markup. This required a bit of fiddling around with the theme’s functions.php file. I’m not a PHP developer so this might not be pretty!

Removing actions from wp_head()

WordPress has a hook called wp_head that sits in the header.php of most themes. To avoid it inserting unwanted code into the <head> of the document I used the remove_action function to disable the functions that were responsible. The following code was added to the functions.php file of my theme:

// Remove links to the extra feeds (e.g. category feeds)
remove_action( 'wp_head', 'feed_links_extra', 3 );
// Remove links to the general feeds (e.g. posts and comments)
remove_action( 'wp_head', 'feed_links', 2 );
// Remove link to the RSD service endpoint, EditURI link
remove_action( 'wp_head', 'rsd_link' );
// Remove link to the Windows Live Writer manifest file
remove_action( 'wp_head', 'wlwmanifest_link' );
// Remove index link
remove_action( 'wp_head', 'index_rel_link' );
// Remove prev link
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
// Remove start link
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
// Display relational links for adjacent posts
remove_action( 'wp_head', 'adjacent_posts_rel_link', 10, 0 );
// Remove XHTML generator showing WP version
remove_action( 'wp_head', 'wp_generator' );

Source: WPEngineer.com: Cleanup WordPress Header

Removing an empty <span>

If you want to create excerpts you can either write them into the excerpt box or use the <--more--> quicktag in the WordPress editor. I just wanted the first paragraph of my posts to be used as the excerpt and so using the in-editor tag was the most practical approach I was aware of. However, when you do this WordPress will insert an empty <span> in the post’s content. This element has an id so that the area following the excerpt can be targeted by “more” or “continue reading” links. I removed both the empty <span> and the jump link by adding the following code to the functions.php file of the theme:

// removes empty span
function remove_empty_read_more_span($content) {
  return eregi_replace("(<p><span id="more-[0-9]{1,}"></span></p>)", "", $content);
}
add_filter('the_content', 'remove_empty_read_more_span');

Source: Ganda Manurung: Remove Empty Span Tag On WordPress

// removes url hash to avoid the jump link
function remove_more_jump_link($link) {
  $offset = strpos($link, '#more-');
  if ($offset) {
    $end = strpos($link, '"',$offset);
  }
  if ($end) {
    $link = substr_replace($link, '', $offset, $end-$offset);
  }
  return $link;
}
add_filter('the_content_more_link', 'remove_more_jump_link');

Source: WordPress Codex: Customizing the Read More

Displaying images in the excerpt

For posts that display nothing but a photograph (yes, they will be shit but I’m hoping it gets me using my camera a bit more often) I wanted the image to show up in the archives. Equally, if the first paragraph of a post contained a link I wanted that to be preserved. The default the_excerpt() template tag doesn’t allow for this so it needed some modifying. I added a new function, which is just a modified version of the core excerpt function, to the functions.php file and then made sure that the template tag executed this function rather than the one contained in the core WordPress files.

function improved_trim_excerpt($text) {
   if ( '' == $text ) {
      $text = get_the_content('');
      $text = strip_shortcodes( $text );
      $text = apply_filters('the_content', $text);
      $text = str_replace(']]>', ']]&amp;gt;', $text);
      $text = strip_tags($text, '<p><img><a>');
      $excerpt_length = apply_filters('excerpt_length', 55);
      $words = explode(' ', $text, $excerpt_length + 1);
      if (count($words) > $excerpt_length) {
         array_pop($words);
         array_push($words, '[...]');
         $text = implode(' ', $words);
         $text = force_balance_tags($text);
      }
   }
   return $text;
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'improved_trim_excerpt');

Source: Aaron Russell: Improving WordPress’ the_excerpt() template tag

I prefer not to have empty elements in the markup and so I needed a way to conditionally insert the “Older entries”, “Newer Entries”, etc., links into templates. The solution I’m using here, which isn’t perfect, is to add this to functions.php:

function show_posts_nav() {
  global $wp_query;
  return ($wp_query->max_num_pages > 1);
}

Source: Eric Martin: Conditional navigation links in WordPress

And then to wrap the navigation markup in the templates with the following:

<?php if (show_posts_nav()) : ?>
<nav>
   <ul>
      <li><?php next_posts_link('&#171; Older Entries') ?></li>
      <li><?php previous_posts_link('Newer Entries &#187;') ?></li>
   </ul>
</nav>
<?php endif; ?>

Summary

It’s fairly easy to create a simple site with HTML5 and to use WordPress to deliver it. At the moment there are issues with Internet Explorer because you cannot style HTML5 elements unless you use Javascript. However, HTML5 redefines the meaning of certain elements (such as <dl>, which has become a more versatile “description list”) and allows block elements to be wrapped in a link. Therefore, there is still benefit in using the HTML5 DOCTYPE even if you do not make use of the new elements.

Further reading

  1. HTML5 working draft
  2. HTML5 differences from HTML4
  3. Accessible Rich Internet Applications (WAI-ARIA) 1.0




tm

Thoughts on some new HTML5 elements

In the last few months there has been increased discussion about some of the new elements that have been introduced in the HTML5 draft specification. This entry is primarily a counter argument to some of the comments that I disagree with.

The most recent and high-profile comments in regard to parts of the HTML5 specification come from The HTML5 Super Friends in an article entitled Guide to HTML5 Hiccups. It lays out their concerns with the HTML5 draft specification as it stood at the time of its writing and I am largely going to focus on the issues they have discussed.

The article and section elements

The first argument that I disagree with is that the article and section elements are redundant and, therefore, that the article element should be dropped.

article and section are identical except that article allows a pubdate attribute. We would suggest that article be dropped and section be adapted to allow an optional pubdate attribute or, even better, more explicit metadata.

The article and section elements are not identical according the to HTML5 draft specification. Here is what it says about the section element as of 13 September 2009:

The section element represents a generic document or application section. A section, in this context, is a thematic grouping of content, typically with a heading, possibly with a footer.

Now contrast that with what it says about the the article element:

The article element represents a section of a page that consists of a composition that forms an independent part of a document, page, application, or site.

An article element is “independent” in the sense that its contents could stand alone, for example in syndication, or as a interchangeable component on a user-configurable portal page.

That is a clear distinction that resists the reading of article and section being “identical”. The article element has a specific purpose: to mark parts of a document that form an independent composition that may be appropriate for syndication. It is a special kind of sectioning element that performs an essential role that is lacking in the semantics of the generic section element. This generic element serves only to thematically group content. That grouping may occur at the document level, within an independent article, or within a footer.

The article element has unique semantics and practical use. There is a fundamental conceptual difference between stand-alone compositions and sections of compositions, documents, or pages and this difference should be recognised and catered for in the specification. Websites regularly employ microformats and you don’t have to look far to see independent compositions currently marked up with class="hentry" or find links to individual blog comments and twitter updates. There is clearly a need for an easy way to define independent compositions and that is met with the introduction of the article element in HTML5.

What may be needed is a stronger clarification and definition of the article element to minimise the potential for this distinction to be overlooked and to highlight the differences from a generic document section.

The hgroup element

The hgroup element is a relatively recent addition to the draft specification. It is defined as serving a fairly specific purpose:

The hgroup element represents the heading of a section. The element is used to group a set of h1h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines.

The element works to associate headings together so that the highest ranked heading descendant (if present) of the hgroup element is used as its text in document outlines and summary. Other heading descendants are treated as subheadings and are left out of outlines.

The HTML5 Super Friends have this to say about the hgroup element:

We don’t see the added value of this element and would instead add a boolean attribute to the heading element which allows content authors to specify if that particular heading should be included in the outline.

Bruce Lawson has similar concerns and proposes another alternative – removing the need for a wrapping element and defining a new element specifically for marking up subtitles:

I agree that hgroup is clumsy and likely to be misused. Rather than wrap an h1 and its h2 subtitle in hgroup to keep the subtitle out of the outlining algorithm, I would prefer to use

<header>
<h1>My blog</h1>
<subtitle>My wit and wisdom</subtitle>
</header>

as I think that;s easier to understand than a heading-that’s-not-a-heading, and it removes a wrapping element.

I disagree with these criticisms of the hgroup element and consider the proposed alternatives to be more problematic, less intuitive, less flexible, and further removed from the way in which authors currently markup subheadings.

The way that many authors are currently marking up subheadings is by using headings of various ranks and in various orders depending on whether the subheading or qualifying heading needs to appear above or below the main page heading. A subheading is still, conceptually, a heading of sorts and it cannot be accurately marked up with a paragraph or any other currently available element.

Allowing the addition of a boolean attribute to heading elements has several problems.

  1. A boolean attribute may be less intuitive for authors than the hgroup element. The hgroup element relies upon and produces an association between all the headings it contains. Since headings and subheadings occur together and derive their meaning from each other, it is semantic to wrap these headings in an element. We know that the highest ranked heading contains the string to be used in the outline and that the other headings serve as ranked subheadings to this primary heading. A boolean attribute is only associated with the element that it is a part of. We can create no association between the element and adjacent elements. This is related to the next issue.

  2. The hgroup itself acts as heading content while a boolean attribute would act only to remove headings from the outline. The hgroup element only removes the descendant headings that are those not of the highest rank. The boolean attribute shifts the burden onto the author to decide which headings should be marked for removal from the outline, rather than providing an element to wrap a collection of headings without authors having to be concerned with (or aware of) issues of outlining.

What about Bruce Lawson’s idea for a subtitle element? I believe that, irrespective of the what this element were actually called, it suffers from similar problems to the idea of using a boolean attribute. There is nothing to prevent the use of a subtitle element away from a heading, it creates no association with other elements, and it does not allow for ranking of subheadings.

One of my key points in relation to criticism of the hgroup element is that subheadings draw their meaning from context. A subheading (as opposed to a section heading) is only a sub-heading if it is associated with a higher ranking heading. Remove the higher ranking heading and what was once a subheading is likely to be understood as a heading.

The strength of the hgroup element over the two alternative suggestions I have referenced is that it is the only proposal that defines a subheading as contextual. I think that it is the most intuitive proposal (although perhaps none of them are particularly inuitive) – the name of the element is self-descriptive and encapsulates the contextual relationship and adjacent positioning of its child elements — and matches most closely with the way that subheadings are currently marked up on many websites.

The aside element

The HTML5 Super Friends are of the opinion that the aside element is not worth including in the specification:

The use cases for aside are too limited to warrant its inclusion in the specification. We were also concerned about potentially duplicating content within an aside.

However, the specification itself provides some fairly compelling uses for the element:

The element can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page.

Authors might use the aside element for their blogrolls, for marking up adverts ranging from google ads on blogs to large banners on enterprise websites, for expanding on themes within an article or providing an extended definition of a term, for pull quotes, and anything else “tangentially related to the content around the aside element, and which could be considered separate from that content”.

Most of these uses would not involve duplication of content. Using the aside element for pull quotes would produce some instances of content duplication. However, this is not really a problem for users who are used to content being duplicated in this way in newspapers and magazines. It would not take much for search engines to adapt to deal with short amounts of duplicate content contained within an aside either. While I appreciate the point about duplicate content I’m not yet convinced that it is actually problematic.

The legend element

The current specification defines the legend element as providing an explanatory caption for the contents of its parent element. The parent element may be a fieldset, figure or details element. However, Remy Sharp‘s article entitled legend not such a legend anymore shows why it is not practical to use legend for the new elements details and figure – because it is not backwards compatible with current browsers and effectively unusable outside of a fieldset because of the inability to style the element.

In this case, forging a new element is most appropriate rather than trying to use an element like label which will only create confusion with little advantage.

Summary

I have discussed my reasons for disagreeing with certain feedback on the HTML5 draft specification. I have yet to be convinced that the article, hgroup, or aside elements should be dropped from the specification because it seems to me that they have necessary uses and advantages over alternatives.




tm

New HTML5 elements: summary & figcaption

Over the weekend two new HTML5 elements – summary and figcaption – were added to the draft specification. The introduction of summary and figcaption marks the acceptance that new elements are needed to act as captions or legends for the details and figure elements. The addition of the figcaption element finally begins to clear up the difficulty in marking-up figure element captions and looks to cement the place of the figure element in the HTML5 specification. The summary element does much the same for the details element but the very nature of the details element itself means that its future is not yet clear.

The figcaption element

This new element acts as the optional caption or legend for any content contained within its parent figure element.

If there is no figcaption element within a figure element then there is no caption for the rest of its content. If there is a figcaption element then it must be the first or last child of the figure element and only the first figcaption element (should there be more than one child figcaption of the parent figure element) represents a caption.

The figure element is used to mark up any self-contained content that may be referenced from the main flow of a document but could also be removed from the primary content (for example, to an appendix) without affecting its flow. This makes it suitable for various types of content ranging from graphs and data tables to photographs and code blocks.

<p><a href="#fig-ftse">Figure 1</a> shows the extent of the collapse in the markets and how recovery has been slow.</p>

<figure id="fig-ftse">
  <figcaption>Figure 1. The value of the FTSE 100 Index from 1999&ndash;2009.</figcaption>
  <img src="ftse-100-index-graph.jpg" alt="The index hit a record high at the end of 1999 and experienced two significant drops in the following last decade.">
</figure>

<p>This latest financial crisis hasn't stopped Alex from writing music and his latest track is actually worth listening to.</p>

<figure>
  <audio src="what-am-i-doing.mp3" controls></audio>
  <figcaption><cite>What am I doing?</cite> by Alex Brown</figcaption>
</figure>

The creation of the figcaption element is an important step forward for the HTML5 draft specification as it finally provides a reliable means to markup the caption for content that is best marked up as a figure. Previous attempts to use the legend element, the caption element, and the dt and dd elements had failed due to a lack of backwards compatibility when it came to styling these elements with CSS.

The summary element

This new element represents a summary, caption, or legend for any content contained within its parent details element.

The summary element must be the first child of a details element and if there is no summary element present then the user agent should provide its own. The reason for this is because the details element has a specific function – to markup additional information and allow the user to toggle the visibility of the additional information. Although it is not specified in the specification, it is expected that the summary element will act as the control that toggles the open-closed status of the contents of the parent details element.

<details>
  <summary>Technical details.</summary>
  <dl>
    <dt>Bit rate:</dt> <dd>190KB/s</dd>
    <dt>Filename:</dt> <dd>drum-and-bass-mix.mp3</dd>
    <dt>Duration:</dt> <dd>01:02:34</dd>
    <dt>File size:</dt> <dd>78.9MB</dd>
  </dl>
</details>

The introduction of the summary element seems to secure the future of the details element and the new behaviour that it affords, for now. When user agents begin to add support for the details element you won’t need JavaScript, or even CSS, to have expanding or collapsing sections in an HTML document.

The future of the details element

There will continue to be some debate over the inclusion of behaviour in an HTML specification especially given the widespread use of JavaScript to provide the expand-collapse functionality that details describes.

The details element writes some quite significant behaviour into an HTML document and I can see it being abused to provide generic expand-collapse functionality throughout a document. It is also not entirely clear what purpose the details element actually serves other than being an attempt to bypass the need for JavaScript or CSS to expand or collapse sections of a document.

There has been a general softening of the rough distinction between content, presentation, and behaviour. JavaScript libraries are being used to patch holes in browser CSS and HTML5 support, the CSS3 modules introduce plenty of behaviour that was previously only possibly with JavaScript, and the HTML5 specification is also introducing functionality and behaviour that previously required the use of JavaScript.

The future survival of the details element, and the behaviour associated with it, may well depend on browser implementations and author applications over the coming months.




tm

Using HTML5 elements in WordPress post content

Here are two ways to include HTML5 elements in your WordPress post content without WordPress’ wpautop function wrapping them in p tags or littering your code with line breaks.

HTML5 has several new elements that you may want to use in your post content to markup document sections, headers, footers, pullquotes, figures, or groups of headings. One way to safely include these elements in your posts is simple; the other way is a bit more complicated. Both ways rely on hand-coding the HTML5 markup in the WordPress editor’s HTML view.

If you are adding HTML5 elements to your post content then you should use an HTML5 doctype.

Disable wpautop for your theme

This is the simple way. Disable the wpautop function so that WordPress makes no attempt to correct your markup and leaves you to hand-code every line of your posts. If you want total control over every line of your HTML then this is the option for you.

To disable wpautop entirely add these lines to your theme’s functions.php:

remove_filter('the_excerpt', 'wpautop');
remove_filter('the_content', 'wpautop');

However, wpautop is generally quite useful if most of your posts are simple text content and you only occasionally want to include HTML5 elements. Therefore, modifying wpautop to recognise HTML5 elements might be more practical.

Modify wpautop to recognise HTML5 elements

WordPress’ wpautop is part of the core functions and can be found in this file within your WordPress installation: wp-includes/formatting.php. It controls how and where paragraphs and line breaks are inserted in excerpts and post content.

In order to create a modified version of WordPress’ core wpautop function I started off by duplicating it in my theme’s functions.php file.

What I’ve experimented with is disabling wpautop and adding a modified copy of it – which includes HTML5 elements in its arrayss – to my theme’s functions.php file.

Add the following to your theme’s functions.php file and you’ll be able to use section, article, aside, header, footer, hgroup, figure, details, figcaption, and summary in your post content. (Probably best to try this in a testing environment first!)

/* -----------------------------
MODIFIED WPAUTOP - Allow HTML5 block elements in wordpress posts
----------------------------- */

function html5autop($pee, $br = 1) {
   if ( trim($pee) === '' )
      return '';
   $pee = $pee . "
"; // just to make things a little easier, pad the end
   $pee = preg_replace('|<br />s*<br />|', "

", $pee);
   // Space things out a little
    // *insertion* of section|article|aside|header|footer|hgroup|figure|details|figcaption|summary
   $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|header|footer|hgroup|figure|details|figcaption|summary)';
   $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "
$1", $pee);
   $pee = preg_replace('!(</' . $allblocks . '>)!', "$1

", $pee);
   $pee = str_replace(array("
", "
"), "
", $pee); // cross-platform newlines
   if ( strpos($pee, '<object') !== false ) {
      $pee = preg_replace('|s*<param([^>]*)>s*|', "<param$1>", $pee); // no pee inside object/embed
      $pee = preg_replace('|s*</embed>s*|', '</embed>', $pee);
   }
   $pee = preg_replace("/

+/", "

", $pee); // take care of duplicates
// make paragraphs, including one at the end
   $pees = preg_split('/
s*
/', $pee, -1, PREG_SPLIT_NO_EMPTY);
   $pee = '';
   foreach ( $pees as $tinkle )
      $pee .= '<p>' . trim($tinkle, "
") . "</p>
";
   $pee = preg_replace('|<p>s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
// *insertion* of section|article|aside
   $pee = preg_replace('!<p>([^<]+)</(div|address|form|section|article|aside)>!', "<p>$1</p></$2>", $pee);
   $pee = preg_replace('!<p>s*(</?' . $allblocks . '[^>]*>)s*</p>!', "$1", $pee); // don't pee all over a tag
   $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
   $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
   $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
   $pee = preg_replace('!<p>s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
   $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)s*</p>!', "$1", $pee);
   if ($br) {
      $pee = preg_replace_callback('/<(script|style).*?</\1>/s', create_function('$matches', 'return str_replace("
", "<WPPreserveNewline />", $matches[0]);'), $pee);
      $pee = preg_replace('|(?<!<br />)s*
|', "<br />
", $pee); // optionally make line breaks
      $pee = str_replace('<WPPreserveNewline />', "
", $pee);
   }
   $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)s*<br />!', "$1", $pee);
// *insertion* of img|figcaption|summary
   $pee = preg_replace('!<br />(s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol|img|figcaption|summary)[^>]*>)!', '$1', $pee);
   if (strpos($pee, '<pre') !== false)
      $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
   $pee = preg_replace( "|
</p>$|", '</p>', $pee );

   return $pee;
}

// remove the original wpautop function
remove_filter('the_excerpt', 'wpautop');
remove_filter('the_content', 'wpautop');

// add our new html5autop function
add_filter('the_excerpt', 'html5autop');
add_filter('the_content', 'html5autop');

The results are not absolutely perfect but then neither is the original wpautop function. Certain ways of formatting the code will result in unwanted trailing </p> tags or a missing opening <p> tags.

For example, to insert a figure with caption into a post you should avoid adding the figcaption on a new line because an image or link appearing before the figcaption will end up with a trailing </p>.

<!-- this turns out ok -->
<figure>
  <a href="#"><img src="image.jpg" alt="" /></a><figcaption>A figure caption for your reading pleasure</figcaption>
</figure>

<!-- this turns out not so ok -->
<figure>
  <a href="#"><img src="image.jpg" alt="" /></a>
  <figcaption>A figure caption for your reading pleasure</figcaption>
</figure>

Another example would be when beginning the contents of an aside with a paragraph. You’ll have to leave a blank line between the opening aside tag and the first paragraph.

<aside>

This content could be a pullquote or information that is tangentially related to the surrounding content. But to get it wrapped in a paragraph you have to leave those blank lines either side of it before the tags.

</aside>

Room for improvement

Obviously there are still a few issues with this because if you format your post content in certain ways then you can end up with invalid HTML, even if it doesn’t actually affect the rendering of the page. But it seems to be pretty close!

Leave a comment or email me if you are using this function and find there that are instances where it breaks down. I ran numerous tests and formatting variations to try and iron out as many problems as possible but it’s unlikely that I tried or spotted everything.

Hopefully someone with more PHP and WordPress experience will be able to improve upon what I’ve been experimenting with, or find a simpler and more elegant solution that retains the useful wpautop functionality while allowing for the use of HTML5 elements in posts. Please share anything you find!




tm

Yet another HTML5 fallback strategy for IE

If you’re using HTML5 elements then you’re probably also using a JavaScript shiv to help make it possible to style those elements in versions of Internet Explorer prior to IE9. But when JavaScript is disabled the accessibility of the content may be affected in these versions of IE. This is one way to provide a more accessible fallback.

The concept is to ensure that all modern browsers are served the default style sheet(s) and that people using older versions of IE only download them if JavaScript is enabled. When JavaScript is not enabled, people using those browsers can be served either no styles at all (as Yahoo! suggests for browsers receiving C-Grade support) or simple fallback styles.

Client-side method: conditional comments

Doing this on the client-side comes at the cost of having to litter your code with proprietary conditional comments. First, it’s necessary to comment out the default style sheet(s) from versions of IE earlier than IE9. All other browsers will be able to read the file(s).

<!--[if ! lt IE 9]><!-->
<link rel="stylesheet" href="/css/default.css">
<!--<![endif]-->

For earlier versions of IE, an HTML5 shiv is included and the necessary link elements are created and added to the DOM using JavaScript. This means that when JavaScript is not enabled in IE7 or IE8 the style sheet will not be present, resulting in an unstyled HTML page. In this example, IE6 won’t be served CSS at all.

<!--[if (IE 7)|(IE 8)]>
<script src="/js/html5.js"></script>
<script>
   (function() {
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = "/css/default.css";
      document.getElementsByTagName("head")[0].appendChild(link);
   }());
</script>
<![endif]-->

To support multiple style sheets, an array and for loop can be used.

<!--[if (IE 7)|(IE 8)]>
<script src="/js/html5.js"></script>
<script>
   (function() {
      var css = [
         '/css/default.css',
         '/css/section.css',
         '/css/custom.css'
      ];
      var i;
      var link = document.createElement('link');
      var head = document.getElementsByTagName('head')[0];
      var tmp;

      link.rel = 'stylesheet';

      for(i = 0; i < css.length; i++){
         tmp = link.cloneNode(true);
         tmp.href = css[i];
         head.appendChild(tmp);
      }
   }());
</script>
<![endif]-->

Thanks to Remy Sharp and Mathias Bynens for helping me to improve this script. Fork it.

Rather than serving unstyled content, it may be preferable to provide some simple fallback styles. This can be done by linking to a separate style sheet wrapped in noscript tags. In this example, IE6 will always use these legacy styles while IE7 and IE8 will do so only when JavaScript is disabled.

<!--[if lt IE 9]>
<noscript>
   <link rel="stylesheet" href="/css/legacy.css">
</noscript>
<![endif]-->

You may wish to use a generic style sheet, such as “Universal IE6 CSS”, or spend a few minutes crafting your own and ensuring that the typography and colours approximate those in the default style sheet.

The complete example code is as follows:

<!--[if ! lt IE 9]><!-->
<link rel="stylesheet" href="/css/default.css">
<!--<![endif]-->

<!--[if (IE 7)|(IE 8)]>
<script src="/js/html5.js"></script>
<script>
   (function() {
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = "/css/default.css";
      document.getElementsByTagName("head")[0].appendChild(link);
   }());
</script>
<![endif]-->

<!--[if lt IE 9]>
<noscript>
   <link rel="stylesheet" href="/css/legacy.css">
</noscript>
<![endif]-->

Server-side method: user-agent string detection

The drawbacks of current client-side approaches to IE fallbacks is that they are IE-specific, make extensive use of conditional comments, and have to use JavaScript to create or rewrite link elements. This blog makes use of an alternative approach: server-side user-agent detection. It was inspired by Yahoo!’s Graded Browser Support strategy – created by Nate Koechley – which recommends that all CSS and JavaScript is withheld from legacy browsers (not limited to IE).

The source code in the head of this blog changes when viewed in modern browsers, IE8, and legacy browsers that are incapable of styling HTML5 elements (e.g. Firefox 2) or lack adequate CSS2.1 support (e.g. IE7).

Browsers are assumed to be capable; there is no need to update the script every time a new browser is released. Only when a browser is deemed to be severely incapable is it added to a “blacklist” and served simple styles to ensure that the accessibility of the content is maintained. This is the method I prefer, although it does require more time upfront.




tm

About HTML semantics and front-end architecture

A collection of thoughts, experiences, ideas that I like, and ideas that I have been experimenting with over the last year. It covers HTML semantics, components and approaches to front-end architecture, class naming patterns, and HTTP compression.

About semantics

Semantics is the study of the relationships between signs and symbols and what they represent. In linguistics, this is primarily the study of the meaning of signs (such as words, phrases, or sounds) in language. In the context of front-end web development, semantics are largely concerned with the agreed meaning of HTML elements, attributes, and attribute values (including extensions like Microdata). These agreed semantics, which are usually formalised in specifications, can be used to help programmes (and subsequently humans) better understand aspects of the information on a website. However, even after formalisation, the semantics of elements, attributes, and attribute values are subject to adaptation and co-option by developers. This can lead to subsequent modifications of the formally agreed semantics (and is an HTML design principle).

Distinguishing between different types of HTML semantics

The principle of writing “semantic HTML” is one of the foundations of modern, professional front-end development. Most semantics are related to aspects of the nature of the existing or expected content (e.g. h1 element, lang attribute, email value of the type attribute, Microdata).

However, not all semantics need to be content-derived. Class names cannot be “unsemantic”. Whatever names are being used: they have meaning, they have purpose. Class name semantics can be different to those of HTML elements. We can leverage the agreed “global” semantics of HTML elements, certain HTML attributes, Microdata, etc., without confusing their purpose with those of the “local” website/application-specific semantics that are usually contained in the values of attributes like the class attribute.

Despite the HTML5 specification section on classes repeating the assumed “best practice” that…

…authors are encouraged to use [class attribute] values that describe the nature of the content, rather than values that describe the desired presentation of the content.

…there is no inherent reason to do this. In fact, it’s often a hindrance when working on large websites or applications.

  • Content-layer semantics are already served by HTML elements and other attributes.
  • Class names impart little or no useful semantic information to machines or human visitors unless it is part of a small set of agreed upon (and machine readable) names – Microformats.
  • The primary purpose of a class name is to be a hook for CSS and JavaScript. If you don’t need to add presentation and behaviour to your web documents, then you probably don’t need classes in your HTML.
  • Class names should communicate useful information to developers. It’s helpful to understand what a specific class name is going to do when you read a DOM snippet, especially in multi-developer teams where front-enders won’t be the only people working with HTML components.

Take this very simple example:

<div class="news">
    <h2>News</h2>
    [news content]
</div>

The class name news doesn’t tell you anything that is not already obvious from the content. It gives you no information about the architectural structure of the component, and it cannot be used with content that isn’t “news”. Tying your class name semantics tightly to the nature of the content has already reduced the ability of your architecture to scale or be easily put to use by other developers.

Content-independent class names

An alternative is to derive class name semantics from repeating structural and functional patterns in a design. The most reusable components are those with class names that are independent of the content.

We shouldn’t be afraid of making the connections between layers clear and explicit rather than having class names rigidly reflect specific content. Doing this doesn’t make classes “unsemantic”, it just means that their semantics are not derived from the content. We shouldn’t be afraid to include additional HTML elements if they help create more robust, flexible, and reusable components. Doing so does not make the HTML “unsemantic”, it just means that you use elements beyond the bare minimum needed to markup the content.

Front-end architecture

The aim of a component/template/object-oriented architecture is to be able to develop a limited number of reusable components that can contain a range of different content types. The important thing for class name semantics in non-trivial applications is that they be driven by pragmatism and best serve their primary purpose – providing meaningful, flexible, and reusable presentational/behavioural hooks for developers to use.

Reusable and combinable components

Scalable HTML/CSS must, by and large, rely on classes within the HTML to allow for the creation of reusable components. A flexible and reusable component is one which neither relies on existing within a certain part of the DOM tree, nor requires the use of specific element types. It should be able to adapt to different containers and be easily themed. If necessary, extra HTML elements (beyond those needed just to markup the content) and can be used to make the component more robust. A good example is what Nicole Sullivan calls the media object.

Components that can be easily combined benefit from the avoidance of type selectors in favour of classes. The following example prevents the easy combination of the btn component with the uilist component. The problems are that the specificity of .btn is less than that of .uilist a (which will override any shared properties), and the uilist component requires anchors as child nodes.

.btn { /* styles */ }
.uilist { /* styles */ }
.uilist a { /* styles */ }
<nav class="uilist">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a class="btn" href="#">Login</a>
</nav>

An approach that improves the ease with which you can combine other components with uilist is to use classes to style the child DOM elements. Although this helps to reduce the specificity of the rule, the main benefit is that it gives you the option to apply the structural styles to any type of child node.

.btn { /* styles */ }
.uilist { /* styles */ }
.uilist-item { /* styles */ }
<nav class="uilist">
    <a class="uilist-item" href="#">Home</a>
    <a class="uilist-item" href="#">About</a>
    <span class="uilist-item">
        <a class="btn" href="#">Login</a>
    </span>
</nav>

JavaScript-specific classes

Using some form of JavaScript-specific classes can help to reduce the risk that thematic or structural changes to components will break any JavaScript that is also applied. An approach that I’ve found helpful is to use certain classes only for JavaScript hooks – js-* – and not to hang any presentation off them.

<a href="/login" class="btn btn-primary js-login"></a>

This way, you can reduce the chance that changing the structure or theme of components will inadvertently affect any required JavaScript behaviour and complex functionality.

Component modifiers

Components often have variants with slightly different presentations from the base component, e.g., a different coloured background or border. There are two mains patterns used to create these component variants. I’m going to call them the “single-class” and “multi-class” patterns.

The “single-class” pattern

.btn, .btn-primary { /* button template styles */ }
.btn-primary { /* styles specific to save button */ }

<button class="btn">Default</button>
<button class="btn-primary">Login</button>

The “multi-class” pattern

.btn { /* button template styles */ }
.btn-primary { /* styles specific to primary button */ }

<button class="btn">Default</button>
<button class="btn btn-primary">Login</button>

If you use a pre-processor, you might use Sass’s @extend functionality to reduce some of the maintenance work involved in using the “single-class” pattern. However, even with the help of a pre-processor, my preference is to use the “multi-class” pattern and add modifier classes in the HTML.

I’ve found it to be a more scalable pattern. For example, take the base btn component and add a further 5 types of button and 3 additional sizes. Using a “multi-class” pattern you end up with 9 classes that can be mixed-and-matched. Using a “single-class” pattern you end up with 24 classes.

It is also easier to make contextual tweaks to a component, if absolutely necessary. You might want to make small adjustments to any btn that appears within another component.

/* "multi-class" adjustment */
.thing .btn { /* adjustments */ }

/* "single-class" adjustment */
.thing .btn,
.thing .btn-primary,
.thing .btn-danger,
.thing .btn-etc { /* adjustments */ }

A “multi-class” pattern means you only need a single intra-component selector to target any type of btn-styled element within the component. A “single-class” pattern would mean that you may have to account for any possible button type, and adjust the selector whenever a new button variant is created.

Structured class names

When creating components – and “themes” that build upon them – some classes are used as component boundaries, some are used as component modifiers, and others are used to associate a collection of DOM nodes into a larger abstract presentational component.

It’s hard to deduce the relationship between btn (component), btn-primary (modifier), btn-group (component), and btn-group-item (component sub-object) because the names don’t clearly surface the purpose of the class. There is no consistent pattern.

In early 2011, I started experimenting with naming patterns that help me to more quickly understand the presentational relationship between nodes in a DOM snippet, rather than trying to piece together the site’s architecture by switching back-and-forth between HTML, CSS, and JS files. The notation in the gist is primarily influenced by the BEM system‘s approach to naming, but adapted into a form that I found easier to scan.

Since I first wrote this post, several other teams and frameworks have adopted this approach. MontageJS modified the notation into a different style, which I prefer and currently use in the SUIT framework:

/* Utility */
.u-utilityName {}

/* Component */
.ComponentName {}

/* Component modifier */
.ComponentName--modifierName {}

/* Component descendant */
.ComponentName-descendant {}

/* Component descendant modifier */
.ComponentName-descendant--modifierName {}

/* Component state (scoped to component) */
.ComponentName.is-stateOfComponent {}

This is merely a naming pattern that I’m finding helpful at the moment. It could take any form. But the benefit lies in removing the ambiguity of class names that rely only on (single) hyphens, or underscores, or camel case.

A note on raw file size and HTTP compression

Related to any discussion about modular/scalable CSS is a concern about file size and “bloat”. Nicole Sullivan’s talks often mention the file size savings (as well as maintenance improvements) that companies like Facebook experienced when adopting this kind of approach. Further to that, I thought I’d share my anecdotes about the effects of HTTP compression on pre-processor output and the extensive use of HTML classes.

When Twitter Bootstrap first came out, I rewrote the compiled CSS to better reflect how I would author it by hand and to compare the file sizes. After minifying both files, the hand-crafted CSS was about 10% smaller than the pre-processor output. But when both files were also gzipped, the pre-processor output was about 5% smaller than the hand-crafted CSS.

This highlights how important it is to compare the size of files after HTTP compression, because minified file sizes do not tell the whole story. It suggests that experienced CSS developers using pre-processors don’t need to be overly concerned about a certain degree of repetition in the compiled CSS because it can lend itself well to smaller file sizes after HTTP compression. The benefits of more maintainable “CSS” code via pre-processors should trump concerns about the aesthetics or size of the raw and minified output CSS.

In another experiment, I removed every class attribute from a 60KB HTML file pulled from a live site (already made up of many reusable components). Doing this reduced the file size to 25KB. When the original and stripped files were gzipped, their sizes were 7.6KB and 6KB respectively – a difference of 1.6KB. The actual file size consequences of liberal class use are rarely going to be worth stressing over.

How I learned to stop worrying…

The experience of many skilled developers, over many years, has led to a shift in how large-scale website and applications are developed. Despite this, for individuals weaned on an ideology where “semantic HTML” means using content-derived class names (and even then, only as a last resort), it usually requires you to work on a large application before you can become acutely aware of the impractical nature of that approach. You have to be prepared to disgard old ideas, look at alternatives, and even revisit ways that you may have previously dismissed.

Once you start writing non-trivial websites and applications that you and others must not only maintain but actively iterate upon, you quickly realise that despite your best efforts, your code starts to get harder and harder to maintain. It’s well worth taking the time to explore the work of some people who have proposed their own approaches to tackling these problems: Nicole’s blog and Object Oriented CSS project, Jonathan Snook’s Scalable Modular Architecture CSS, and the Block Element Modifier method that Yandex have developed.

When you choose to author HTML and CSS in a way that seeks to reduce the amount of time you spend writing and editing CSS, it involves accepting that you must instead spend more time changing HTML classes on elements if you want to change their styles. This turns out to be fairly practical, both for front-end and back-end developers – anyone can rearrange pre-built “lego blocks”; it turns out that no one can perform CSS-alchemy.




tm

Supply chain management at warp speed [electronic resource] : integrating the system from end to end / Eli Schragenheim, H. William Dettmer, J. Wayne Patterson

Schragenheim, Eli




tm

Wise money [electronic resource] : how the smart money invests using the endowment investment approach to minimize volatility and increase control / Daniel Wildermuth

Wildermuth, Daniel




tm

Zeitmanagement mit Microsoft Office Outlook [electronic resource] : die Zeit im Griff mit der meistgenutzten Bürosoftware - Strategien, Tipps und Techniken (Versionen 2003 - 2010) / Lothar Seiwert

Seiwert, Lothar




tm

Zeitmanagement mit Microsoft Outlook [electronic resource] : die Zeit im Griff mit der meist genutzten Bürosoftware : Strategien, Tipps und Techniken (Versionen 2003-2013) / Lothar Seiwert, Holger Wöltje, Christian Obermayr

Seiwert, Lothar




tm

Zeitmanagement mit Outlook [electronic resource] : die zeit im griff mit Microsoft Outlook 2003-2013 : strategien, tipps und techniken / Lothar Seiwert, Holger Wöltje, Christian Obermayr

Seiwert, Lothar, author





tm

JAMA Otolaryngology–Head & Neck Surgery : Effect of a Change in Papillary Thyroid Cancer Terminology on Anxiety Levels and Treatment Preferences

Interview with Brooke Nickel and Juan Brito, MD, MSc, authors of Effect of a Change in Papillary Thyroid Cancer Terminology on Anxiety Levels and Treatment Preferences: A Randomized Crossover Trial














tm

Indian-American Civil Rights lawyer Vanita Gupta appointed to head US Justice Department



  • DO NOT USE Indians Abroad
  • World

tm

Indians charged for running fraudulent investment scheme



  • DO NOT USE Indians Abroad
  • World

tm

Indian diplomat Atul Khare named head of UN Department of Field Support



  • DO NOT USE Indians Abroad
  • World

tm

Indian-origin investment advisor jailed for 18 months in US



  • DO NOT USE Indians Abroad
  • World

tm

The histology of fishes / editors, Frank Kirschbaum (Faculty of Life Sciences, Unit of Biology and Ecology of Fishes, Humboldt University, Berlin, Germany), Krzysztof Formicki (Department of Hydrobiology, Ichthyology and Biotechnology of Reproduction, Wes




tm

The Wiley Handbook of Healthcare Treatment Engagement: Theory, Research, and Clinical Practice


 

Against a global backdrop of problematic adherence to medical treatment, this volume addresses and provides practical solutions to the simple question: “Why don’t patients take treatments that could save their lives?”

The Wiley handbook of Healthcare Treatment Engagementoffers a guide to the theory, research and clinical practice of promoting patient engagement in healthcare treatment at individual, organizational and systems levels. The concept of



Read More...




tm

The case for impeachment / Allan J. Lichtman

Dewey Library - KF5076.T78 L53 2017




tm

Arbitration costs: myths and realities in investment treaty arbitration / Susan D. Franck

Dewey Library - K3830.F73 2019




tm

Contributory fault and investor misconduct in investment arbitration / Martin Jarrett, University of Mannheim

Dewey Library - K3830.J368 2019




tm

From bilateral arbitral tribunals and investment courts to a multilateral investment court: options regarding the institutionalization of investor-state dispute settlement / Marc Bungenberg, August Reinisch

Online Resource




tm

A Matter of Interpretation: Federal Courts and the Law - New Edition / Antonin Scalia; Amy Gutmann

Online Resource




tm

Chair Professor/Professor/Associate Professor/Assistant Professor Department of Physics Ref. A/301/09: City University of Hong Kong

£Attractive: City University of Hong Kong
For more latest jobs and jobs in China visit brightrecruits.com




tm

China's banking law and the national treatment of foreign-funded banks = [Zhongguo yin hang fa yu wai zi yin hang guo min dai yu] / Wei Wang, Ph.D., Associate Professor of Fudan University Law School, Shanghai, China

Wang, Wei, 1972 September-- author




tm

Leveraging our advantages : the trade relationship between Australia and Indonesia / Joint Standing Committee on Trade and Investment Growth

Australia. Parliament. Joint Standing Committee on Trade and Investment Growth, author, issuing body




tm

A Cambodian spring [videorecording] / Little Ease Films in association with Dartmouth Films, Zanzibar Films & EyesteelFilm presents a film by Chris Kelly




tm

Unexpected atmospheric chemistry may explain an air pollution mystery

New understanding of the complex chemistry of haze could provide guidance for air-quality regulators




tm

New Jersey town switches to peracetic acid wastewater treatment




tm

Molded microfluidic device makes gel &#8220;apartments&#8221; for single cells

Hydrogel device allows localized treatment and analysis of 10,000 individual cells at a time




tm

Gilead and Moderna lead on coronavirus treatments

Gilead has a head start on an antiviral, while Moderna is pursuing a novel mRNA vaccine




tm

Gilead and Moderna lead on coronavirus treatments

Gilead has a head start on an antiviral, while Moderna is pursuing a novel mRNA vaccine




tm

Method detects new PFAS in the atmosphere

Untargeted capture and analysis turns up previously unobserved airborne PFAS




tm

Gates, Wellcome, and Mastercard give $125 million for coronavirus treatments




tm

Chemistry departments deal with coronavirus closures

Amid university shutdowns worldwide, professors and students adjust what social distancing means for lab scientists




tm

Protein mapping finds 69 potential treatments for COVID-19

Many are FDA-approved drugs that could be repurposed




tm

Eastman donates polyester for medical face shields




tm

Fujifilm tests favipiravir as COVID-19 treatment

Japanese government plans to buy at least 2 million tablets of the influenza drug




tm

Fujifilm tests favipiravir as a COVID-19 treatment

Japanese government plans to buy at least 2 million courses of the influenza drug