Author Archive

Opinion Column: The Road To Reusable HTML Components


  

A few weeks ago, I dug up an old article that I wrote for Smashing Magazine, “When One Word Is More Meaningful Than a Thousand.� While I stand firmly behind all of the HTML development principles I listed back then, the article lacked one important thing: hands-on examples.

Sure enough, the theory behind component-based HTML is interesting in its own right, but without a few illustrative examples, it’s all very dry and abstract. Not that HTML enthusiasts should shy away from that (on the contrary, I would say), but there’s nothing like a good example to clear up some of the finer points of a concept.

So, that’s what I’ve set out to do in this article. In the previous one, I sampled a couple of common content types (such as products, stories and videos) across different websites. Now I’ll stick to four different views of a single content type: the story (or news article). It’s a pretty simple and straightforward content type that most people know and have developed at some point in their career. For some real-world inspiration, I’ll refer to the Boston Globe website (a front-end favorite of mine).

One important disclaimer before we get started. This article isn’t so much about the resulting HTML as it is about the methodology of writing HTML. Your opinion on the class names, structures and source order that I suggest along the way may differ, but that’s not what the article is really about (although I’m not saying it wouldn’t yield some interesting discussion).

The Difference Between This And Other Popular Component-Based Methodologies

Component-based HTML development isn’t exactly new. A couple of months ago, Smashing Magazine has run articles on BEM, OOCSS and SMACSS. While I don’t have enough information to judge BEM, the other two methodologies are clearly opposed to what I am going to propose here.

Methodologies such as OOCSS and SMACCS were born out of frustration with CSS, but these methodologies try to ease CSS development by altering the HTML code. I think this is definitely not the way to go (and if you check the original presentation by Nicole Sullivan, you’ll find that she proposes an early version of mixins as a better alternative). Writing HTML is about so much more than making sure the CSS has the hooks it needs for you to implement the design; so, coming at it from a CSS angle can only diminish the overall quality of the HTML you write. The problem is not limited to providing the right hooks for CSS and JavaScript; the true challenge is to make sure that every element across a website is identifiable. If you can accomplish that, then you’ve got CSS, JavaScript and whatever other script technology you’re using covered without having to worry about the project’s specifics.

The methodology I will demonstrate below was conceived with reusability and robustness in mind. It is largely independent of project-specific requirements and remains as close as possible to the purity that HTML development deserves, resulting in individual HTML snippets that are as versatile as they are reusable.

Step 1: Gather All Views And Instances Of A Single Component

Let’s take this one step at a time. First of all, we need to state the requirements of our content type. To do that, we would normally run through all of the wireframes of a project, listing and grouping all of the different instances and views of each content type. To keep our example as clear and simple as possible, though, I’ve hand-picked four representative views that I’ve encountered on the Boston Globe website.

Boston News

I peeked quickly behind the curtains and found the following hooks in the HTML code:

  1. Shortlist view: .in-section ul li
  2. Thumb view: .feat-thumb
  3. Summary view: div.story
  4. Detail view: div.article (or no root at all)

To be honest, I find this quite messy. If for some reason you wanted to single out all stories on your page or website (whether for CSS, JavaScript, analytics or another reason), you would have to work around quite a few ambiguities. Surely, we can do a better job.

Step 2: Define The Root

<article class="story">
   …
</article>

There! That wasn’t too difficult now, was it? We picked the article element and hooked a single class name to it, which we’ll use as a base indicator for all stories. This way, we make sure that we can target all story instances using a single fixed identifier. As you can see from the Boston Globe examples, though, each view requires unique styling. Relying solely on the context of our story instances is far from flexible, so let’s introduce a specifying class for each view:

  1. Shortlist view: .story.shortlist
  2. Thumb view: .story.thumb
  3. Summary view: .story.summary
  4. Detail view: .story.detail

The reason for adding specifying classes to the root element itself (rather than, for example, to a list surrounding it) is flexibility. If tomorrow you are asked to build a composite list that holds both summary and shortlist views of the story component, you want to be able to do that without breaking a sweat.

Step 3: Defining The Logical Units Inside

With that out of the way, it’s time to look at what’s inside each story component. Rather than writing the HTML for each separate view, we’ll start by going through all of the different views, listing all of the elements (i.e. logical units) that we find inside. For each element, we’ll define the HTML. Mind that these logical units could probably reappear in a different context and that they are usually components by themselves, so chances are high that you’ve already written HTML snippets for them elsewhere in your project.

Heading

There’s always a heading. The heading summarizes all of the content that follows, so it’s one of the most essential parts of your content type (apart from the content itself, of course). All of the views listed above contain a heading, but even if you come across a view that doesn’t visually display a heading, put it in the HTML code anyway and hide it with CSS if necessary. This way, you will always “enter� your content type knowing what it’s going to be about. As for the actual code, that’s pretty straightforward:

<h1>news heading</h1>

Thumbnail

The second thing we see is a thumbnail image. Thumbnail images aren’t quite a part of the actual content, although in some cases a thumbnail is little more than a (browser-)resized version of the first image within the story content. It doesn’t have to be, though, because a thumbnail functions mainly as a visual cue that attracts the visitor’s attention to the story. In some cases, it isn’t even featured at all in the story itself, so let’s consider it a standalone item.

Again, the code is pretty simple. We’ve just added a wrapper around the img element so that we can easily add a caption if needed.

<div class="image thumb"><img src="…" alt="…" /></div>

Meta Data

Most content types feature meta data. Meta data isn’t truly a part of the content itself, but it tells you something extra about the content embedded within the content type. In the views above, we find several types of meta data: author, publication date, section indicator and a “first published in [resource]� line.

Coming up with the markup for meta data is a little trickier. If you follow the HTML5 specficiation to the letter, then you are supposed to use a definition list. Meta data is nothing more than a list of label-value pairs, which is exactly what the specification’s authors had in mind when they expanded the semantic range of the HTML5 definition list. But because the markup for definition lists is still missing a wrapper for list items, it’s not very robust, and in many cases styling it proves to be a real hassle (if not impossible). You could invalidate your code by wrapping a div around each dd-dt pair (so that you still enjoy the semantic benefits of the element), but I usually prefer to keep my code valid, sacrificing some tag semantics in the process.

<div class="meta">
    <div class="author">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
    <div class="publishDate">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
    <div class="section">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
    <div class="publishedIn">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
</div>

Abstract

An abstract is a short summary of or introduction to your content type. In some cases, but not always, it is identical to the actual introductory text. If the abstract is identical to the introductory text, then you could consider it a part of the actual content; if it’s tailored copy, then it should be marked up separately.

As for the HTML, you could use a paragraph tag with a class attached to it, but then you’d limit abstracts to a single paragraph. Looking at the Boston Globe example, it’s fine, but if we want our code to be portable across projects, then keeping our options open is probably best. This results in the following HTML code:

<div class="abstract">
    <p> … </p>
</div>

Action Links

In the detail view of the story, we see a list of actions related to the story itself. Typically, lists such as these include print and mail actions and, of course, the token social sharing options. Instead on relying on source order or numbered classes, we’ll give each link a unique class so that we can play around with it if needed.

<div class="actions">
   <ul>
      <li class="recommend">…</li>
      …
      <li class="print">…</li>
   </ul>
</div>

You’ll notice that the action list is placed above the content, making it a likely candidate to be put inside a header element. While I’ll stick to that as a concession to the design, the links actually belong in the footer element of your content type. These are actions that become relevant once you know the context. You wouldn’t (or at least shouldn’t) share an article based merely on the title; knowing the content is crucial to deciding on your action. Adventurous CSS’ers could leave room in the header and then position the list from within the footer, but that would make the CSS implementation more fragile.

Actual Content

Finally, we get to the crux of the matter, the story itself. What’s actually inside a story often depends on the freedom you’ve given to your content editors. Either you’ve given them a fixed set of templates to work with, or you’ve just dropped a WYSIWYG editor into the CMS and hoped for the best. One thing you need to do, though, is contain the content section, if only as a warning that what follows may be user content.

<div class="content">
    …
</div>

Related Stories

Finally, we find a shortlist of related stories. The most important thing to recognize here is that example one is exactly the same view as the list of related stories that we’re trying to make, so there’s really no reason to differentiate the HTML code between the two instances.

<section class="storyList">
    <div class="main">
      <article class="story"> … </article>
    </div>
</section>

Step 4: Defining Structural Containers

The elements listed above have not only a logical sequence of elements, but also a logical hierarchical structure. Some elements precede the content itself and should be placed separate from the main content. Some elements are afterthoughts or additional information and should be placed after the actual content. To do this, we set up a typical header-main-footer structure.

<article class="story">
   <header> … </header>
   <div class="main"> … </div>
   <footer> … </footer>
<article>

The main wrapper might not look absolutely necessary at first glance, but because it is a logical unit, it deserves a container of its own.

Step 5: Throw Everything Together

Now that all of the HTML snippets are ready, it is time to throw everything together, creating one master component.

<article class="story">
   <header>
      <h1>story heading</h1>
      <div class="image thumb"><img src="…" alt="…" /></div>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
         <div class="publishDate">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
         <div class="section">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
         <div class="publishedIn">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
      </div>
      <div class="abstract">
         <p> … </p>
      </div>
      <div class="actions">
         <ul>
            <li class="recommend">…</li>
            …
            <li class="print">…</li>
         </ul>
      </div>
   </header>
   <div class="main">
      <div class="content"> … </div>
      <aside>
         <section class="storyList">
            <div class="main">
               <article class="story">…</article>
            </div>
         </section>
      </aside>
   </div>
   <footer> (used for read more links, links to comment section, etc.) </footer>
<article>

Step 6: Adding Microdata

Even though the HTML code is now flexible and descriptive enough for other scripts to extract or pinpoint whatever structure they need, our component still misses a common vocabulary. Sure enough, we’ve added a .story class to the root element, but what about using .news, .article or .newsItem? They’re still not very semantic. Well, HTML5 provides us with microdata, a part of the HTML5 specification, which allows us to add a global vocabulary to our HTML code. You can make your own vocabulary if you wish, but if you check a website such as Schema.org you’ll see that plenty are already available for the most common objects. As a bonus, search engines such as Google, Yahoo and Bing support microdata already.

The itemscope property should be placed in the root element, together with the itemtype (which specifies a URL for the vocabulary — in this case, the Schema.org website). After that, it’s just a matter of running through the available vocabulary properties and adding them to your code using itemprop. This will give us the following HTML component:

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="image thumb"><img src="…" alt="…" itemprop="image"/></div>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd" itemprop="author">value</span>
         </div>
         <div class="publishDate">
            <span class="dt">label:</span><span class="dd" itemprop="datePublished">value</span>
         </div>
         <div class="section">
            <span class="dt">label:</span><span class="dd" itemprop="articleSection">value</span>
         </div>
         <div class="publishedIn">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
      </div>
      <div class="abstract" itemprop="description">
         <p> … </p>
      </div>
      <div class="actions">
         <ul>
            <li class="recommend">…</li>
            …
            <li class="print">…</li>
         </ul>
      </div>
   </header>
   <div class="main">
      <div class="content" itemprop="articleBody"> … </div>
      <aside>
         <section class="storyList">
            <div class="main">
               <article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">…</article>
            </div>
         </section>
      </aside>
   </div>
   <footer> (used for read more links, links to comment section, etc.) </footer>
<article>

Step 7: And Finally…

Now that we have our master component, all that’s left to do is check each view and remove the elements from the master component that are not needed. If this results in any leftover (= empty) structural wrappers, we’ll remove them, too. This will give us the following snippets:

Shortlist View

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
   </header>
<article>

Thumb view

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="image thumb"><img src="…" alt="…" itemprop="image"/></div>
      <div class="meta">
         <div class="section">
            <span class="dt">label:</span><span class="dd" itemprop="articleSection">value</span>
         </div>
      </div>
   </header>
<article>

Summary view

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="image thumb"><img src="…" alt="…" itemprop="image"/></div>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd" itemprop="author">value</span>
         </div>
      </div>
      <div class="abstract" itemprop="description">
         <p> … </p>
      </div>
   </header>
   <div class="main">
      <aside>
         <section class="storyList">
            <div class="main">
               <article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">…</article>
            </div>
         </section>
      </aside>
   </div>
<article>

Detail view

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd" itemprop="author">value</span>
         </div>
         <div class="publishDate">
            <span class="dt">label:</span><span class="dd" itemprop="datePublished">value</span>
         </div>
         <div class="section">
            <span class="dt">label:</span><span class="dd" itemprop="articleSection">value</span>
         </div>
         <div class="publishedIn">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
      </div>
      <div class="actions">
         <ul>
            <li class="recommend">…</li>
            …
            <li class="print">…</li>
         </ul>
      </div>
   </header>
   <div class="main">
      <div class="content" itemprop="articleBody">…</div>
   </div>
<article>

Reusable HTML Components Make Sense

If you look closely at the core principles of HTML, you will see that HTML leaves little room for variation. The HTML code we write is supposed to describe our content as clearly as possible, independent of the styling; so, there is really no reason to make different structural versions of a single component that appears in different contexts, pages or even projects. A news article is a news article, and while the inner particles may vary, the core structure, tag selection and naming conventions need not be tampered with. Of course, there is still room to accommodate the author’s personality, including minor personal preferences, certain ideologies and overall experience, but one author should ideally stick to a single structure for a single component.

Component-based HTML also has important practical advantages. Of course, the news article above is just one simple example, but you could do the same for all of the components that you use across projects. This might seem like a lot of work at first, but you’ll need to do it only once; after that, you can spend the time that you’ve saved on the dumb monkey work of fine-tuning your library. When I write the HTML for a new website these days, about 80 to 85% of the components are out of the box; the remaining 15 to 20% consist of small changes for project-specific requirements and new components (which might get added to my core library later on). This speeds up HTML development dramatically.

It’s also a tremendous advantage for people who prefer to design in the browser. One of the biggest drawbacks of designing in the browser is that the HTML is usually the least of your worries. You might intend to clean it up later, but if you’re honest with yourself, then you know that the probability that you’ll take the time to perfect an aspect of your work that’s mostly invisible to the client anyway is quite low. By using your own library of components, you won’t need to worry about the HTML anymore. If you need a certain component, you can just pluck it out of the box, knowing that you’re getting quality HTML from the start, and leaving you to focus on the design and CSS.

The most important advantage of component-based HTML is the quality of service you will be providing to your clients. Rather than delivering project-specific (i.e. styled) templates, you can offer them a solid HTML and component framework. This way, you give clients the option to deploy these components across multiple websites. Again, this will greatly speed up HTML development (and back-end implementation) in future projects — projects that can now start as soon as the wireframes are finished, rather than once the graphical designs are done. You could even go so far as to wireframe using your HTML components (with a white-label CSS attached to them). The possibilities seem endless. At the same time, this methodology will introduce an unprecedented level of consistency and predictability in code across all of the client’s websites, two things that are often lacking these days.

The Future Of HTML

The way I see it, reusable, component-based HTML is definitely the way forward, and it’s about time we take this next step in HTML development. Just start from the components that you’ve already built, make yourself a snippet library, and go from there. Of course, some level of customization will always be needed, but I’m confident that the HTML snippet above can handle 90% of all story content types that you’ll find on the Web. The meta data may differ a little sometimes, and certain visualizations might require you to change the source order, but the basics are there to create whatever you need in less than five minutes. This is about applying the DRY principle (“don’t repeat yourself�) not just within a single project, but across multiple websites and even multiple clients.

In the end, methodologies such as OOCSS and SMACSS will only work against this ideal, because they are rooted in visual styling that prohobits the proper reuse of components across different websites. Not only that, but they will slow down the development cycle because the design becomes just another dependency. For now, this means you’ll have to rely on CSS preprocessors if you want maintainable CSS, but in the long run, we’ll benefit greatly from adapting the methodology described above. I’m interested in hearing your thoughts on this.

Image source of picture on front page.

(al)


© Niels Matthijs for Smashing Magazine, 2012.


Opinion Column: The Road To Reusable HTML Components


  

A few weeks ago, I dug up an old article that I wrote for Smashing Magazine, “When One Word Is More Meaningful Than a Thousand.� While I stand firmly behind all of the HTML development principles I listed back then, the article lacked one important thing: hands-on examples.

Sure enough, the theory behind component-based HTML is interesting in its own right, but without a few illustrative examples, it’s all very dry and abstract. Not that HTML enthusiasts should shy away from that (on the contrary, I would say), but there’s nothing like a good example to clear up some of the finer points of a concept.

So, that’s what I’ve set out to do in this article. In the previous one, I sampled a couple of common content types (such as products, stories and videos) across different websites. Now I’ll stick to four different views of a single content type: the story (or news article). It’s a pretty simple and straightforward content type that most people know and have developed at some point in their career. For some real-world inspiration, I’ll refer to the Boston Globe website (a front-end favorite of mine).

One important disclaimer before we get started. This article isn’t so much about the resulting HTML as it is about the methodology of writing HTML. Your opinion on the class names, structures and source order that I suggest along the way may differ, but that’s not what the article is really about (although I’m not saying it wouldn’t yield some interesting discussion).

The Difference Between This And Other Popular Component-Based Methodologies

Component-based HTML development isn’t exactly new. A couple of months ago, Smashing Magazine has run articles on BEM, OOCSS and SMACSS. While I don’t have enough information to judge BEM, the other two methodologies are clearly opposed to what I am going to propose here.

Methodologies such as OOCSS and SMACCS were born out of frustration with CSS, but these methodologies try to ease CSS development by altering the HTML code. I think this is definitely not the way to go (and if you check the original presentation by Nicole Sullivan, you’ll find that she proposes an early version of mixins as a better alternative). Writing HTML is about so much more than making sure the CSS has the hooks it needs for you to implement the design; so, coming at it from a CSS angle can only diminish the overall quality of the HTML you write. The problem is not limited to providing the right hooks for CSS and JavaScript; the true challenge is to make sure that every element across a website is identifiable. If you can accomplish that, then you’ve got CSS, JavaScript and whatever other script technology you’re using covered without having to worry about the project’s specifics.

The methodology I will demonstrate below was conceived with reusability and robustness in mind. It is largely independent of project-specific requirements and remains as close as possible to the purity that HTML development deserves, resulting in individual HTML snippets that are as versatile as they are reusable.

Step 1: Gather All Views And Instances Of A Single Component

Let’s take this one step at a time. First of all, we need to state the requirements of our content type. To do that, we would normally run through all of the wireframes of a project, listing and grouping all of the different instances and views of each content type. To keep our example as clear and simple as possible, though, I’ve hand-picked four representative views that I’ve encountered on the Boston Globe website.

Boston News

I peeked quickly behind the curtains and found the following hooks in the HTML code:

  1. Shortlist view: .in-section ul li
  2. Thumb view: .feat-thumb
  3. Summary view: div.story
  4. Detail view: div.article (or no root at all)

To be honest, I find this quite messy. If for some reason you wanted to single out all stories on your page or website (whether for CSS, JavaScript, analytics or another reason), you would have to work around quite a few ambiguities. Surely, we can do a better job.

Step 2: Define The Root

<article class="story">
   …
</article>

There! That wasn’t too difficult now, was it? We picked the article element and hooked a single class name to it, which we’ll use as a base indicator for all stories. This way, we make sure that we can target all story instances using a single fixed identifier. As you can see from the Boston Globe examples, though, each view requires unique styling. Relying solely on the context of our story instances is far from flexible, so let’s introduce a specifying class for each view:

  1. Shortlist view: .story.shortlist
  2. Thumb view: .story.thumb
  3. Summary view: .story.summary
  4. Detail view: .story.detail

The reason for adding specifying classes to the root element itself (rather than, for example, to a list surrounding it) is flexibility. If tomorrow you are asked to build a composite list that holds both summary and shortlist views of the story component, you want to be able to do that without breaking a sweat.

Step 3: Defining The Logical Units Inside

With that out of the way, it’s time to look at what’s inside each story component. Rather than writing the HTML for each separate view, we’ll start by going through all of the different views, listing all of the elements (i.e. logical units) that we find inside. For each element, we’ll define the HTML. Mind that these logical units could probably reappear in a different context and that they are usually components by themselves, so chances are high that you’ve already written HTML snippets for them elsewhere in your project.

Heading

There’s always a heading. The heading summarizes all of the content that follows, so it’s one of the most essential parts of your content type (apart from the content itself, of course). All of the views listed above contain a heading, but even if you come across a view that doesn’t visually display a heading, put it in the HTML code anyway and hide it with CSS if necessary. This way, you will always “enter� your content type knowing what it’s going to be about. As for the actual code, that’s pretty straightforward:

<h1>news heading</h1>

Thumbnail

The second thing we see is a thumbnail image. Thumbnail images aren’t quite a part of the actual content, although in some cases a thumbnail is little more than a (browser-)resized version of the first image within the story content. It doesn’t have to be, though, because a thumbnail functions mainly as a visual cue that attracts the visitor’s attention to the story. In some cases, it isn’t even featured at all in the story itself, so let’s consider it a standalone item.

Again, the code is pretty simple. We’ve just added a wrapper around the img element so that we can easily add a caption if needed.

<div class="image thumb"><img src="…" alt="…" /></div>

Meta Data

Most content types feature meta data. Meta data isn’t truly a part of the content itself, but it tells you something extra about the content embedded within the content type. In the views above, we find several types of meta data: author, publication date, section indicator and a “first published in [resource]� line.

Coming up with the markup for meta data is a little trickier. If you follow the HTML5 specficiation to the letter, then you are supposed to use a definition list. Meta data is nothing more than a list of label-value pairs, which is exactly what the specification’s authors had in mind when they expanded the semantic range of the HTML5 definition list. But because the markup for definition lists is still missing a wrapper for list items, it’s not very robust, and in many cases styling it proves to be a real hassle (if not impossible). You could invalidate your code by wrapping a div around each dd-dt pair (so that you still enjoy the semantic benefits of the element), but I usually prefer to keep my code valid, sacrificing some tag semantics in the process.

<div class="meta">
    <div class="author">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
    <div class="publishDate">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
    <div class="section">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
    <div class="publishedIn">
        <span class="dt">label:</span><span class="dd">value</span>
    </div>
</div>

Abstract

An abstract is a short summary of or introduction to your content type. In some cases, but not always, it is identical to the actual introductory text. If the abstract is identical to the introductory text, then you could consider it a part of the actual content; if it’s tailored copy, then it should be marked up separately.

As for the HTML, you could use a paragraph tag with a class attached to it, but then you’d limit abstracts to a single paragraph. Looking at the Boston Globe example, it’s fine, but if we want our code to be portable across projects, then keeping our options open is probably best. This results in the following HTML code:

<div class="abstract">
    <p> … </p>
</div>

Action Links

In the detail view of the story, we see a list of actions related to the story itself. Typically, lists such as these include print and mail actions and, of course, the token social sharing options. Instead on relying on source order or numbered classes, we’ll give each link a unique class so that we can play around with it if needed.

<div class="actions">
   <ul>
      <li class="recommend">…</li>
      …
      <li class="print">…</li>
   </ul>
</div>

You’ll notice that the action list is placed above the content, making it a likely candidate to be put inside a header element. While I’ll stick to that as a concession to the design, the links actually belong in the footer element of your content type. These are actions that become relevant once you know the context. You wouldn’t (or at least shouldn’t) share an article based merely on the title; knowing the content is crucial to deciding on your action. Adventurous CSS’ers could leave room in the header and then position the list from within the footer, but that would make the CSS implementation more fragile.

Actual Content

Finally, we get to the crux of the matter, the story itself. What’s actually inside a story often depends on the freedom you’ve given to your content editors. Either you’ve given them a fixed set of templates to work with, or you’ve just dropped a WYSIWYG editor into the CMS and hoped for the best. One thing you need to do, though, is contain the content section, if only as a warning that what follows may be user content.

<div class="content">
    …
</div>

Related Stories

Finally, we find a shortlist of related stories. The most important thing to recognize here is that example one is exactly the same view as the list of related stories that we’re trying to make, so there’s really no reason to differentiate the HTML code between the two instances.

<section class="storyList">
    <div class="main">
      <article class="story"> … </article>
    </div>
</section>

Step 4: Defining Structural Containers

The elements listed above have not only a logical sequence of elements, but also a logical hierarchical structure. Some elements precede the content itself and should be placed separate from the main content. Some elements are afterthoughts or additional information and should be placed after the actual content. To do this, we set up a typical header-main-footer structure.

<article class="story">
   <header> … </header>
   <div class="main"> … </div>
   <footer> … </footer>
<article>

The main wrapper might not look absolutely necessary at first glance, but because it is a logical unit, it deserves a container of its own.

Step 5: Throw Everything Together

Now that all of the HTML snippets are ready, it is time to throw everything together, creating one master component.

<article class="story">
   <header>
      <h1>story heading</h1>
      <div class="image thumb"><img src="…" alt="…" /></div>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
         <div class="publishDate">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
         <div class="section">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
         <div class="publishedIn">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
      </div>
      <div class="abstract">
         <p> … </p>
      </div>
      <div class="actions">
         <ul>
            <li class="recommend">…</li>
            …
            <li class="print">…</li>
         </ul>
      </div>
   </header>
   <div class="main">
      <div class="content"> … </div>
      <aside>
         <section class="storyList">
            <div class="main">
               <article class="story">…</article>
            </div>
         </section>
      </aside>
   </div>
   <footer> (used for read more links, links to comment section, etc.) </footer>
<article>

Step 6: Adding Microdata

Even though the HTML code is now flexible and descriptive enough for other scripts to extract or pinpoint whatever structure they need, our component still misses a common vocabulary. Sure enough, we’ve added a .story class to the root element, but what about using .news, .article or .newsItem? They’re still not very semantic. Well, HTML5 provides us with microdata, a part of the HTML5 specification, which allows us to add a global vocabulary to our HTML code. You can make your own vocabulary if you wish, but if you check a website such as Schema.org you’ll see that plenty are already available for the most common objects. As a bonus, search engines such as Google, Yahoo and Bing support microdata already.

The itemscope property should be placed in the root element, together with the itemtype (which specifies a URL for the vocabulary — in this case, the Schema.org website). After that, it’s just a matter of running through the available vocabulary properties and adding them to your code using itemprop. This will give us the following HTML component:

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="image thumb"><img src="…" alt="…" itemprop="image"/></div>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd" itemprop="author">value</span>
         </div>
         <div class="publishDate">
            <span class="dt">label:</span><span class="dd" itemprop="datePublished">value</span>
         </div>
         <div class="section">
            <span class="dt">label:</span><span class="dd" itemprop="articleSection">value</span>
         </div>
         <div class="publishedIn">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
      </div>
      <div class="abstract" itemprop="description">
         <p> … </p>
      </div>
      <div class="actions">
         <ul>
            <li class="recommend">…</li>
            …
            <li class="print">…</li>
         </ul>
      </div>
   </header>
   <div class="main">
      <div class="content" itemprop="articleBody"> … </div>
      <aside>
         <section class="storyList">
            <div class="main">
               <article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">…</article>
            </div>
         </section>
      </aside>
   </div>
   <footer> (used for read more links, links to comment section, etc.) </footer>
<article>

Step 7: And Finally…

Now that we have our master component, all that’s left to do is check each view and remove the elements from the master component that are not needed. If this results in any leftover (= empty) structural wrappers, we’ll remove them, too. This will give us the following snippets:

Shortlist View

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
   </header>
<article>

Thumb view

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="image thumb"><img src="…" alt="…" itemprop="image"/></div>
      <div class="meta">
         <div class="section">
            <span class="dt">label:</span><span class="dd" itemprop="articleSection">value</span>
         </div>
      </div>
   </header>
<article>

Summary view

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="image thumb"><img src="…" alt="…" itemprop="image"/></div>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd" itemprop="author">value</span>
         </div>
      </div>
      <div class="abstract" itemprop="description">
         <p> … </p>
      </div>
   </header>
   <div class="main">
      <aside>
         <section class="storyList">
            <div class="main">
               <article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">…</article>
            </div>
         </section>
      </aside>
   </div>
<article>

Detail view

<article class="story" itemscope="itemscope" itemtype="http://schema.org/NewsArticle">
   <meta content="en" itemprop="inLanguage" />
   <header>
      <h1 itemprop="headline">story heading</h1>
      <div class="meta">
         <div class="author">
            <span class="dt">label:</span><span class="dd" itemprop="author">value</span>
         </div>
         <div class="publishDate">
            <span class="dt">label:</span><span class="dd" itemprop="datePublished">value</span>
         </div>
         <div class="section">
            <span class="dt">label:</span><span class="dd" itemprop="articleSection">value</span>
         </div>
         <div class="publishedIn">
            <span class="dt">label:</span><span class="dd">value</span>
         </div>
      </div>
      <div class="actions">
         <ul>
            <li class="recommend">…</li>
            …
            <li class="print">…</li>
         </ul>
      </div>
   </header>
   <div class="main">
      <div class="content" itemprop="articleBody">…</div>
   </div>
<article>

Reusable HTML Components Make Sense

If you look closely at the core principles of HTML, you will see that HTML leaves little room for variation. The HTML code we write is supposed to describe our content as clearly as possible, independent of the styling; so, there is really no reason to make different structural versions of a single component that appears in different contexts, pages or even projects. A news article is a news article, and while the inner particles may vary, the core structure, tag selection and naming conventions need not be tampered with. Of course, there is still room to accommodate the author’s personality, including minor personal preferences, certain ideologies and overall experience, but one author should ideally stick to a single structure for a single component.

Component-based HTML also has important practical advantages. Of course, the news article above is just one simple example, but you could do the same for all of the components that you use across projects. This might seem like a lot of work at first, but you’ll need to do it only once; after that, you can spend the time that you’ve saved on the dumb monkey work of fine-tuning your library. When I write the HTML for a new website these days, about 80 to 85% of the components are out of the box; the remaining 15 to 20% consist of small changes for project-specific requirements and new components (which might get added to my core library later on). This speeds up HTML development dramatically.

It’s also a tremendous advantage for people who prefer to design in the browser. One of the biggest drawbacks of designing in the browser is that the HTML is usually the least of your worries. You might intend to clean it up later, but if you’re honest with yourself, then you know that the probability that you’ll take the time to perfect an aspect of your work that’s mostly invisible to the client anyway is quite low. By using your own library of components, you won’t need to worry about the HTML anymore. If you need a certain component, you can just pluck it out of the box, knowing that you’re getting quality HTML from the start, and leaving you to focus on the design and CSS.

The most important advantage of component-based HTML is the quality of service you will be providing to your clients. Rather than delivering project-specific (i.e. styled) templates, you can offer them a solid HTML and component framework. This way, you give clients the option to deploy these components across multiple websites. Again, this will greatly speed up HTML development (and back-end implementation) in future projects — projects that can now start as soon as the wireframes are finished, rather than once the graphical designs are done. You could even go so far as to wireframe using your HTML components (with a white-label CSS attached to them). The possibilities seem endless. At the same time, this methodology will introduce an unprecedented level of consistency and predictability in code across all of the client’s websites, two things that are often lacking these days.

The Future Of HTML

The way I see it, reusable, component-based HTML is definitely the way forward, and it’s about time we take this next step in HTML development. Just start from the components that you’ve already built, make yourself a snippet library, and go from there. Of course, some level of customization will always be needed, but I’m confident that the HTML snippet above can handle 90% of all story content types that you’ll find on the Web. The meta data may differ a little sometimes, and certain visualizations might require you to change the source order, but the basics are there to create whatever you need in less than five minutes. This is about applying the DRY principle (“don’t repeat yourself�) not just within a single project, but across multiple websites and even multiple clients.

In the end, methodologies such as OOCSS and SMACSS will only work against this ideal, because they are rooted in visual styling that prohobits the proper reuse of components across different websites. Not only that, but they will slow down the development cycle because the design becomes just another dependency. For now, this means you’ll have to rely on CSS preprocessors if you want maintainable CSS, but in the long run, we’ll benefit greatly from adapting the methodology described above. I’m interested in hearing your thoughts on this.

Image source of picture on front page.

(al)


© Niels Matthijs for Smashing Magazine, 2012.


CSS Sprites Revisited


  

I’m pretty confident that I won’t surprise anyone here by saying that CSS sprites have been around for quite a while now, rearing their somewhat controversial heads in the Web development sphere as early as 2003.

Still, the CSS sprite hasn’t truly found its way into the everyday toolkit of the common Web developer. While the theory behind CSS sprites is easy enough and its advantages are clear, they still prove to be too bothersome to implement, especially when time is short and deadlines are looming. Barriers exist to be breached, though, and we’re not going to let a couple of tiny bumps in the road spoil the greater perks of the CSS sprite.

If you want more background information on best practices and practical use cases, definitely read “The Mystery of CSS Sprites: Techniques, Tools and Resources.� If you’re the defensive type, I would recommend “CSS Sprites: Useful Technique, or Potential Nuisance?,� which discusses possible caveats.

I won’t take a stance on the validity of CSS sprites. The aim of this article is to find out why people still find it difficult to use CSS sprites. Also, we’ll come up with a couple of substantial improvements to current techniques. So, start up Photoshop (or your CSS sprite tool of choice), put on your LESS and Sass hats, and brush up your CSS pseudo-element skills, because we’ll be mixing and matching our way to easier CSS sprite implementation.

The Problem With CSS Sprites

While Photoshop is booting, take a moment to consider why CSS sprites have had such a hard time getting widespread acceptance and support. I’m always struggling to find the correct starting position for each image within a sprite. I’ll usually forget the exact coordinates by the time I need to write them down in the style sheet, especially when the image is located at x:259, y:182 and measures 17×13 pixels.

I’m always switching back and forth between Photoshop and my CSS editor to write down the correct values, getting more and more frustrated with every switch. I know software is out there specifically tailored to help us deal with this, but I’ve never found an application that lets me properly structure its CSS output so that I can just copy and paste it into my CSS file.

Another important thing to realize is that CSS sprites are meant to be one part of our website optimization toolkit. Many of the people who write and blog about CSS sprites are comfortably wearing their optimization hats while laying out best practices, often going a little overboard and losing track of how much effort it requires to implement their methods of choice.

This is fine if you’re working on an optimization project, but it becomes counterproductive when you need to build a website from scratch while fighting tight deadlines. If you have time to truly focus on implementing a CSS sprite, it’s really not all that hard; but if you have to juggle 50 other priorities at the same time, it does turn into a nuisance for many developers. With these two factors in mind, we’ll try to find a way to make image targeting easier, while coming to terms with the fact that sometimes we have to sacrifice full optimization in the name of ease of development.

CSS sprites in the wild: Amazon, Google and Facebook.
CSS sprites in the wild: Amazon, Google and Facebook.

Preparing The Sprite

If you look online for examples of CSS sprites, you’ll see that most are optimized for an ideal use of real estate—gaps between images are kept to a minimum in order to keep the load of the entire sprite as low as possible. This reduces loading time considerably when the image is first downloaded, but it also introduces those horrible image coordinates that we mentioned earlier. So, why not take a slightly different approach? Let’s look for an easier way to target images while making sure the resulting sprite is not substantially bigger than the sum of its individual images.

Rather than try to stack the images in such a way that makes the resulting sprite as small as possible, let’s try a different layout. Instead of a random grid, we’re going to build a nice square grid, reserving the space of each square for one image (although larger images might cover multiple squares). The goal is to be able to target the starting point of every image (top-left corner) with a very simple mathematical function.

The size of the grid squares will depend on the average dimension of the images that you’ll be spriting. For my website, I used a 32×32 pixel grid (because only one image exceeds this dimension), but grid sizes will vary according to the situation. Another thing to take into account is the image bleeding that can occur when zooming a page; if you want to play it safe, add a little padding to each image within the sprite. For extra optimization, you could also use a rectangular grid instead of a square grid, further reducing any wasted space; while a tad more complex, this isn’t much different from what we’ll be doing. For this article, though, we’ll stick with the square grid.

Preparing The Sprite: A Photoshop Bonus

I’m no designer, so I’m not sure how applicable this section is beyond the realm of Photoshop, but there are still some noteworthy improvements that can be made before we get to the actual code. First of all, visualizing the grid can be of great help. Photoshop has guides to do this (so you don’t actually have to include the markers in your sprite), with the added bonus that layers will snap to these guides (making pixel-perfect positioning of each individual image much easier).

Manually adding these guides can be somewhat of a drag, though. Luckily, a colleague of mine (hats off to Filip Van Tendeloo) was kind enough to write and share a little Photoshop script that builds this grid of guides automatically based on the base size of your square. Pretty convenient, no? Just download the script, save it in the Presets\Scripts directory, and choose File → Scripts → Sprite Grid from the Photoshop menu.

Finally, to really finish things off, you can add numbers to the x and y axes of your grid so that you can easily pinpoint every square in the grid. Don’t add these numbers to the actual sprite, though; just copy the sprite into a new image and add them there. These numbers are just for reference—but trust me, they will definitely come in handy in a minute.

Example of a reference image.
Example of a reference image.

If you can’t (or don’t want to) use preprocessing languages such as LESS and Sass, just add the coordinates of each square instead.

LESS And Sass To The Rescue

With all of the images on the same square grid, we can now easily compute the top-left coordinate of each image (this coordinate is the exact match needed for the background-position values to reposition the sprite). Just take the base size of the grid and multiply it by the numbers that you just added to your reference image. Say you need to target the image at a position of (5,3), and your grid size is 32 pixels; the top-left position of your image will be 32 × (5,3) = (160,96). To add these values to your CSS file, just use their negative equivalents, like so:

background-position: -160px -96px;

Leave your calculator where it is for the time being, because it would be too much of a hassle. If computers are good at anything, it’s doing calculations, so we’re going to make good use of that power. Plain CSS doesn’t allow us to do calculations (yet), but languages like LESS and Sass were made to do just that. If you need more background information, check out the article “An Introduction to LESS and Comparison to Sass.� While both languages offer similar functionality, their syntaxes are slightly different. I’m a LESS man myself, but if you’re used to Sass, converting the following examples to Sass code shouldn’t be too hard. Now for some advanced CSS magic:

@spriteGrid: 32px;
.sprite(@x, @y) {
   background: url(img/sprite.png) no-repeat;
   background-position: -(@x*@spriteGrid) -(@y*@spriteGrid);
}

Nothing too exciting so far. First, we’ve defined the grid size using a LESS variable (@spriteGrid). Then, we made a mixin that accepts the numbers we added to the reference image earlier. This mixin uses the grid variable and the image’s coordinates to calculate the base position of the image that we want to target. It might not look fancy, but it sure makes the basic use of sprites a lot easier already. From now on, you can just use .sprite(1,5), and that’s all there is to it. No more annoying calculations or finding random start coordinates.

Of course, the mixin above only works in our somewhat simplified example (using a square grid and just one sprite). Some websites out there are more complex and might require different sprites using rectangular grids for additional optimization. This isn’t exactly impossible to fix with LESS, though:

.spriteHelper(@image, @x, @y, @spriteX, @spriteY) {
   background: url("img/@{image}.png") no-repeat;
   background-position: -(@x*@spriteX) -(@y*@spriteY);
}
.sprite(@image, @x, @y) when (@image = sprite1), (@image = sprite3){
   @spriteX: 32px;
   @spriteY: 16px;
   .spriteHelper(@image, @x, @y, @spriteX, @spriteY);
}
.sprite(@image, @x, @y) when (@image = sprite2){
   @spriteX: 64px;
   @spriteY: 32px;
   .spriteHelper(@image, @x, @y, @spriteX, @spriteY);
}

Yes, this looks a bit more daunting, but it’s still pretty basic if you take a minute to understand what’s going on. Most importantly, the added complexity is safely hidden away inside the LESS mixins, and we’re still able to use the same sprite mixin as before, only now with three parameters in total. We’ve just added an image parameter so that we can easily determine which sprite to use each time we call our mixin.

Different sprites might have different grid dimensions, though; so, for each grid dimension, we need to write a separate LESS mixin. We match each sprite to its specific dimension (the example above handles three different sprites and matches it to two different grid dimensions), and we define the dimensions (@spriteX and @spriteY) locally in each mixin. Once that is done, we offload the rest of the work to a little .spriteHelper mixin that does all of the necessary calculations and gives us the same result as before.

The “guardsâ€� (as LESS calls them—characterized by the keyword “whenâ€�) are quite new to the LESS vocabulary, so do make sure you’re using the latest version of the LESS engine if you attempt to run this yourself. It does offer a great way to keep the sprite mixin as clear and concise as possible, though. Just pass the sprite you want to use to the sprite mixin, and LESS will figure out the rest for you.

Common CSS Sprite Use Cases

With these mixins at our disposal, let’s see what different CSS sprite use cases we can identify and find out whether capturing these use cases in additional LESS mixins is possible. Once again, in order to minimize complexity in the upcoming sections, we’ll assume you’re working with a square grid sprite. If you need a rectangular grid, just add the image’s parameter to the LESS mixins we’ll be working with, and everything should be fine.

For each use case, we’ll define two mixins: one with and one without height and width parameters. If you’re like me and you keep misspelling the height and width keywords, the second mixin might come in handy. It does leave you the responsibility of learning the correct order of the parameters, though. LESS allows you to define these mixins in the same document, however, so there’s really no harm in listing them both, picking whichever is easiest for you.

1. Replaced Text

This is probably the easiest use case, occurring when we have an html element at our disposal that can be given a fixed dimension (in order to ensure we can hide the unwanted parts of the sprite). We’ll also be hiding the text inside the html element, replacing it with an image from our sprite. Typical examples of this use case are action links (think delete icons, print links, RSS icons, etc.) and headings (although CSS3 and Web fonts are quickly making this technique obsolete).

.hideText{
   text-indent: -999em;
   letter-spacing: -999em;
   overflow: hidden;
}
.spriteReplace(@x, @y) {
   .sprite(@x, @y);
   .hideText;
}
.spriteReplace (@x, @y, @width, @height) {
   .sprite(@x, @y);
   .hideText;
   width: @width;
   height: @height;
}

The spriteReplace mixin simply wraps our former sprite mixin and adds a small helper mixin to hide the text from view. It’s pretty basic, but it does save us the trouble of adding the .hideText mixin manually for every instance of this use case.


Using sprites for replaced elements.

In the example above, we have a list of sharing options. For whatever reason (theming or just personal preference), let’s say we decide to use CSS backgrounds instead of HTML images. Nothing to it with the mixins we just created. Here’s the code (assuming we’re using the reference image shown earlier):

<ul class="sharing">
   <li class="twitter"><a href="#">Share [article’s title] on Twitter</a></li>
   …
</ul>
.sharing .twitter a {
   .spriteReplace(0, 0, 32px, 32px); display:block;
}

2. Inline Images

For the second use case, we’ll tackle inline images. The main problem we’re facing here is that we won’t be able to put fixed dimensions on the html element itself because we’re dealing with variable-sized content. Typical uses of inline images are for icons next to text links (for example, external links, download links, etc.), but this method can also be used for any other item that allows text to be wrapped around a sprite image.

.spriteInline(@x, @y) {
   .sprite(@x, @y);
   display: inline-block;
   content: "";
}

.spriteInline(@x, @y, @width, @height) {
   .sprite(@x, @y);
   display: inline-block;
   content: "";
   width: @width;
   height: @height;
}

We might be lacking a structural element to visualize our image, but 2011 taught us that pseudo-elements are the perfect hack to overcome this problem (Nicolas Gallagher’s eye-opening article on using pseudo-elements for background images explains everything in detail). This is why the spriteInline mixin was especially developed to be used within a :before or :after selector (depending on where the image needs to appear). We’ll add an inline-block declaration to the pseudo-element so that it behaves like an inline element while still allowing us to add fixed dimensions to it, and we’ll add the content property, which is needed just for visualizing the pseudo-element.


Using sprites for inline images.

The example above shows a list of affiliate links. The design demands that each link be limited to one line, so we can safely use the .spriteInline mixin to display the icons in front of each link:

<ul class="affiliates">
   <li class="amazon"><a href="#">Buy on Amazon.com</a></li>
   …
</ul>
.affiliates .amazon a:before {
   .spriteInline(4, 1, 22px, 16px);
}

3. Padded Images

The third and final use case comes up when text isn’t allowed to wrap around a sprite image. Typical examples are list items that span multiple lines, and all kinds of visual notifications that bare icons. Whenever you want to reserve space on a multi-line element to make sure the text lines up neatly next to the image, this is the method you’ll want to use.

.spritePadded(@x, @y) {
   .sprite(@x, @y);
   position: absolute;
   content: "";
}
.spritePadded(@x, @y, @width, @height) {
   .sprite(@x, @y);
   position: absolute;
   content: "";
   width: @width;
   height: @height;
}

Again we’ll try our luck with pseudo-elements; this time, though, we’ll be performing some positioning tricks. By applying a position: absolute to the pseudo-element, we can place it right inside the space reserved by its parent element (usually by applying padding to the parent—hence, the name of the mixin). The actual position of the image (the left, right, top and bottom properties) is not added to the spritePadded mixin and should be done in the selector itself to keep things as clean and simple as possible (in this case, by maintaining a low parameter count).

Because we’re using absolute positioning, either the :before or :after pseudo-element will do the job. Keep in mind, though, that the :after element is a likely candidate for CSS clearing methods, so if you want to avoid future conflicts (because the clearing fix won’t work if you add a position: absolute to the :after pseudo-element), you’d be safest applying the sprite style to the :before element.


Using sprites for padded elements.

Let’s assume we need to indicate that our article is available in other languages (probably on a different page or even website). We’ll add a little notification box, listing the different translations of the current article. If the text breaks onto a second line, though, we do not want it to crawl below our little icon, so we’ll use the spritePadded mixin:

<section class="notification translated">
   <p>Translation available…</p>
</section>
.translated p {
   padding-left: 22px;
   position: relative;
}
.translated p:before {
   .spritePadded(5, 5, 16px, 14px);
   left: 0;
   top: 0;
}

The Ideal Sprite

So, have we achieved CSS sprite wizardry here? Heck, no! If you’ve been paying close attention, you might have noticed that the use cases above offer no solution for adding repeating backgrounds to a sprite. While there are some ways around this problem, none of them are very efficient or even worthy of recommendation.

What CSS sprites need in order to truly flourish is a CSS solution for cropping an image. Such a property should define a crop operation on a given background image before the image is used for further CSS processing. This way, it would be easy to crop the desired image from the sprite and position it accordingly, repeating it as needed; we’d be done with these :before and :after hacks because there wouldn’t be anything left to hide. A solution has been proposed in the Editor’s Draft of the CSS Image Values and Replaced Content Module Level 3 (section 3.2.1), but it could take months, even years, for this to become readily available.

For now, the LESS mixins above should prove pretty helpful if you plan to use CSS sprites. Just remember to prepare your sprite well; if you do, things should move ahead pretty smoothly, even when deadlines are weighing on you.

(al)


© Niels Matthijs for Smashing Magazine, 2012.


CSS Sprites Revisited


  

I’m pretty confident that I won’t surprise anyone here by saying that CSS sprites have been around for quite a while now, rearing their somewhat controversial heads in the Web development sphere as early as 2003.

Still, the CSS sprite hasn’t truly found its way into the everyday toolkit of the common Web developer. While the theory behind CSS sprites is easy enough and its advantages are clear, they still prove to be too bothersome to implement, especially when time is short and deadlines are looming. Barriers exist to be breached, though, and we’re not going to let a couple of tiny bumps in the road spoil the greater perks of the CSS sprite.

If you want more background information on best practices and practical use cases, definitely read “The Mystery of CSS Sprites: Techniques, Tools and Resources.� If you’re the defensive type, I would recommend “CSS Sprites: Useful Technique, or Potential Nuisance?,� which discusses possible caveats.

I won’t take a stance on the validity of CSS sprites. The aim of this article is to find out why people still find it difficult to use CSS sprites. Also, we’ll come up with a couple of substantial improvements to current techniques. So, start up Photoshop (or your CSS sprite tool of choice), put on your LESS and Sass hats, and brush up your CSS pseudo-element skills, because we’ll be mixing and matching our way to easier CSS sprite implementation.

The Problem With CSS Sprites

While Photoshop is booting, take a moment to consider why CSS sprites have had such a hard time getting widespread acceptance and support. I’m always struggling to find the correct starting position for each image within a sprite. I’ll usually forget the exact coordinates by the time I need to write them down in the style sheet, especially when the image is located at x:259, y:182 and measures 17×13 pixels.

I’m always switching back and forth between Photoshop and my CSS editor to write down the correct values, getting more and more frustrated with every switch. I know software is out there specifically tailored to help us deal with this, but I’ve never found an application that lets me properly structure its CSS output so that I can just copy and paste it into my CSS file.

Another important thing to realize is that CSS sprites are meant to be one part of our website optimization toolkit. Many of the people who write and blog about CSS sprites are comfortably wearing their optimization hats while laying out best practices, often going a little overboard and losing track of how much effort it requires to implement their methods of choice.

This is fine if you’re working on an optimization project, but it becomes counterproductive when you need to build a website from scratch while fighting tight deadlines. If you have time to truly focus on implementing a CSS sprite, it’s really not all that hard; but if you have to juggle 50 other priorities at the same time, it does turn into a nuisance for many developers. With these two factors in mind, we’ll try to find a way to make image targeting easier, while coming to terms with the fact that sometimes we have to sacrifice full optimization in the name of ease of development.

CSS sprites in the wild: Amazon, Google and Facebook.
CSS sprites in the wild: Amazon, Google and Facebook.

Preparing The Sprite

If you look online for examples of CSS sprites, you’ll see that most are optimized for an ideal use of real estate—gaps between images are kept to a minimum in order to keep the load of the entire sprite as low as possible. This reduces loading time considerably when the image is first downloaded, but it also introduces those horrible image coordinates that we mentioned earlier. So, why not take a slightly different approach? Let’s look for an easier way to target images while making sure the resulting sprite is not substantially bigger than the sum of its individual images.

Rather than try to stack the images in such a way that makes the resulting sprite as small as possible, let’s try a different layout. Instead of a random grid, we’re going to build a nice square grid, reserving the space of each square for one image (although larger images might cover multiple squares). The goal is to be able to target the starting point of every image (top-left corner) with a very simple mathematical function.

The size of the grid squares will depend on the average dimension of the images that you’ll be spriting. For my website, I used a 32×32 pixel grid (because only one image exceeds this dimension), but grid sizes will vary according to the situation. Another thing to take into account is the image bleeding that can occur when zooming a page; if you want to play it safe, add a little padding to each image within the sprite. For extra optimization, you could also use a rectangular grid instead of a square grid, further reducing any wasted space; while a tad more complex, this isn’t much different from what we’ll be doing. For this article, though, we’ll stick with the square grid.

Preparing The Sprite: A Photoshop Bonus

I’m no designer, so I’m not sure how applicable this section is beyond the realm of Photoshop, but there are still some noteworthy improvements that can be made before we get to the actual code. First of all, visualizing the grid can be of great help. Photoshop has guides to do this (so you don’t actually have to include the markers in your sprite), with the added bonus that layers will snap to these guides (making pixel-perfect positioning of each individual image much easier).

Manually adding these guides can be somewhat of a drag, though. Luckily, a colleague of mine (hats off to Filip Van Tendeloo) was kind enough to write and share a little Photoshop script that builds this grid of guides automatically based on the base size of your square. Pretty convenient, no? Just download the script, save it in the Presets\Scripts directory, and choose File → Scripts → Sprite Grid from the Photoshop menu.

Finally, to really finish things off, you can add numbers to the x and y axes of your grid so that you can easily pinpoint every square in the grid. Don’t add these numbers to the actual sprite, though; just copy the sprite into a new image and add them there. These numbers are just for reference—but trust me, they will definitely come in handy in a minute.

Example of a reference image.
Example of a reference image.

If you can’t (or don’t want to) use preprocessing languages such as LESS and Sass, just add the coordinates of each square instead.

LESS And Sass To The Rescue

With all of the images on the same square grid, we can now easily compute the top-left coordinate of each image (this coordinate is the exact match needed for the background-position values to reposition the sprite). Just take the base size of the grid and multiply it by the numbers that you just added to your reference image. Say you need to target the image at a position of (5,3), and your grid size is 32 pixels; the top-left position of your image will be 32 × (5,3) = (160,96). To add these values to your CSS file, just use their negative equivalents, like so:

background-position: -160px -96px;

Leave your calculator where it is for the time being, because it would be too much of a hassle. If computers are good at anything, it’s doing calculations, so we’re going to make good use of that power. Plain CSS doesn’t allow us to do calculations (yet), but languages like LESS and Sass were made to do just that. If you need more background information, check out the article “An Introduction to LESS and Comparison to Sass.� While both languages offer similar functionality, their syntaxes are slightly different. I’m a LESS man myself, but if you’re used to Sass, converting the following examples to Sass code shouldn’t be too hard. Now for some advanced CSS magic:

@spriteGrid: 32px;
.sprite(@x, @y) {
   background: url(img/sprite.png) no-repeat;
   background-position: -(@x*@spriteGrid) -(@y*@spriteGrid);
}

Nothing too exciting so far. First, we’ve defined the grid size using a LESS variable (@spriteGrid). Then, we made a mixin that accepts the numbers we added to the reference image earlier. This mixin uses the grid variable and the image’s coordinates to calculate the base position of the image that we want to target. It might not look fancy, but it sure makes the basic use of sprites a lot easier already. From now on, you can just use .sprite(1,5), and that’s all there is to it. No more annoying calculations or finding random start coordinates.

Of course, the mixin above only works in our somewhat simplified example (using a square grid and just one sprite). Some websites out there are more complex and might require different sprites using rectangular grids for additional optimization. This isn’t exactly impossible to fix with LESS, though:

.spriteHelper(@image, @x, @y, @spriteX, @spriteY) {
   background: url("img/@{image}.png") no-repeat;
   background-position: -(@x*@spriteX) -(@y*@spriteY);
}
.sprite(@image, @x, @y) when (@image = sprite1), (@image = sprite3){
   @spriteX: 32px;
   @spriteY: 16px;
   .spriteHelper(@image, @x, @y, @spriteX, @spriteY);
}
.sprite(@image, @x, @y) when (@image = sprite2){
   @spriteX: 64px;
   @spriteY: 32px;
   .spriteHelper(@image, @x, @y, @spriteX, @spriteY);
}

Yes, this looks a bit more daunting, but it’s still pretty basic if you take a minute to understand what’s going on. Most importantly, the added complexity is safely hidden away inside the LESS mixins, and we’re still able to use the same sprite mixin as before, only now with three parameters in total. We’ve just added an image parameter so that we can easily determine which sprite to use each time we call our mixin.

Different sprites might have different grid dimensions, though; so, for each grid dimension, we need to write a separate LESS mixin. We match each sprite to its specific dimension (the example above handles three different sprites and matches it to two different grid dimensions), and we define the dimensions (@spriteX and @spriteY) locally in each mixin. Once that is done, we offload the rest of the work to a little .spriteHelper mixin that does all of the necessary calculations and gives us the same result as before.

The “guardsâ€� (as LESS calls them—characterized by the keyword “whenâ€�) are quite new to the LESS vocabulary, so do make sure you’re using the latest version of the LESS engine if you attempt to run this yourself. It does offer a great way to keep the sprite mixin as clear and concise as possible, though. Just pass the sprite you want to use to the sprite mixin, and LESS will figure out the rest for you.

Common CSS Sprite Use Cases

With these mixins at our disposal, let’s see what different CSS sprite use cases we can identify and find out whether capturing these use cases in additional LESS mixins is possible. Once again, in order to minimize complexity in the upcoming sections, we’ll assume you’re working with a square grid sprite. If you need a rectangular grid, just add the image’s parameter to the LESS mixins we’ll be working with, and everything should be fine.

For each use case, we’ll define two mixins: one with and one without height and width parameters. If you’re like me and you keep misspelling the height and width keywords, the second mixin might come in handy. It does leave you the responsibility of learning the correct order of the parameters, though. LESS allows you to define these mixins in the same document, however, so there’s really no harm in listing them both, picking whichever is easiest for you.

1. Replaced Text

This is probably the easiest use case, occurring when we have an html element at our disposal that can be given a fixed dimension (in order to ensure we can hide the unwanted parts of the sprite). We’ll also be hiding the text inside the html element, replacing it with an image from our sprite. Typical examples of this use case are action links (think delete icons, print links, RSS icons, etc.) and headings (although CSS3 and Web fonts are quickly making this technique obsolete).

.hideText{
   text-indent: -999em;
   letter-spacing: -999em;
   overflow: hidden;
}
.spriteReplace(@x, @y) {
   .sprite(@x, @y);
   .hideText;
}
.spriteReplace (@x, @y, @width, @height) {
   .sprite(@x, @y);
   .hideText;
   width: @width;
   height: @height;
}

The spriteReplace mixin simply wraps our former sprite mixin and adds a small helper mixin to hide the text from view. It’s pretty basic, but it does save us the trouble of adding the .hideText mixin manually for every instance of this use case.


Using sprites for replaced elements.

In the example above, we have a list of sharing options. For whatever reason (theming or just personal preference), let’s say we decide to use CSS backgrounds instead of HTML images. Nothing to it with the mixins we just created. Here’s the code (assuming we’re using the reference image shown earlier):

<ul class="sharing">
   <li class="twitter"><a href="#">Share [article’s title] on Twitter</a></li>
   …
</ul>
.sharing .twitter a {
   .spriteReplace(0, 0, 32px, 32px); display:block;
}

2. Inline Images

For the second use case, we’ll tackle inline images. The main problem we’re facing here is that we won’t be able to put fixed dimensions on the html element itself because we’re dealing with variable-sized content. Typical uses of inline images are for icons next to text links (for example, external links, download links, etc.), but this method can also be used for any other item that allows text to be wrapped around a sprite image.

.spriteInline(@x, @y) {
   .sprite(@x, @y);
   display: inline-block;
   content: "";
}

.spriteInline(@x, @y, @width, @height) {
   .sprite(@x, @y);
   display: inline-block;
   content: "";
   width: @width;
   height: @height;
}

We might be lacking a structural element to visualize our image, but 2011 taught us that pseudo-elements are the perfect hack to overcome this problem (Nicolas Gallagher’s eye-opening article on using pseudo-elements for background images explains everything in detail). This is why the spriteInline mixin was especially developed to be used within a :before or :after selector (depending on where the image needs to appear). We’ll add an inline-block declaration to the pseudo-element so that it behaves like an inline element while still allowing us to add fixed dimensions to it, and we’ll add the content property, which is needed just for visualizing the pseudo-element.


Using sprites for inline images.

The example above shows a list of affiliate links. The design demands that each link be limited to one line, so we can safely use the .spriteInline mixin to display the icons in front of each link:

<ul class="affiliates">
   <li class="amazon"><a href="#">Buy on Amazon.com</a></li>
   …
</ul>
.affiliates .amazon a:before {
   .spriteInline(4, 1, 22px, 16px);
}

3. Padded Images

The third and final use case comes up when text isn’t allowed to wrap around a sprite image. Typical examples are list items that span multiple lines, and all kinds of visual notifications that bare icons. Whenever you want to reserve space on a multi-line element to make sure the text lines up neatly next to the image, this is the method you’ll want to use.

.spritePadded(@x, @y) {
   .sprite(@x, @y);
   position: absolute;
   content: "";
}
.spritePadded(@x, @y, @width, @height) {
   .sprite(@x, @y);
   position: absolute;
   content: "";
   width: @width;
   height: @height;
}

Again we’ll try our luck with pseudo-elements; this time, though, we’ll be performing some positioning tricks. By applying a position: absolute to the pseudo-element, we can place it right inside the space reserved by its parent element (usually by applying padding to the parent—hence, the name of the mixin). The actual position of the image (the left, right, top and bottom properties) is not added to the spritePadded mixin and should be done in the selector itself to keep things as clean and simple as possible (in this case, by maintaining a low parameter count).

Because we’re using absolute positioning, either the :before or :after pseudo-element will do the job. Keep in mind, though, that the :after element is a likely candidate for CSS clearing methods, so if you want to avoid future conflicts (because the clearing fix won’t work if you add a position: absolute to the :after pseudo-element), you’d be safest applying the sprite style to the :before element.


Using sprites for padded elements.

Let’s assume we need to indicate that our article is available in other languages (probably on a different page or even website). We’ll add a little notification box, listing the different translations of the current article. If the text breaks onto a second line, though, we do not want it to crawl below our little icon, so we’ll use the spritePadded mixin:

<section class="notification translated">
   <p>Translation available…</p>
</section>
.translated p {
   padding-left: 22px;
   position: relative;
}
.translated p:before {
   .spritePadded(5, 5, 16px, 14px);
   left: 0;
   top: 0;
}

The Ideal Sprite

So, have we achieved CSS sprite wizardry here? Heck, no! If you’ve been paying close attention, you might have noticed that the use cases above offer no solution for adding repeating backgrounds to a sprite. While there are some ways around this problem, none of them are very efficient or even worthy of recommendation.

What CSS sprites need in order to truly flourish is a CSS solution for cropping an image. Such a property should define a crop operation on a given background image before the image is used for further CSS processing. This way, it would be easy to crop the desired image from the sprite and position it accordingly, repeating it as needed; we’d be done with these :before and :after hacks because there wouldn’t be anything left to hide. A solution has been proposed in the Editor’s Draft of the CSS Image Values and Replaced Content Module Level 3 (section 3.2.1), but it could take months, even years, for this to become readily available.

For now, the LESS mixins above should prove pretty helpful if you plan to use CSS sprites. Just remember to prepare your sprite well; if you do, things should move ahead pretty smoothly, even when deadlines are weighing on you.

(al)


© Niels Matthijs for Smashing Magazine, 2012.


When One Word Is More Meaningful Than A Thousand

Smashing-magazine-advertisement in When One Word Is More Meaningful Than A ThousandSpacer in When One Word Is More Meaningful Than A Thousand
 in When One Word Is More Meaningful Than A Thousand  in When One Word Is More Meaningful Than A Thousand  in When One Word Is More Meaningful Than A Thousand

You may be wondering why you’re reading about the good old semantics on Smashing Magazine. Why doesn’t this article deal with HTML5 or another fancy new language: anything but plain, clear, tired old semantics. You may even find the subject boring, being a devoted front-end developer. You don’t need a lecture on semantics. You’ve done a good job keeping up with the Web these last 10 years, and you know pretty much all there is to know.

I’m writing about HTML semantics because I’ve noticed that semantic values are often handled sloppily and are sometimes neglected, even today. A huge void remains in semantic consistency and clarity, begging to be filled. We need better and more consistent naming conventions and smarter ways to construct HTML templates, to give us more consistent, clearer and readable HTML code. If that doesn’t sound like paradise, I don’t know what does.

[By the way, did you know we have a brand new free Smashing Email Newsletter? Subscribe now and get fresh short tips and tricks on Tuesdays!]

The Bare Necessities Of Semantics

With all the functional mumbo jumbo hidden away in HTML5, some of us seem to have forgotten what HTML is really all about. Native video support is considered way cooler than the new header tags, somewhat understandably, but from a semantic and structural point of view, these latter elements present the most valuable improvement.

Semantic importance got a serious boost when accessibility became a big deal to us Web developers. But its powers go way beyond making our content available to those lacking the skills to surf the Web in regular ways. For one, making content recognizable to all kinds of crawlers (but most importantly search engines) could greatly improve the results of search queries on the Web. Rather than wading through trailers, film websites and product pages, wouldn’t it be much nicer to filter reviews directly and find out how a certain film has been received? Currently, no trustworthy mechanism exists to recognize or filter a broad range of content types, which is a serious loss for the Web as a whole.

Sm-img1 in When One Word Is More Meaningful Than A Thousand
When looking for reviews, you don’t want to end up on a page with grayed-out links.

If all of that sounds like a far-off dream, then note that once you’ve distinguished between all the elements on your website, you will have little to no trouble styling or adding functional behavior to the page. The combination of context and proper semantics ensures a solid structure for all further front-end work, which is only made stronger by making sure every element is defined correctly.

The (Very Simple) Basics

Absolutely nothing is complex about semantics, and the basics have been preached for a long time now. A recap of the bare minimum won’t hurt anybody, though, so here it goes.

The HTML language has a range of tags with semantic meaning. If none of the available tags suits your needs, then two generic tags (span and div) are the HTML equivalents of the word “thing,” which can be used in combination with one or more classes to add (not necessarily standardized) semantic value to your elements. It’s the microformats idea without the actual microformats. Some basic examples:

  • Main navigation: nav.main (HTML5) or div.navMain;
  • An article: article (HTML5) or div.article;
  • Article header: article>header (HTML5) or div.article>div.header

That’s all there is to it, really. Adding semantic value is about choosing the correct tag(s) and/or applying the correct label(s) to an element. It really makes you wonder why applying this simple concept consistently to professionally developed websites has proven to be so difficult, even today.

For those of you who don’t like the microformats ideology, you could also go all HTML5 and look at the HTML5 Microdata proposition. What follows in this article reflects both methodologies equally, so the choice is entirely up to you.

Sampling The Web

To illustrate my point, I took some quick samples from some of today’s leading websites. By no means do these samples hold any scientific validity, nor is this a purposeful bash of the websites I’ve singled out. They are simply chosen because I believe they best represent their kind. I hope the data speaks for itself either way.

To grasp the semantic consistency within a website, I tried finding some common content types. Content types are easy to recognize and even easier to label. Before I get to the data, though, let’s look at one way we could label products in a Web store:

  • Product detail: div.product;
  • Products added to your basket: .basket li.product;
  • Promo product in a list: .categoryList .product.promo;
  • Etc.

Products are everywhere in a Web store, so it seems logical that the product class would reappear across the pages for every instance of a product on the website. After all, whether a product is located in a “Related items” list, added to a basket or shown in full doesn’t really change its semantic nature, so why change its structure or class name?

Sm-img2 in When One Word Is More Meaningful Than A Thousand
These are all products, appearing as variants or in different contexts.

For my sample, I picked five content types (story, product, video, person, blog post) and picked four websites to represent each content type. To check for semantic consistency, I looked at the labels on a shortlist (a list of content type instances) and the content type’s detail. The following table summarizes my findings:

TypeWebsiteShortlistDetail
StoryBBCdiv.hpDatatable.storycontent
StoryNew York Timesdiv.storydiv#article
StoryCNNul.cnn_bulletbin lidiv.cnn_storyarea
StoryMSNli.terdiv.w649 (?)
ProductAmazondiv.asinItem-
ProductApple Storeli.productdiv.product-selection
ProductPlay.comdiv.infodiv.dvd
ProductYesAsiadiv.itemdiv#productpage
VideoYouTubediv.video-celldiv.video-info
VideoVimeodiv.itemdiv.video_container_hd
VideoDailymotiondiv.videodiv.dmco_box
VideoeBaum’s Worlddiv.mediaitemdiv#videoContentContainer
PersonFacebookdiv.UIFullListingdiv.profile_top_wash and div.profile_bottom_wash
PersonLast.fmdiv.userdiv.user
PersonVirbtable.people tddiv#profile_wrapper.artist
PersonTwitterdiv#following_list span.vcarddiv#profile
Blog postZeldman--
Blog postA List Apartdiv.item- or body.articles
Blog postJens Meiertdiv.item.content .col-1
Blog postWebaimdiv#featuresdiv.section

Apart from last.fm, none of the websites I checked got it right, even though the content types I chose were very easy to label. Apple and the New York Times came quite close, but some of the others are miles away from what you’d expect to find. And that’s just looking at the root tag of the content type. The structure and classes within are often even worse, bordering on complete randomness. Another thing to note is that blogs about Web design seem to score the worst.

Think Components, Not Pages

There is, of course, not one single cause of this problem, nor is the solution simple. But you can make one important mental shift as a front-end developer to give your work more semantic consistency. The key is to stop thinking of a website as a collection of pages and to instead look for common components.

Front-end developers tend to work the same as designers: start with the home page, finish that, and then move on to the second wireframe — copy the reusable components, adapt if needed, and then repeat until all pages are done. This process requires a lot of copying, adapting and checking older pages to find reusable elements. It is a true killer of consistency — invoking spur-of-the-moment labels and destroying semantic consistency.

Because we want consistency, both in structure and semantics, focusing on a single component at a time is better. When you need to write the HTML code for a product, check each wireframe for variations within and across products. Write code that can handle all existing variants. Once that is done, you will have a consistent and solid model to describe your component that you can used wherever you want.

Making It All Happen

I know from experience that this mental shift takes some time to get used to, and the only way to get it working is to throw yourself in and practice. I’ll share some quick pointers to make the whole process a little less daunting.

Think Beyond Styling Needs and Performance

.productList li or .products li

ul li.product

Consider the example above. As Web developers, we’ve been taught that the first option should be preferred. From a performance and styling perspective, this is indeed the case. But putting on your semantic hat, you’ll notice that to recognize the list items in the first example as products, you need to make a deduction. Singling out all products on a page isn’t as easy as looking for the product class. Automated systems should also account for the possibility that a product is defined as a list item inside a parent that refers to a collection of products. Not such a big deal for the human brain, but writing a foolproof, fully automated implementation isn’t as easy.

On top of that, the second option allows for more flexibility because it makes it possible to drop instances of other content types into the same list without running into styling hell, while at the same time ensuring semantic integrity. It wouldn’t be the first time I was asked to merge a news and event shortlist into one big list just because there wasn’t sufficient content to warrant separate lists. The second option would give you a smaller headache, especially if you’re nearing an important deadline.

Bottom line: try to minimize semantic deductions, and keep the code clear and simple. Pick unique class names for components, and stick with them throughout the entire project.

Don’t Mix Responsibilities

I know that many people like to mix wireframing, HTML and even design into one organic and homogeneous process. The downside to this is that you will have a hard time not compromising your work. When you’re designing, writing HTML and CSS is not priority number one; and once the design is done, you’ll find it tough to go back and rework your code to match HTML and CSS standards.

It’s also refreshing to try to build a website based purely on a set of wireframes, without the slightest notion of design. It helps you focus on meaning and makes it easier to spot components that are actually the same but could differ wildly design-wise. And if you’ve done it right, you’ll find that during CSS development, you don’t have to adapt the HTML at all, unless the design calls for major structural changes.

Try to build your HTML templates based on wireframes, and save the design and CSS for when your static HTML templates are completed.

Automate Your Job

Automation is a major key to success. Whether you use existing tools (such as a CMS) or build your own (as we do), automating the job of building static templates could help you to define a component once and reuse the code everywhere that the component is featured in your templates. The process itself (when done right) ensures semantic consistency and is sure to bring you new insight when constructing HTML templates.

At my current job, we build such a tool based on components (recurring HTML code blocks) and schemes (outlines of each template that refer to these components). Thrown in some simple program logic (if and loop statements, parameters) and allow for proper nesting methods, and you’re good to go.

Semantic Consistency Across Projects

Finally, keep a list of components you’ve made over multiple projects. Many components will be relevant for each new project and will be semantically identical, meaning that the HTML structure should be identical just as well (save some wrappers for visual CSS trickery, if you’re into that).

Once you have such a list of components, starting up a new project will be a lot faster, and you’ll have the added benefit of semantic consistency across all of your projects.

Banana ≠ Curvy Yellow Fruit

Semantics is all about identifying objects, but it goes beyond simply slapping a label on every object that comes your way. If you have a blog, and you randomly throw around classes like article, story, blogpost and news, then your website will lack semantic consistency, making all your hard work amount to very little. Semantics have no point when they are not applied consistently, even though today’s technology does very little with them — which, by the way, is no surprise given that locating a simple “product” on most Web stores is nearly impossible these days.

Sm-img3 in When One Word Is More Meaningful Than A Thousand
People looking for bananas might think twice before buying these.

The next time you begin a project, try to view a Web page as a collection of building blocks. Start by constructing these building blocks first, and worry about building the pages later. Come up with a single label for an HTML component, and use it consistently across your website. It won’t make styling harder, and it won’t affect the way you write JavaScript. Over time, you can take it further by being semantically consistent over multiple projects.

If your main job is to develop static HTML templates, try to automate your work. You’ll find that you spend more time writing flexible and solid HTML structures and less time copying and adapting code from point A to point B. It makes your job more interesting and makes the Web a better and more meaningful place.

Further Resources

  • Microformats
    Summarizes the microformats ideology. Read more about using class names as semantic aids.
  • HTML5 Microdata
    Explains how HTML5 is built to standardize the use of flexible semantics.

(al)


© Niels Matthijs for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress