Part 3

CSS PATTERNS AND ADVANCED TECHNIQUES

As you saw in the earlier chapters of this book, much of what CSS is capable of depends heavily on organized and well-formed HTML or XML that's largely self-describing by working in concert with the semantic structure of the markup. Starting out this way, the markup itself functions as a sort of application programming interface (API) for other purposes. One common purpose for such semantic markup is to ease transformations from one format to another or extract data from it, as microformats and RDFa can do today.

In much the same way, CSS itself can benefit from being equally “self-describing.” Writing CSS that is not merely readable but meaningful creates additional patterns and improves the reusability of CSS code whether the goal is to create rules for a set of web sites, user style sheets, JavaScript widgets, or other resources. Style sheets written in this way are then able to more freely move and mirror the semantic structures that they're applied to.

In this part of the book, you'll see how writing meaningful, reusable, modular style sheets can result in better CSS as well as other content when combined with appropriately semantic markup.

Chapter 7 Image

SEMANTIC PATTERNS FOR STYLING COMMON DESIGN COMPONENTS

When developers talk about patterns, they are really talking about tasks, or things they have to do often. In the case of a CSS developer, common tasks might be creating a sidebar, styling a footer, skinning a navigation bar, or creating a mobile- or print-ready layout from an existing design. In turn, each of these tasks can be broken up into smaller chunks of work, where each chunk can be encoded into a particular CSS rule or groups of rules. The goal of creating patterns is to make these rules generic enough that they can be used with minimal modifications in more than one place.

Patterns can also be thought of as conventions, or—to use a linguistic phrase—idioms. As they do in human languages, conventions help ease interoperability among various components. When people talk about burning the midnight oil, we know they're not literally igniting a canister of fuel at midnight, but rather that they are working hard late into the night. Since this is a well-known phrase, communication between people usually runs smoothly. However, if some people weren't familiar with that phrase, then an explanation would be needed. Thus, being familiar with the idioms of a particular language helps you interface with its native speakers.

This phenomenon holds true for markup and CSS code as well. In this chapter, we'll introduce you to two major ways you can add semantics and functionality to your markup: microformats, and RDFa. Next, we'll show you how you can use CSS to style markup that uses these techniques effectively, as well as explain how taking advantage of these markup techniques makes your CSS easier to write and reuse much more logically. Finally, we'll show you how to take what you've learned about code reuse in the form of patterns in your markup and CSS and use it to make everyday tasks like styling various common interface elements a breeze regardless of what project you're working on now or in the future.

Markup patterns and common authoring conventions

Not surprisingly, being able to create CSS patterns depends on already having specific patterns in your markup. Thankfully, patterns are a naturally occurring phenomenon. This happens for a number of reasons; due to the simplicity of HTML and CSS, much of today's web content is created by people copying and pasting code that already exists and then modifying it to suit their needs; web sites with similar needs often have similar implementations. While much variation exists, there begins to emerge a semantic structure to your garden-variety HTML document.

Both of these evolved from the simplest of HTML patterns, so before all that, let's start at the beginning.

The evolution of markup conventions

HTML is a relatively simple language. It has a limited number of elements that represent function (that is, structure), and it used to have a number of elements that depicted form. As you know, the elements depicting form were deprecated and replaced with CSS. What was left were the structural elements, and while the needs of web developers evolved, the language itself stagnated for years.

The most recent incarnation of the HTML language is HTML 4.01, and it includes several “semantically meaningless” structural elements that are routinely overloaded with semantics in particular ways by developers today. For example, consider a fragment of HTML such as the following:

<body>
    <div id="page-wrapper">
        <div id="header">
            <h1>My Header</h1>
        </div>
        <div id="main">
            <div class="section">
                <!-- Other content here. -->
            </div>
            <!-- More sections here. -->
        </div>
        <div id="sidebar">
            <!-- Sidebar content here. -->
        </div>
    </div>
</body>

This is a common pattern that's almost second nature to many web authors today. It describes a document's major sections by providing structural differentiation between the content components in the document. This particular structure, with a “main” area, a “header,” and a “sidebar” is so familiar, in fact, that you could even call it an HTML idiom.

These conventions are also noteworthy for how they've influenced HTML5, which is the version of HTML currently under development as of this writing. In this next major version of HTML, we have full-fledged elements like <section> and <header>. In other words, where authors commonly used markup such as <div class="section">, using HTML5 we will be able to more simply do things like this:

<header>
    <h1>My Header</h1>
</header>
<div id="main">
    <section>
        <!-- Other content here. -->
    </section>
</div>

This is no coincidence; the authors of the HTML5 specification purposefully used common authoring patterns to make decisions about what elements to add or remove from the language, and why. Such convention and consistency is thus an integral part of the evolution of web technology.

Markup patterns can be spread across entire document structures, such as the header-and-section pattern just shown (we call these “wide” patterns), or as small as single attribute and value pairs ("narrow" patterns). Here's another pattern that's even narrower, affecting an individual component on a page, a navigation list in this case:

<div id="main-navigation">
    <ul>
        <li class="selected">
            <a href="/">Home</a>
        </li>
        <!-- More list items here. -->
        <li>
            <a href="/contact/">Contact Us</a>
        </li>
    </ul>
</div>

This pattern—a <div> element containing a single <ul> element, which itself contains <li>s with <a> elements within them—is also a familiar HTML idiom to many developers. What's more, it's actually composed of several nested subpatterns, each level of nesting narrower than its ancestor's. For example, note that one of the list items has a class value of selected. This class name could indicate that the item in the list is the one the user is currently browsing.

The existence of these patterns allows you to create the simple but powerful rules that can apply to large numbers of documents at once. Indeed, some of the most powerful patterns are composed of the most humble parts. HTML5's addition of a <section> element, for instance, is likely to improve CSS because it means that more developers will more consistently use that element for demarcating the structural pieces of their documents, making style sheets that style such “sections” reusable across more published content.

Microformats: reusing markup patterns and adding semantics

The power in reusing existing design patterns and the reuse of conventions into attribute names like this is a central focus for the microformats community. By analyzing common use cases and breaking them down into constituent parts, markup patterns are developed for conveying different semantic meaning. These can be even nested inside one another, and when evolved to a particular degree are ultimately able to suggest the structure of a document based on its content.

Microformats are a community-driven effort to analyze and encode common HTML authoring conventions into specifications of patterns of element, attribute, and attribute values that add semantics and functionality to your markup. These patterns are widely adopted because they are simple and powerful; elemental microformats are atomic semantic building blocks from which compound microformats are built. In turn, compound microformats can be grouped, nested inside other microformats formats, or seamlessly integrated with custom markup without losing either the semantic fidelity acquired by using the microformat or—more to our purposes in this chapter—the styling potential.

In fact, this powerful framework of patterns-inside-patterns offers an incredibly rich array of styling hooks, and its implicit structural support makes CSS more readable, too.

How microformats work

The class attribute holds special meaning to CSS; it's one mechanism by which you can target markup elements with your CSS selectors.

Limitations to regular web development imposed by using microformats are worth mentioning. The fact is that microformats make use of core HTML properties in a way that the designers of the language never envisioned. This means that while microformats can provide unmatched benefits, they have some drawbacks and limitations that you may run into when you work with them.

The most obvious limitation is that, since many microformats rely heavily on class attribute values, you need to be cautious that the class names you choose to use do not clash with class names that are used in microformats on your pages. If such a clash occurs, you may find your CSS rules applying to elements you didn't intend, which can cause layout issues or other design problems. Thankfully, these issues are relatively easy to spot with a good inspector tool such as Firebug.

With recent surges in the adoption of semantic markup techniques like microformats, developers are running into naming collisions more and more frequently. Some developers are of the opinion that microformat values should be given “pseudo-namespaces” to avoid such class name collisions.1 Of course, one easy way to work around the problem is to give your own class names a prefix or suffix, a technique heavily promoted as a best practice in JavaScript development already. This can be cumbersome, but at least this practice is effective and would help keep your custom classes distinct from commonly used vocabularies.

__________

1. Jens Meiert wrote more about this interesting topic on a blog post published at http://meiert.com/en/blog/20070913/microformats-and-pseudo-namespaces/.

For example, one property of the hCard microformat is declared with a class attribute value of photo. There are lots of situations where such a class name could be used, both on <img> elements and on others, such as in the following example fragment:

<div class="photo">
<img src="/raven.jpg"Image
    alt="A black raven stands perched on a tree branch." />
    <p class="caption">
        The blackness of a Raven often symbolized darkness and night.
    </p>
</div>

This is where descendant selectors and specificity really come in handy. Simply using a .photo selector may target too many subjects, so if you know that all of your hCard's photographs use an <img> (and not, say, an <object>) element, it's safer to use img.photo as your selector. An even better selector would take advantage of the hierarchical HTML structure, and could therefore look like .vcard.photo img.

There are already some projects that are making use of these ideas on a large scale. The Oomph Microformats Toolkit2 is a recent example, providing plug-and-play style sheets that attach themselves to microformatted content in your pages. Well before that in 2006, however, Jon Hicks was one of the first to provide a downloadable user style sheet that visibly highlighted microformats on web pages3 and in the same year, John Allsopp demonstrated how designers could make use of CSS in conjunction with hCard microformats4 for simple, logical styling. More recently, these ideas have also been used to style XFN and rel-license links.5

Despite their benefits, since microformats rely on embedding specific patterns inside of ordinary markup, they have some severe limitations: they can accomplish only what the markup itself will permit, they have few mechanisms for extensibility, and they can impinge upon other uses of the same markup (or class names). Due in part to these dangers, microformats can take a long time to mature and build functionality on top of. The microformats community is strictly focused on creating building blocks in markup that solves the most generic problems with the most broadly applicable solutions—the so-called 80 percent of the challenge with 20 percent of the complexity.

A full discussion of microformats is beyond the scope of this book, but thankfully there are some excellent resources available for you to learn more. As microformats are a semantic technique as well as a solid engineering practice, we strongly encourage you to pick up a copy of John Allsopp's book Microformats: Empowering Your Markup for Web 2.0.6

RDFa: adding extensible vocabularies to semantic markup

Since microformats typically don't try to solve specific cases for niche fields, RDFa picks up where microformats leave off by adding an open-ended mechanism for extending the semantics of markup without limitations from the host markup language itself. In other words, RDFa is a simple and, more important, language-agnostic way of giving documents the means to be self-describing. RDFa uses a set of attributes (hence the trailing “a”) that can be attached to any element whose values reference other elements in the same or other documents.

__________

2. The Oomph Microformats Toolkit actually provides additional tools and widgets that work with microformats. You can learn more about the CSS portions of the toolkit at http://visitmix.com/Lab/Oomph#Style.

3. Jon Hicks's user style sheet can be downloaded from http://hicksdesign.co.uk/journal/highlight-microformats-with-css.

4. John Allsopp's article was published at http://24ways.org/2006/styling-hcards-with-css.

5. Christopher Schmitt shows several additional illustrative examples on an Opera Developer Community blog post at http://dev.opera.com/articles/view/styling-xfn-and-rel-license-links/.

6. John Allsopp's book (friends of ED, 2007) also has a useful free companion web site available at http://microformatique.com.

Recall from our discussion of the linguistics of markup languages in Chapter 1 that markup languages contain rudimentary but powerful grammars in three major forms: which elements are being used, which attributes and attribute values those elements have, and the hierarchical context of elements in relation to one another. The ability to nest one element within another creates implicit relationships between different elements, but is structurally limiting. If elements are required to be nested to reference one another, neither the document itself nor the rest of the Web can be flexibly structured.

RDFa adds a fourth grammatical form by allowing one element, via an attribute and value pair, to reference any other element anywhere else on the Web by way of its unique web address or URI. Rather than referring to a document, now the reference actually refers to an object—a person, idea, place, event, book, or some other thing. The attribute used to do this is the about attribute. For example, given a transcript of a speech we can now explicitly refer to and describe it without requiring that the two pieces of markup be structurally attached to one another.

<blockquote cite="http://example.com/myspeech" id="my-speech">
    <p>Once upon a time[...]</p>
</blockquote>

By giving this speech an explicit id attribute and unique value, we then use this value in a different element's about attribute:

<p>
    The speech was written by
    <a about="#my-speech" property="dc:creator"
        href="http://example.com/~bobsmith/">
        Bob Smith
    </a>
</p>

Here, we've described the speech as being created by Bob Smith. RDFa gets its name from the fact that it borrows a concept from the W3C's Resource Description Framework (RDF) called a triple, itself merely a way of describing two objects (two “things”) with a relationship to one another. In the prior example, the quoted speech is one object (the subject), Bob Smith is the other (the predicate), and the fact that Bob wrote the speech (that is, he is the creator) is the relationship. The only magic here is that the meaning of a “creator” has already been defined by a vocabulary we're referring to as “dc” (short for Dublin Core7).

__________

7. The Dublin Core Metadata Initiative is an open industry collaboration that attempts to provide standardized and general metadata vocabularies useful for describing documents on the Web. Learn more at http://dublincore.org/.

In addition to the attributes already present in XHTML that RDFa makes use of such as rel and rev, RDFa adds the following attributes:

  • property: Specifies a URI (or CURIE, simply a more compact URI) that references a particular term in a given vocabulary; the marked-up content is then known to be that “thing.” For instance, while blogging about this book, we might mark up its title like this: <cite property="dc:title">AdvancED CSS</cite>.
  • about: Optionally provides an explicit reference to a second object that the current element describes.
  • content: Optionally used with the property attribute to provide an explicit, machine-readable interpretation of the content of an element. For example, an element such as <span property="dc:date" content="2009-05-17">May 17, 2009</span> reads to humans as “May 17, 2009” but reads as 2009-05-17 to machines.
  • datatype: Optional CURIE that specifies the data type of text specified for use with the property attribute (for example, string or integer, useful for ensuring data integrity for machine processing).
  • typeof: Optional CURIE value that declares a new data item.
  • resource: A URI or CURIE, which expresses the resource of a relationship.

It's this flexibility with the RDF triple and the extensible, highly specific capabilities that RDFa brings to markup languages that distinguishes it and makes it infinitely more scalable than the microformats initiative. Some might consider these two technologies in competition, but really they are not; both are simply differing approaches to solving the same challenge of having a more semantic and understandable markup framework on the Web. Some crossover exists, but both microformats and RDFa can coexist within the same markup.8

Although not new, RDFa is seeing greater adoption very recently than ever before. Notably, several of the redesigned web sites of the US government now sprinkle RDFa in their Creative Commons–licensed copyright statements.9

Opportunities and benefits of semantics for CSS developers

Whether semantic markup is in the form of microformats, RDFa, or some other construction, it is guaranteed to have some specific benefits for CSS developers. Patterns make it easier for multiple people working on the same code to work together, because they each have a sort of reference to follow in their work. Furthermore, when patterns become well known within a team or a community, the code itself becomes easier to grok for newer team members or contributors in the wider community (in the case of an open source project). Additionally, as we saw in the previous chapter, having consistency in your code increases reuse and optimization opportunities.

Another benefit of semantic markup is the fact that additional meaning exists in the content itself, and you can expose this extra meaning to end users with visual signals and cues. When your markup is smart enough to understand that a particular block is about a person, a visual symbol such as an icon or avatar can more easily be placed next to that block of text.

__________

8. Toby Inkster provides a great example of mixing complex markup that uses both an hCard microformat and various aspects of RDFa at http://examples.tobyinkster.co.uk/hcard.

9. David Peterson was one of the earliest people to notice and publicize this on a blog post at http://www.sitepoint.com/blogs/2009/01/29/president-obama-uses-rdfa/.

In other words, when it comes to semantics, you should be thinking in terms of things, or objects. To do this, you must have a fair amount of familiarity with the content you have. Are you marking up a speech? The “thing” is the speech; it has properties you should describe in the markup you use, such as the date and time the speech was delivered, the name of the orator, a reference to the source where you got it, and so forth.

Encoding semantics naturally leads to creating patterns because there are, for instance, many speeches being given around the world and many of them share the same sorts of properties. Such patterns build on one another; the orator of the speech is a person, and if you've already got CSS rules that apply to “markup that describes people,” this can be plugged into the details of the speech to highlight the orator. So it's not the semantics per se that you leverage with CSS, but rather the semantic patterns that emerge within one another like building blocks.

These building block patterns can be evident on a single page (often on “archive” or other sorts of pages that list collections of things), across a whole site, or—most interestingly—across the entire Web. With web-wide patterns, CSS becomes even more powerful. As it turns out, such patterns are appearing more frequently, and what's more, CSS that takes advantage of them is also appearing. Next, let's examine how you can write this sort of CSS yourself.

Styling microformats with CSS

Most microformats overload the use of the class attribute in order to imbue the markup with the necessary semantics to produce functional applications. However, not all microformats use the class attribute, and other microformats use a combination of attributes and elements in sequence (known as patterns). In theory, styling microformats with CSS shouldn't be too hard, since CSS 2.1 gives us all the mechanisms we need to do so in the form of its attribute selectors.

Unfortunately, not all mainstream browsers today support the attribute selector syntaxes, and as a result this throws a monkey wrench into the straightforwardness of styling microformats that don't use the class attribute. However, simple solutions—relying on additional site-specific structural markup patterns, or adding your own class names into the mix for the purposes of explicit CSS hooks—can be used to great effect to work around the problems in these cases.

Styling rel-tag links

A tag is a short, descriptive word or phrase that provides a moniker to describe piece of content. By using the rel attribute inside a link, you can more fully describe the kind of content that the link points to. When the rel attribute has a value of tag, the markup indicates that the destination of the link is a page about a particular subject. For example, here's a rel-tag link pointing to a page that lists blog posts about CSS:

<a href="http://technorati.com/tag/css" rel="tag">Cascading StyleImage
    Sheets</a>

In this markup, the entirety of the microformat is the pattern of using the rel attribute with a value of tag, no more and no less.

Ordinarily, this should be as easy as

[rel=tag] { /* declarations for a tag; perhaps a background image? */ }

Unfortunately, this attribute selector syntax doesn't always work. Instead, we recommend you use an easily recognizable class name, perhaps, say, rel-tag? So, with your own class attribute here, we use this HTML, which is still a valid rel-tag microformat:

<a href="http://technorati.com/tag/css" rel="tag" class="rel-tag">Image
    Cascading Style Sheets</a>

with this CSS:

[rel=tag], .rel-tag {
    /* declarations for a tag; perhaps a background image? */
}

This will group both selectors with the same declarations, and voilà: mostly painless backward compatibility ahoy.

Styling an hCard

An hCard is modeled after the ISO's vCard standard for electronic business cards. This microformat is used for encoding contact information for people or places. This is a compound microformat that can make use of several elemental microformats, such as adr for encoding addresses and geo for encoding latitude and longitude coordinates. However, these are optional and so an hCard can be incredibly simple. Here's a simple paragraph that mentions Tim Berners-Lee, the director of the W3C:

<p>
    Tim Berners-Lee is the Director of the World Wide Web Consortium.
</p>

This is simple enough, but this information could be encoded in a machine-readable hCard microformat with nary much effort at all. hCards rely on nested HTML structures, the outermost element of which contains the class name vcard. In the simplest case, an hCard need only contain one additional element, with a class name of fn (standing for “formatted name”). A full, but simple, hCard microformat thus looks like

<p class="vcard">
    <span class="fn">Tim Berners-Lee</span>
    is the Director of the World Wide Web Consortium.
</p>

Since the attributes (in this case, class names) are what encode the semantics, the HTML itself can be altered. We can turn Tim Berners-Lee's name into a link to his homepage at the W3C:

<p class="vcard">
    <a class="fn" href="http://www.w3.org/People/Berners-Lee/">
        Tim Berners-Lee
    </a>
    is the Director of the World Wide Web Consortium.
</p>

With homepage information, it now becomes trivial to encode this into the hCard itself:

<p class="vcard">
    <a class="fn url" href="http://www.w3.org/People/Berners-Lee/">
        Tim Berners-Lee
    </a>
    is the Director of the World Wide Web Consortium.
</p>

The simple addition of the url class to the link signifies that the value of this link's href attribute should be used as the web address on this particular hCard. Also note that we've still got more information in this paragraph that describes Tim Berners-Lee. We can add this to the hCard as well:

<p class="vcard">
    <a class="fn url" href="http://www.w3.org/People/Berners-Lee/">
        Tim Berners-Lee
    </a>
    is the <span class="role">Director</span> of the
    <span class="org">World Wide Web Consortium</span>.
</p>

When you style microformats with nested HTML structures, it's safest to use descendant selectors in order to increase readability and decrease the chance for collisions in common class names. Therefore, for hCards, all your selectors should start with .vcard.

One way to think about this is to read CSS selectors as though they were English. In the first selector, we are saying, “Style all tags within an hCard...” whereas in the second selector we are saying, “Style all tags...” Naturally, CSS's specificity rules let us create two distinct looks for rel-tag microformats that exist inside or outside of hCards:

.vcard [rel=tag] { /* "Style all tags inside of an hCard... "*/ }
[rel=tag] { /* "Style all tags..." */ }

Using descendant selectors in this way is arguably the single most powerful technique for creating plug-and-play style sheets. As you develop styles for markup patterns that are building blocks such as these microformats, it behooves you to start with specific selectors over more general ones instead of the typical CSS workflow that favors generality and inheritance over specifics. This way, you can be assured that your styles will only apply to the appropriate parts, or components, on the page.

Styling an hCalendar

An hCalendar microformat is another compound microformat that encodes information about events, such as the time and date they occur, where they take place, what they're about, and so forth. hCalendars are composed of a number of elemental microformats just like hCards, including adr for addresses, and can even contain hCards for describing attendees, contact information, and organizers. In its simplest form, an hCalendar event only needs to contain a start time and a summary, so it can also remain pretty simple. Here's a note about an upcoming “unconference” (a conference-like but ad hoc and informal gathering of like-minded folk):

<p>
    On March 8<sup>th</sup>, I will be participating in the next local
    BarCamp!
    John Smith has put lots of time into (un)organizing it, and I am
    really excited to meet
    Jane Doe and her brother, Joe, when I attend.
</p>

Turning this into an hCalendar is just as straightforward as it was for an hCard. We merely mark the date and the topic with appropriate markup:

<p class="vevent">
    On <abbr title="2009-03-08" class="dtstart"> March 8<sup>th</sup>Image
    </abbr>, I will be participating
    in the next local <span class="summary">BarCamp</span>!
    John Smith has put lots of time into (un)organizing it, and I am
    really excited to meet
    Jane Doe and her brother, Joe, when I attend.
</p>

As before, we still have plenty of additional information we could add here. For instance, let's turn the BarCamp text into a link to the BarCamp homepage. By doing this and adding the url class, the href value becomes the web address of the event:

<p class="vevent">
    On <abbr title="2009-03-08" class="dtstart">March 8<sup>th</sup>Image
    </abbr>, I will be participating
    in the next local
    <a class="summary url" href="http://barcamp.org/">BarCamp</a>!
    John Smith has put lots of time into (un)organizing it, and I am
    really excited to meet
    Jane Doe and her brother, Joe, when I attend.
</p>

Of course, we also have a bunch more information about the event that may be plain for you to see but that a computer can't quite make out nearly as easily. We know that John Smith has helped organized the event, and that Jane and Joe Doe will both be in attendance. We can mark this information up as well:

<p class="vevent">
    On <abbr title="2009-03-08" class="dtstart">March 8<sup>th</sup>Image
    </abbr>, I will be participating
    in the next local
    <a class="summary url" href="http://barcamp.org/">BarCamp</a>!
    <span class="vcard fn organizer">John Smith</span>
    has put lots of time into (un)organizing it,
    and I am really excited to meet
    <span class="vcard fn attendee">Jane Doe</span> and her brother,
    <span class="vcard fn attendee">Joe</span>, when I attend.
</p>

As you can see, we've used hCards to encode the names of the people organizing and attending the event, although we didn't have to. This single block of HTML markup now has four distinct microformats inside it (actually, five, if you count the datetime design pattern being used in the <abbr> element).

As before, the CSS selectors for styling such a microformat should mirror the markup's structure. You can also use the element itself to create visual differentiation in how to display such embedded event information. For example, you might want to display a list of events as square blocks, and you can accomplish this by floating them all. Events embedded as part of plain, inline text might be differently styled such that the date itself is called out with an icon. You can even be specific to the point of matching particular dates.

li.vevent {
    float: left;
    width: 250px;
    height: 250px;
    margin: 5px 10px;
}
/* ... */
.vevent abbr[title$="-03-08"] { /* match March 8th */
    padding-left: 20px;
    background-image: url(cal-03-08-inline.png);
    background-position: left middle;
    background-repeat: no-repeat;
}

Styling RDFa with CSS

As the “a” in RDFa stands for attributes, you can instantly see the direction with which your CSS selectors need to be written to style this code. Beyond the styling hooks that the RDFa attributes add to your document themselves, the values in these attributes are also structured in such a way as to make it possible to use CSS to target certain elements.

For instance, say you wanted to style all Dublin Core metadata in a particular way. Since RDFa is an extension to XHTML, and XHTML is itself an application of XML, you start by supplying a localized namespace for the Dublin Core properties. To make RDFa distillers happy, you need to use a modified DOCTYPE as well as add a few additional attributes to the root html and head elements of your document.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
    "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html version="XHTML+RDFa 1.0"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:dc="http://purl.org/dc/elements/1.1/">
    <head version="XHTML+RDFa 1.0"
        profile="http://www.w3.org/1999/xhtml/vocab">

In this code snippet, we've used the XHTML+RDFa document type declaration, and added the appropriate vocabulary profile to the head element. The part of this code that's relevant to the Dublin Core metadata we're going to style is in the xmlns:dc attribute:

xmlns:dc="http://purl.org/dc/elements/1.1/"

We'll discuss XML namespaces in more detail in Chapter 9, but for now it's important to recognize certain pieces of this attribute and value pair. We have the attribute itself, xmlns, followed by a colon (:), followed by a CURIE prefix. In this case, that prefix is dc. However, the document author defines what the prefix will be. In other words, we could also have used code like this:

xmlns:dublincore="http://purl.org/dc/elements/1.1/"

That's perfectly valid as well, although in practice many people tend to use the more compact dc prefix.

Now that we have access to the Dublin Core vocabulary in our document, we can use it in the values of the RDFa code we're going to add to our document. Take some HTML describing web browsers, for example:

<ul>
    <li id="InternetExplorer">
        Internet Explorer, byImage
        <span about="#InternetExplorer" property="dc:creator">Microsoft, Inc.
    </li>
    <li id="Safari">
        Safari, Mobile Safari, byImage
        <span about="#Safari" property="dc:creator">Apple, Inc.</span>
    </li>
</ul>

What we have, obviously, is a list of web browsers and their manufacturers. The manufacturing companies are marked up with the RDFa property attribute, and these attribute values are using the Dublin Core vocabulary to denote that they are the creators of the particular browsers.

The styling hook we can use here is the RDFa itself, and we can do so in several ways. If we want to style any of the Dublin Core metadata, we can use this:

[property^="dc:"]

In this selector, we use the CURIE prefix we defined earlier, dc, followed by a colon as part of an attribute matching CSS selector. However, if we're developing CSS and don't necessarily know what the CURIE prefix will be, in many situations we can also do something like this:

[property$=":creator"]

Here, we've just reversed the attribute matching selector so it matches a CURIE reference (the part after the colon) instead of the CURIE prefix. In both examples, the colon is included in the CSS selector in order to more precisely match CURIE values, and not just plain string values.

Although a reference only needs to be unique inside a particular vocabulary, and there may be some overlap of functionality in some vocabularies, in practice few documents make use of overlapping vocabularies so CURIE references are usually safe styling hooks. In documents with an abundance of CURIE references, using descendant, type, and longer chains of other simple selectors to increase the specificity of a rule's subjects is a natural way to create ever more precise CSS.

Summary

On today's Web, having a solid structure for your data is essential. As the Web evolved, patterns of structured markup emerged and became ubiquitous among many web pages. This consistency enabled developers to more easily share and manipulate the data being published. To encourage this consistency even further, future revisions to core web technologies such as HTML5 are embedding the patterns that have emerged naturally into the language of the Web itself.

Microformats and RDFa are similar evolutions that embed semantics into the highly structured markup of well-formed data. Both of them offer numerous styling hooks that allow you to expose the meaning of the content they describe. Microformats give you particular classes and nested element patterns, whereas RDFa gives you particular attributes and a structure for those attributes' values called CURIEs. By writing CSS in a specific-to-general way instead of the usual general-to-specific method, you can make style sheets that style blocks of structured markup as components, like specific people or events.

Lots of the discussion in this chapter focused on concepts of reuse in markup and how you can leverage these markup patterns employed by the wider development community in your CSS. However, there are also patterns that are specific to the visual aspects of CSS without as much reliance on the markup underpinning it. In the next chapter, we'll explore these other CSS patterns in more detail, and examine how the evolution of such patterns ultimately resulted in CSS frameworks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset