Home Web Development Responsive Web Design with HTML5 and CSS - Third Edition

Responsive Web Design with HTML5 and CSS - Third Edition

By Ben Frain
books-svg-icon Book
eBook $62.99 $43.99
Print $78.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $62.99 $43.99
Print $78.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Writing HTML Markup
About this book
Responsive Web Design with HTML5 and CSS, Third Edition is a renewed and extended version of one of the most comprehensive and bestselling books on the latest HTML5 and CSS tools and techniques for responsive web design. Written in the author's signature friendly and informal style, this edition covers all the newest developments and improvements in responsive web design including better user accessibility, variable fonts and font loading, CSS Scroll Snap, and much, much more. With a new chapter dedicated to CSS Grid, you will understand how it differs from the Flexbox layout mechanism and when you should use one over the other. Furthermore, you will acquire practical knowledge of SVG, writing accessible HTML markup, creating stunning aesthetics and effects with CSS, applying transitions, transformations, and animations, integrating media queries, and more. The book concludes by exploring some exclusive tips and approaches for front-end development from the author. By the end of this book, you will not only have a comprehensive understanding of responsive web design and what is possible with the latest HTML5 and CSS, but also the knowledge of how to best implement each technique.
Publication date:
April 2020
Publisher
Packt
Pages
408
ISBN
9781839211560

 

Writing HTML Markup

HTML stands for Hypertext Markup Language. It is a language that allows content to be marked up in a manner that makes it more understandable to technology, and then in turn to humans.

You can have content on the web without CSS or without JavaScript. But you can't have content without HTML.

It's a common misconception that HTML is the easy part of authoring web pages and applications. Writing HTML is often dismissed out of hand as something anyone can do easily. My experience tells me HTML is easy to get wrong and not a lot else.

Also consider that for users of the web without sight or who have impaired vision, the way you author HTML can turn content from a confusing unusable mess, into a meaningful, useful, and delightful experience. Sighted users who rely on assistive technology for other reasons can also enjoy web pages far more easily if they have been marked up correctly.

Writing good quality HTML is not a specific need of responsive web design. It's far more important than that. It's a prerequisite of anything that you want to be accessible to all users of the web.

This chapter is therefore going to be about writing HTML markup. We will be considering the vocabulary of HTML, its semantics, or, more succinctly, the way we can use the elements of HTML to describe the content we place in markup.

HTML is what's known as a living standard. A few years back, the latest version was typically referred to as HTML5, a buzzword that helped identify modern web techniques and approaches. It's the reason this book is named "Responsive Web Design with HTML5 and CSS" instead of simply "Responsive Web Design with HTML and CSS." Back in 2012, you could more easily highlight that your techniques were modern by using the terms HTML5 and CSS3. As I write this in 2020, this distinction is less important. To read the living standard, head over here: http://www.w3.org/TR/html5/.

The topics we will cover in this chapter are:

  • Starting HTML pages correctly
  • The forgiving nature of HTML5 markup
  • Sectioning, grouping, and text-level elements
  • Putting HTML elements to use
  • WCAG accessibility conformance and WAI-ARIA for more accessible web applications
  • Embedding media
  • Responsive video and iframes

HTML also provides specific tools for handling forms and user input. This set of features takes much of the burden away from more resource heavy technologies like JavaScript for things like form validation. However, we're going to look at HTML forms separately in Chapter 10, Conquer Forms with HTML5 and CSS.

The basic structure of an HTML page is like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Web Page Structure</title>
</head>
<body></body>
</html>

When writing HTML, you will typically be "marking up" or writing content inside a series of tags or elements. The majority of elements in HTML have an opening and closing tag. A few, like the preceding meta example, are void and hence "self-closing."

There's only a limited number of self-closing or void elements, defined here: https://html.spec.whatwg.org/multipage/syntax.html#void-elements.

They are referred to as void elements because they have no contents. Presently the void tags are area, base, br, col, embed, hr, img, input, link, meta, param, source, track, and wbr.

To exemplify the opening and closing nature of HTML tags, a paragraph of text would be most suitably marked up with an opening <p> at the beginning and a closing </p> at the end. Note the forward slash on the closing tag, as that's the differentiator between the opening and closing tags.

Although we are about to cover the head section, which is the content between the opening <head> and closing </head> tags, be aware that the lion's share of HTML authoring is done in the body section.

 

Getting the start of HTML pages right

We will begin at the start, which seems the logical place to start. Let's consider the opening elements of an HTML page and ensure we fully understand all the essential component parts.

Like so many things with the web, remembering the exact syntax of each thing inside the head section is not particularly important. Understanding what each thing is for is important, however. I generally copy and paste the opening code each time, or have it saved in a text snippet, and I would recommend you do too.

The first few lines of an HTML page should look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />

The doctype

So, what do we actually have there? First of all, we opened our document with the HTML5 Doctype declaration:

<!DOCTYPE html>

If you're a fan of lowercase, then <!doctype html> is just as good. It makes no difference.

The html tag and lang attribute

After the Doctype declaration, we open the html tag; the first and therefore root tag for our document. We also use the lang attribute to specify the language for the document, and then we open the <head> section:

<html lang="en">
<head>

Specifying alternate languages

According to the W3C specifications (http://www.w3.org/TR/html5/dom.html#the-lang-and-xml:lang-attributes), the lang attribute specifies the primary language for the element's contents and for any of the element's attributes that contain text. You can imagine how useful this will be to assistive technology such as screen readers. If you're not writing pages in English, you'd best specify the correct language code. For example, for Japanese, the HTML tag would be <html lang="ja">.

For a full list of languages, take a look at http://www.iana.org/assignments/language-subtag-registry.

Character encoding

Finally, we specify the character encoding, which in simple terms tells the browser how to parse the information contained within. As the meta tag is a void element, it doesn't require a closing tag:

<meta charset="utf-8" />

Unless you have a good reason to specify otherwise, the value for the charset is always utf-8.

 

The forgiving nature of HTML5 markup

If you're conscientious about how you write HTML markup, you'll typically use lowercase for the most part, wrap attribute values in straight quotation marks (not curly ones!), and declare a type for the scripts and style sheets you link to. For example, perhaps you link to a style sheet like this:

<link href="CSS/main.css" rel="stylesheet" type="text/css" />

The fact is that HTML5 doesn't require such precision. It's just as happy to see this:

<link href=CSS/main.css rel=stylesheet >

Did you notice that? There's no end forward slash at the end of the tag, there are no quotation marks around the attribute values, and there is no type declaration. However, easy-going HTML5 doesn't care. The second example is just as valid as the first.

This more lax syntax applies across the whole document, not just linked assets. For example, specify a div like this if you like:

<div id=wrapper>

That's perfectly valid HTML5. The same goes for inserting an image:

<img SRC=frontCarousel.png aLt=frontCarousel>

That's also valid HTML5. No end tag/slash, no quotes (although you would still need quotes if the value had white space in), and a mix of capitalization and lowercase characters. You can even omit things such as the opening <head> tag and the page still validates!

Want a shortcut to great HTML5 code? Consider the HTML5 Boilerplate (http://html5boilerplate.com/). It's a premade best practice HTML5 file. You can also custom build the template to match your specific needs.

A sensible approach to HTML markup

Personally, I like writing my markup quite strictly. That means closing tags, quoting attribute values, and adhering to a consistent letter case. One could argue that ditching some of these practices would save a few bytes of data but that's what tools are for (any needless characters/data could be stripped if needed). I want my markup to be as legible as possible and I would encourage others to do the same. I'm of the opinion that clarity in authoring code should trump brevity.

When writing HTML documents, therefore, I think you can write clean and legible code while still embracing the economies afforded by HTML5. To exemplify, for a CSS link, I'd go with the following:

<link href="CSS/main.css" rel="stylesheet" />

I've kept the closing forward slash at the end of the element and the quotation marks but omitted the type attribute. The point to make here is that you can find a level you're happy with yourself. HTML5 won't be shouting at you, flagging up your markup in front of the class, and standing you in a corner for not validating. However you want to write your markup is just fine. No, who am I kidding, I can't let it go—I want you to know that if you're writing your code without quoting attribute values and closing your tags, I am silently judging you!

Despite HTML5's looser syntax, it's always worth checking whether your markup is valid. Checking that markup validates catches basic human errors like missing or mismatched tags, missing alt attributes on images, incorrectly nested elements, and so on. The W3C validator was created for just this reason: http://validator.w3.org/.

Enough of me berating writers of slacker markup. Let's look at some more benefits of HTML5.

All hail the mighty <a> tag

The <a> tag is arguably the most important and defining tag of HTML. The anchor tag is the tag used to link from the document a user is on to another document elsewhere on the internet, or another point in the same document.

You can read the specification for the <a> element here: https://www.w3.org/TR/html52/textlevel-semantics.html#the-a-element.

A welcome benefit of HTML5 is that we can wrap multiple elements in an <a> tag. Previously, if you wanted your markup to validate, it was necessary to wrap each element in its own <a> tag. For example, look at the following code:

<h2><a href="index.html">The home page</a></h2>
<p><a href="index.html">This paragraph also links to the home page</a></p>
<a href="index.html"><img src="home-image.png" alt="A rendering of the home page" /></a>

Nowadays, we can ditch all the individual <a> tags and instead wrap the group, as demonstrated in the following code:

<a href="index.html">
  <h2>The home page</h2>
  <p>This paragraph also links to the home page</p>
  <img src="home-image.png" alt="A rendering of the home page" />
</a>

The only limitations to keep in mind with <a> tags are that, understandably, you can't wrap one <a> tag within another <a> tag or other interactive element (such as a button) and you can't wrap a form in an <a> tag either.

That's not to say you can't physically do it. I doubt your text editor is going to start a fight with you about it, but don't be surprised if things don't work as expected in the browser if you do!

 

New semantic elements in HTML5

My dictionary defines semantics as "the branch of linguistics and logic concerned with meaning." For our purposes, semantics is the process of giving our markup meaning. Why is this important?

Most websites follow fairly standard structural conventions; typical areas include a header, a footer, a sidebar, a navigation bar, and so on. As web authors, we will often name the div elements we use to more clearly designate these areas (for example, <div class="Header">). However, as far as the code itself goes, any user agent, and that includes a web browser, screen reader, or search engine crawler, parsing that content couldn't say for sure what the purpose of each of these div elements is. HTML5 solves that problem with new semantic elements.

For the full list of HTML5 elements, get yourself (very) comfy and point your browser here: http://www.w3.org/TR/html5/semantics.html#semantics.

We won't cover every one of the new elements here, merely those I feel are the most beneficial or interesting in day-to-day responsive web design use. After we have gone through the elements and gained an understanding of their intended use, we will look at some content examples, and consider how they might be best marked up. Then, to end the chapter I'm going to set you a bigger challenge!

In terms of the HTML specification, the elements we will be looking at fall into one of three groups:

  • Sectioning elements, for the broadest strokes in a HTML page. These are the kind of elements to use for header, footer, and sidebar areas.
  • Grouping elements, which are used to wrap associated elements. Think of paragraphs, blockquotes, and content of that nature.
  • Text-level semantics, which are the elements we use to designate particulars, like a section of bold or italic text or code.

We will now look at the most useful from each of these sections in turn.

The <main> element

For a long time, HTML5 had no element to demarcate the main content of a page. It was argued that the content that wasn't inside one of the other new semantic HTML5 elements would, by negation, be the main content. Thankfully, we now have a more declarative way to group the main content: the aptly named <main> tag. Whether you're wrapping the main content of a page or the main section of a web-based application, the main element is what you should be grouping it all with. Here's a particularly useful line from the specification:

The main content area of a document includes content that is unique to that document and excludes content that is repeated across a set of documents such as site navigation links, copyright information, site logos and banners and search forms (unless the document or application's main function is that of a search form).

It's also worth noting that there shouldn't be more than one main on each page (after all, you can't have two main pieces of content) and it shouldn't be used as a descendent child element of some of the other semantic HTML5 elements, such as article, aside, header, footer, nav, or header.

Read the official line on the main element at http://www.w3.org/TR/html5/grouping-content.html#the-main-element.

The <section> element

The <section> element is used to define a generic section of a document or application. For example, you may choose to create sections around your content: one section for contact information, another section for news feeds, and so on. It's important to understand that it isn't intended for styling purposes.

If you need to wrap an element merely to style it, you should continue to use a div as you would have before.

When working on web-based applications, I tend to use section as the wrapping element for visual components. It provides a simple way to see the beginning and end of components in the markup.

You can also qualify for yourself whether you should be using a section based upon whether the content you are sectioning has a natural heading within it (for example, an h1-h6). If it doesn't, it's likely you'd be better off opting for a div.

To find out what the W3C specification says about <section>, go to the following URL: http://www.w3.org/TR/html5/sections.html#the-section-element.

The <nav> element

The <nav> element is used to wrap major navigational links to other pages or parts within the same page. As it is for use in major navigational blocks it isn't strictly intended for use in footers (although it can be) and the like, where groups of links to other pages are common. If you usually mark up your navigational elements with an unordered list (<ul>) and a bunch of list tags (<li>), you may be better served with a nav and a number of nested <a> tags instead.

To find out what the W3C specification says about <nav>, go to the following URL: http://www.w3.org/TR/html5/sections.html#the-nav-element.

The <article> element

The <article> element, alongside <section>, can easily lead to confusion. I certainly had to read and re-read the specifications of each before it sank in. Here's my reiteration of the specification. The <article> element is used to wrap a self-contained piece of content. When structuring a page, ask whether the content you're intending to use within an <article> tag could be taken as a whole lump and pasted onto a different site and still make complete sense. Another way to think about it is, would the content that you are considering wrapping in an <article> actually constitute a separate article in an RSS feed? Obvious examples of content that should be wrapped with an <article> element would be blog posts or news stories. Be aware that if you are nesting <article> elements, it is presumed that the nested <article> elements are principally related to the outer article.

You can read the specification for the <article> element here: http://www.w3.org/TR/html5/sections.html#the-article-element.

The <aside> element

The <aside> element is used for content that is tangentially related to the content around it. In practical terms, I often use it for sidebars, or content as a little tip about a related subject in a blog post. It's also considered suitable for pull quotes, advertising, and groups of navigation elements; basically, anything not directly related to the main content would work well in an aside. If it was an e-commerce site, I'd consider areas like "Customers who bought this also bought" as prime candidates for an <aside>.

For more on what the W3C specification says about <aside>, visit http://www.w3.org/TR/html5/sections.html#the-aside-element.

The <header> element

Practically, the <header> can be used for the "masthead" area of a site's header but also as an introduction to other content, such as an introduction section within an <article> element. You can use it as many times on the same page as needed. You could have a <header> inside every <section> on your page for example.

Here's what the W3C specification says about <header>: http://www.w3.org/TR/html5/sections.html#the-header-element.

The <footer> element

Like the <header>, the <footer> element doesn't take part in the outline algorithm (more on that in the following section) so doesn't section content. Instead it should be used to contain information about the section it sits within. It might contain links to other documents or copyright information, for example. Like the <header>, it can be used multiple times within a page if needed. For example, it could be used for the footer of a blog but also a footer within a blog post <article>.

However, the specification notes that contact information for the author of a blog post should instead be wrapped by an <address> element.

The W3C specification for the <footer> element can be found here: http://www.w3.org/TR/html5/sections.html#the-footer-element.

The HTML5 outline algorithm

Ordinarily, for an HTML document, headings would begin with an h1 for the main page title and then progress to using lower hierarchy title tags as needed for subheadings and the like.

However, HTML5 introduced the ability for each sectioning container to have its own self-contained outline. That means it is not necessary to think about which level of heading tag you're at in terms of the entire document. You could just concentrate on the sectioning container you are currently working in.

To illustrate why this might be preferable, within a blog, post titles could be set to use <h1> tags, while the title of the blog itself could also have an <h1> tag. For example, consider the following structure:

<h1>Ben's site</h1>
<section>
  <h1>Ben's blog</h1>
  <p>All about what I do</p>
</section>
<article>
  <header>
    <h1>A post about something</h1>
    <p>Trust me this is a great read</p>
    <p>No, not really</p>
    <p>See. Told you.</p>
  </header>
</article>

Despite having multiple <h1> headings, the outline still appears as follows:

  1. Ben's site
  2. Ben's blog
  3. A post about something

As such, theoretically you shouldn't need to keep track of the heading tag you need to use in terms of the whole document. It should be possible to use whatever the appropriate level of heading tag is needed within each piece of sectioned content and the HTML5 outline algorithm will order it accordingly.

You can test the outline of your documents using HTML5 outliners at one of the following URLs:

However, the reality is that search engines and the like make no use of the HTML5 outliner at present. Therefore, from a pragmatic standpoint, it probably makes more sense to continue thinking about headings in terms of the whole document. That will make your documents easier to read for search engines and also aid assistive technology to infer the correct meaning.

A note on h1-h6 elements

Something I wasn't aware of initially is that using h1-h6 tags to mark up headings and subheadings is discouraged. I'm talking about this kind of thing:

<h1>Scones:</h1>
<h2>The most resplendent of snacks</h2>

Here's a quote from the HTML5 specification:

h1–h6 elements must not be used to mark up subheadings, subtitles, alternative titles and taglines unless intended to be the heading for a new section or subsection.

That's us told!

So, how should we author such content? The specification actually has a whole section, http://www.w3.org/TR/html5/common-idioms.html#common-idioms, dedicated to this. Personally, I preferred the old <hgroup> element, but sadly that has been deprecated (more info in the Obsolete HTML features section). So, to follow the advice of the specification, our prior example could be rewritten as:

<h1>Scones:</h1>
<p>The most resplendent of snacks</p>

Right, we've now covered the lion's share of the HTML sectioning elements. Let's now consider grouping elements.

The div element

The most ubiquitous grouping element is the <div>. The <div> is so widely used because it is opinion-less. It conveys nothing. The only implied meaning of a div is that it groups something. Despite that, you will often see a div wrapping nothing but a string of text.

You should only opt for a div as a last resort. It is the element to use when you can think of nothing better.

We have more elements in HTML than ever before, so as we continue, hopefully we will get acquainted with plenty of other elements that will be more suitable for the jobs you currently use a div for.

The p element

The <p> element is used to markup a paragraph. However, don't think that means it can only be used on text 3-4 lines long. On the contrary, use it to mark up any text that cannot be better marked up with one of the other elements. For non-specific text, the p element is definitely a better choice than a div.

The blockquote element

A blockquote is used to markup text that is quoted from somewhere else. You don't have to wrap the text with any other element, but you can. For example, knowing what we now do about the p tag, we can use that inside a blockquote too if we wish. Here is a simple example using blockquote. First, there's an introductory section of text in a p tag, and then a blockquote:

<p>I did like Ben's book, but he kept going on about scones. For example:</p>
<blockquote>
All this writing about scones in our sample page and there's no image of the beauties! I'm going to add in an image of a scone near the top of the page; a sort of 'hero' image to entice users to read the page.
</blockquote>

There's some good examples of how and when to use blockquotes over on the HTML specification too: https://html.spec.whatwg.org/multipage/grouping-content.html#the-blockquote-element.

The <figure> and <figcaption> elements

The HTML specification relates that the <figure> element:

...can thus be used to annotate illustrations, diagrams, photos, code listings, etc.

So we use it as an element to call out visuals of any sort, and the accompanying <figcaption> provides the means to add some text supporting the visuals. Now, it is worth pointing out here that while we should always provide text in the alt attribute of an <img> tag to support assistive technology or to mitigate problems if an image fails to load, it isn't a requirement to provide a figcaption with a figure. The figcaption is added if you want to add a visual description alongside the visuals. Here's how we could use it to revise a portion of markup from the first chapter:

<figure class="MoneyShot">
  <img
    class="MoneyShotImg"
    src="img/scones.jpg"
    alt="Incredible scones baked to perfection and ready to eat"
  />
  <figcaption class="ImageCaption">
    This image isn't of scones I have made, instead it's a stock photo from Wikipedia
  </figcaption>
</figure>

You can see that the <figure> element is used to wrap this little self-contained block. Inside, the <figcaption> is used to provide a caption for the parent <figure> element.

It's perfect when images or code need a little caption alongside them (that wouldn't be suitable in the main text of the content).

The specification for the figure element can be found here: http://www.w3.org/TR/html5/grouping-content.html#the-figure-element. The specification for the figcaption is here: http://www.w3.org/TR/html5/grouping-content.html#the-figcaption-element.

<details> and <summary> elements

How many times have you wanted to create a simple open and close widget on your page? A piece of summary text that when clicked, opens a panel with additional information? Modern HTML facilitates this pattern with the details and summary elements. Consider this markup (you can open example3.html from this chapter's code to play with it for yourself):

<details>
  <summary>I ate 15 scones in one day</summary>
  <p>
    Of course I didn't. It would probably kill me if I did. What a way to go.
    Mmmmmm, scones!
  </p>
</details>

Opening this in Chrome, with no added styling, shows only the summary text by default:

Figure 2.1: <details> and <summary> attempt to solve a common problem but their implementation is limited

Clicking anywhere on the summary text opens the panel. Clicking it again toggles it shut. If you want the panel open by default you can add the open attribute to the details element:

<details open>
  <summary>I ate 15 scones in one day</summary>
  <p>
    Of course I didn't. It would probably kill me if I did. What a way to go.
    Mmmmmm, scones!
  </p>
</details>
A screenshot of a social media post

Description automatically generated

Figure 2.2: By adding the open attribute, the content is shown by default

Supporting browsers typically add some default styling to indicate the panel can be opened. Here in Chrome (and also Safari) that's a dark disclosure triangle. Different browsers have their own implementations of how we can deal with any marker for the details. As this is typically not a selector that has been defined in any W3C specification, to disable it in this instance, you need to use a proprietary pseudo class (note the -webkit- prefix):

summary::-webkit-details-marker {
  display: none;
}

You can of course use that same selector to style the marker differently.

Currently, there is no way of animating the open and close. Without JavaScript, there's also no way of toggling other details panels closed when another details/summary combination is open. I'm not sure either of these desires will (or should) ever be addressed. However, I've therefore found the usefulness of these elements pretty limited by themselves. Rather than an all-in-one open/close drawer solution, you should think of them as a way to more semantically facilitate what you would have done previously with a display: none; toggle on a standard div with the help of JavaScript.

The <address> element

The <address> element is to be used explicitly for marking up contact information for its nearest <article> or <body> ancestor. To confuse matters, keep in mind that it isn't to be used for postal addresses and the like (unless they are indeed the contact addresses for the content in question). Instead, postal addresses and other arbitrary contact information should be wrapped in good ol' <p> tags. I'm not a fan of the <address> element. In my experience it would be far more useful to mark up a physical address with this element. However, hopefully it makes more sense to you.

For more on what the W3C specification says about <address>: http://www.w3.org/TR/html5/sections.html#the-address-element.

We have now covered the majority of the sectioning elements of HTML. We will now move on to the text-level elements. These are the elements used to mark up individual words, letters, and symbols to provide explicit meaning as to the intent.

 

HTML text-level semantics

Before HTML5, text-level semantic elements were referred to in the specifications as inline elements. Therefore, if you are familiar with that description, be aware that we are talking about the same thing here.

The section of the HTML specification that details text-level semantics can be found here: http://www.w3.org/TR/html5/text-level-semantics.html#text-level-semantics.

Let's take a look at the most common and useful text-level elements.

The <span> element

The span element is the text-level equivalent of a div. It is unopinionated and is the perfect element to reach for when you merely want to wrap text in an element for styling purposes.

The <b> element

Historically, visuals were defined in the markup and the <b> element meant "make this bold" (http://www.w3.org/TR/html4/present/graphics.html#edef-B). However, the specification now describes the <b> element like this:

The b element represents a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance and with no implication of an alternate voice or mood, such as key words in a document abstract, product names in a review, actionable words in interactive text-driven software, or an article lede.

Although no specific meaning is now attached to it, as it's text level, it's not intended to be used to surround large groups of markup. Use a div for that.

You should also be aware that because it was historically used to bold text, you'll typically have to reset the font-weight in CSS if you want content within a <b> tag to not appear bold.

For example:

b {
    font-weight: normal;
}

The <strong> element

If you do want to emphasize something for strength, urgency, or importance, <strong> is the element for you. Here is how the specification defines these use cases:

Importance: The strong element can be used in a heading, caption, or paragraph to distinguish the part that really matters from other parts that might be more detailed, more jovial, or merely boilerplate.

Seriousness: The strong element can be used to mark up a warning or caution notice.

Urgency: The strong element can be used to denote contents that the user needs to see sooner than other parts of the document."

You can read the full specification for <strong> here:

https://www.w3.org/TR/html52/textlevel-semantics.html#the-strong-element

The <em> element

I'll admit, in the past, I've often used <em> merely as a styling hook to provide italic text when I wanted it. I need to mend my ways as the HTML specification tells us:

The em element represents stress emphasis of its contents.

Therefore, unless you actually want the enclosed contents to be emphasized, consider using a <b> tag or, where relevant, an <i> or span tag instead.

The <i> element

The HTML5 specification describes the <i> as:

A span of text in an alternate voice or mood, or otherwise offset from the normal prose in a manner indicating a different quality of text.

Suffice it to say, it's not to be used to merely italicize something. For example, we could use it to mark up the odd name in this line of text:

<p>However, discussion on the hgroup element is now frustraneous as it's now gone the way of the <i>Raphus cucullatus</i>.</p>

Or, perhaps if you were marking up a button in a food ordering web application, you might do this:

<button type="button">
    French Fries <i>No Salt Added</i>
</button>

There are plenty of other text-level semantic tags in HTML; for the full rundown, take a look at the relevant section of the specification at the following URL: http://www.w3.org/TR/html5/text-level-semantics.html#text-level-semantics.

 

Obsolete HTML features

If you have been writing HTML for a few years, you might be surprised to learn there are parts of HTML that are now considered obsolete. It's important to be aware that there are two camps of obsolete features in HTML: conforming and non-conforming. Conforming features will still work but will generate warnings in validators. Realistically, avoid them if you can but they aren't going to make the sky fall down if you do use them. Non-conforming features may still render in certain browsers but they may not. It's certainly not guaranteed.

In terms of obsolete and non-conforming features, there is quite a raft. I'll confess that there are many I have never used, and some I've never even seen! It's possible you may experience a similar reaction. However, if you're curious, you can find the full list of obsolete and non-conforming features at http://www.w3.org/TR/html5/obsolete.html. Notable obsolete and non-conforming features that you may occasionally encounter are strike, center, font, acronym, frame, and frameset.

There are also features that were present in earlier drafts of HTML5 that have now been dropped. hgroup is one such example. The hgroup element was originally proposed to wrap groups of headings: an h1 for a title and an h2 for a subtitle might have been wrapped in an hgroup element. However, discussion on the hgroup element is now frustraneous as it's now gone the way of the Raphus cucullatus.

 

Putting HTML elements to use

It's time to practice using some of the elements we have just looked at. Let's revisit the example from Chapter 1. If we compare the following markup to the original markup in Chapter 1 (remember, you can download all the examples from http://rwd.education) you can see where the new elements we've looked at have been employed:

<article>
  <header class="Header">
    <a href="/" class="LogoWrapper"
      ><img src="img/SOC-Logo.png" alt="Scone O'Clock logo"
    /></a>
    <h1 class="Strap">Scones: the most resplendent of snacks</h1>
  </header>
  <section class="IntroWrapper">
    <p class="IntroText">
      Occasionally maligned and misunderstood; the scone is a quintessentially British classic.
    </p>
    <figure class="MoneyShot">
      <img class="MoneyShotImg" src="img/scones.jpg" alt="Incredible scones" />
      <figcaption class="ImageCaption">
        Incredible scones, picture from Wikipedia
      </figcaption>
    </figure>
  </section>
  <p>Recipe and serving suggestions follow.</p>
  <section class="Ingredients">
    <h3 class="SubHeader">Ingredients</h3>
  </section>
  <section class="HowToMake">
    <h3 class="SubHeader">Method</h3>
  </section>
  <footer>
    Made for the book,
    <a href="http://rwd.education"
      >'Responsive web design with HTML5 and CSS'</a
    >
    by
    <address><a href="http://benfrain">Ben Frain</a></address>
  </footer>
</article>

I've removed a good portion of the inner content so we can concentrate on the structure. Hopefully you will agree that it's easy to discern different sections of markup from one another. However, at this point I'd also like to offer some pragmatic advice; it isn't the end of the world if you don't always pick the correct element for every single given situation.

For example, whether or not I used a <section> or <div> in the earlier example is of little real consequence. If we use an <em> when we should actually be using an <i>, I certainly don't feel it's a crime against humanity; the folks at the W3C won't hunt you down and tar and feather you for making the wrong choice. Just apply a little common sense. That said, if you can use elements like the <header> and <footer> when relevant, there are inherent accessibility benefits in doing so. I certainly think you're better than using nothing but div elements in your markup!

 

WCAG accessibility conformance and WAI-ARIA for more accessible web applications

Even since writing the first edition of this book in 2011/2012, the W3C has made great strides in making it easier for authors to make the necessary adjustments to code to make web pages more accessible.

Web Content Accessibility Guidelines (WCAG)

The Web Content Accessibility Guidelines (WCAG) exists to provide:

a single shared standard for web content accessibility that meets the needs of individuals, organizations, and governments internationally

When it comes to more pedestrian web pages (as opposed to single-page web applications and the like) it makes sense to concentrate on the WCAG documentation. They offer a number of (mostly common sense) guidelines for how to ensure your web content is accessible. Each recommendation is rated by a conformance level: A, AA, or AAA. For more on these conformance levels, visit http://www.w3.org/TR/UNDERSTANDING-WCAG20/conformance.html#uc-levels-head.

You'll probably find that you are already adhering to many of the guidelines, like providing alternative text for images, for example. However, you can get a brief rundown of the guidelines at http://www.w3.org/WAI/WCAG20/glance/Overview.html and then build your own custom quick reference list of checks here: http://www.w3.org/WAI/WCAG20/quickref/.

I'd encourage everyone to spend an hour or two to look down the list. Many of the guidelines are simple to implement and offer real benefits to users.

WAI-ARIA

The aim of Web Accessibility Initiative – Accessible Rich Internet Applications (WAI-ARIA) is principally to solve the problem of making dynamic content on a web page accessible. It provides a means of describing roles, states, and properties for custom widgets (dynamic sections in web applications) so that they are recognizable and usable by assistive technology users. For example, if an on-screen widget displays a constantly updating stock price, how would a blind user accessing the page know that? WAI-ARIA attempts to solve this problem.

How to implement ARIA fully in something like a web application is outside the scope of this book. However, if that's the kind of project you are building, head over to http://www.w3.org/WAI/intro/aria for more information. Instead, let's just go over some of the most important headline points to consider about ARIA.

The first important point to note is that it used to be advisable to add landmark roles to headers and footers like this: <header role="banner"> A header with ARIA landmark banner role </header>. However, role="banner" is now considered surplus to requirements. Look at the specifications for any of the elements we have looked at and you will see a dedicated Allowed ARIA role attributes section. Here is the relevant quote from the <section> element as an example:

Allowed ARIA role attribute values: region role (default - do not set), alert, alertdialog, application, contentinfo, dialog, document, log, main, marquee, presentation, search or status.

The key part there is "role (default - do not set)." This means explicitly adding an ARIA role to the element is pointless as it is implied by the element itself. A note in the specification now makes this clear:

In the majority of cases setting an ARIA role and/or aria-* attribute that matches the default implicit ARIA semantics is unnecessary and not recommended as these properties are already set by the browser.

Therefore, the easiest thing you can do to aid assistive technologies is use the correct elements where possible. A header element is going to be far more useful than div class="Header". Similarly, if you have a button on your page, use the <button> element (rather than a span or another element styled to look like a button).

Taking ARIA further

If you want to explore a solid set of accessible design patterns, the W3C has a published set you can peruse here: https://www.w3.org/TR/wai-aria-practices-1.1/examples/#examples_by_props_label.

Test your designs for free with NonVisual Desktop Access (NVDA)

If you develop on the Windows platform and you'd like to test your ARIA enhanced designs on a screen reader, you can do so for free with NVDA. You can get it at the following URL: http://www.nvda-project.org/.

Google now also ships the free Accessibility Developer Tools for the Chrome browser (available cross-platform), which is well worth checking out.

There's also a growing number of tools that help quickly test your own designs against things like color blindness. For example, https://michelf.ca/projects/sim-daltonism/ is a macOS app that lets you switch color blindness types and see a preview in a floating palette.

Hopefully, this brief introduction to WAI-ARIA and WCAG has given you a little background information on supporting assistive technologies. Perhaps adding assistive technology support to your next HTML project will be easier than you think. As a final resource for all things accessibility, there are handy links and advice galore on The A11Y Project homepage at http://a11yproject.com/.

 

Embedding media in HTML5

For many, HTML5 first entered their vocabulary when Apple refused to add support for Flash technology in their iOS devices. Flash had gained market dominance (some would argue a market stranglehold) as the plugin of choice to serve video through a web browser. However, rather than using Adobe's proprietary technology, Apple decided to rely on HTML5 instead to handle rich media rendering. While HTML5 was making good headway in this area anyway, Apple's public support of HTML5 gave it a major leg up and helped its media tools gain greater traction in the wider community.

We've discussed already that people tend to just use the term HTML rather than HTML5 these days, but that label was important historically in relation to media. Before HTML5, adding video and audio into markup was a bit of a pain. These days it's easy.

Adding video and audio in HTML

Video and audio in HTML is easy. Here's a "simple as can be" example of how to link to a video file in your page:

<video src="myVideo.mp4"></video>

HTML allows a single <video></video> tag (or <audio></audio> for audio) to do all the heavy lifting. It's also possible to insert text between the opening and closing tag to inform users when there is a problem. There are also additional attributes you'd ordinarily want to add, such as the height and width. Let's add these:

<video src="myVideo.mp4" width="640" height="480">If you're reading this either the video didn't load or your browser is waaaayyyyyy old!</video>

Now, if we add the preceding code snippet into our page and look at it in some browsers, it will appear but there will be no controls for playback. To ensure we show the default playback controls we need to add the controls attribute. For the sake of illustration, we could also add the autoplay attribute. However, I'd recommend against that in real-world scenarios—everyone hates videos that auto-play! Here's an example with the controls and autoplay attributes added:

<video src="myVideo.mp4" width="640" height="480" controls autoplay>If you're reading this either the video didn't load or your browser is waaaayyyyyy old!</video>

The result of the preceding code snippet is shown in the following screenshot:

Figure 2.3: With minimal code we have inserted a video into our page

Further attributes include preload to control preloading of media, loop to repeat the video, and poster to define a poster frame for the video, the image that shows while a video loads. To use an attribute, simply add it to the tag. Here's an example including all these attributes:

<video src="myVideo.mp4" width="640" height="480" controls autoplay preload="auto" loop poster="myVideoPoster.png"> If you're reading this either the video didn't load or your browser is waaaayyyyyy old!</video>

Providing alternate media sources

The <source> tag enables us to provide alternate sources for media. For example, alongside providing an MP4 version of a video, if we wanted to provide support for a new format, we could easily do so. Furthermore, if the user didn't have any suitable playback technology in the browser, we could provide download links to the files themselves. Here's an example:

<video width="640" height="480" controls preload="auto" loop poster="myVideoPoster.png">
    <source src="myVideo.sp8" type="video/super8" />
    <source src="myVideo.mp4" type="video/mp4" />
    <p><b>Download Video:</b> MP4 Format: <a href="myVideo.mp4">"MP4"</a></p>
</video>

In that case, we first specified the source of a made-up video format called super8. The browser goes top to bottom deciding what to play, so if it doesn't support super8, it moves on to the next source, mp4 in this case. And on and on it goes, moving down to the download link if it can't reconcile any of the sources listed. The type attribute tells the browser the MIME type of the resource. If you fail to specify this, the browser will fetch the content and try to play it anyway. But if you know the MIME type, you should add it in the type attribute. The prior code example and the sample video file (which, incidentally, is me appearing in the UK soap Coronation Street back when I had hair and hopes of starring alongside DeNiro) in MP4 format are in the example2 section of the chapter's code.

Audio and video tags work almost identically

The <audio> tag works on the same principles as the video tag, with the same attributes (excluding width, height, and poster). The main difference between the two is the fact that <audio> has no playback area for visible content.

Responsive HTML5 video and iframes

The only problem with our lovely HTML video implementation is it's not responsive. That's right, an example in a book about responsive web design with HTML5 and CSS that doesn't respond. Thankfully, for HTML embedded video, the fix is easy. Simply remove any height and width attributes in the markup (for example, remove width="640" height="480") and add the following in the CSS:

video {
  max-width: 100%;
  height: auto;
}

However, while that works fine for files that we might be hosting locally, it doesn't solve the problem of videos embedded within an iframe (take a bow YouTube, Vimeo, et al.) The following code will add a film trailer for Midnight Run from YouTube:

<iframe width="960" height="720" src="https://www.youtube.com/embed/B1_N28DA3gY" frameborder="0" allowfullscreen></iframe>

However, if you add that to a page as is, even if adding that earlier CSS rule, if the viewport is less than 960px wide, things will start to get clipped.

The easiest way to solve this problem is with a little CSS trick pioneered by Gallic CSS maestro Thierry Koblentz here: http://alistapart.com/article/creating-intrinsic-ratios-for-video. Essentially, he is creating a box of the correct aspect ratio for the video it contains. I won't spoil the magician's own explanation, go take a read.

If you're feeling lazy, you don't even need to work out the aspect ratio and plug it in yourself; there's an online service that can do it for you. Just head to http://embedresponsively.com/ and paste your iframe URL in. It will spit you out a simple chunk of code you can paste into your page.

For example, our Midnight Run trailer results in this (note the padding-bottom value to define the aspect ratio):

<style>
  .embed-container {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    max-width: 100%;
    height: auto;
  }
  .embed-container iframe,
  .embed-container object,
  .embed-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>
<div class="embed-container">
  <iframe
    src="http://www.youtube.com/embed/B1_N28DA3gY"
    frameborder="0"
    allowfullscreen
  ></iframe>
</div>

That's all there is to it! Simply add it to your page and you're done: we now have a fully responsive YouTube video (note: kids, don't pay any attention to Mr. DeNiro; smoking is bad)!

 

Summary

We've covered a lot in this chapter: everything from the basics of creating a page that validates as HTML5, through to embedding rich media (video) into our markup and ensuring it behaves responsively. Although not specific to responsive designs, we've also covered how we can write semantically rich and meaningful code and considered how we might ensure pages are meaningful and usable for users that are relying on assistive technology.

An exercise

In this chapter we covered a raft of HTML elements. We didn't cover them all, but we certainly covered all the elements you are likely to need day to day. I think you're ready to try a little exercise to see how much you have understood. Here is a screenshot of the site design used to create the website for this book:

Figure 2.4: A design of the website made for this book

If you have a Mac and you'd rather look at the original Sketch file, it's included in the download code as RWD3e_design.sketch.

Take a look at the design to try and create an HTML page for it. Consider the head section and what you need in there. Think about the language the content is in and any meta tags you might need. Then think about the visuals themselves. What might be the best elements to use to create the navigation section? Or each of those little sections below the book image? And what about that DOWNLOAD CODE box; any ideas how you might mark that up?

You can see the choices I made by visiting the live site at https://rwd.education, but do yourself a favor and don't peek until you've tried it for yourself!

About the Author
  • Ben Frain

    Ben Frain has been a web designer/developer since 1996. He is currently employed as a UI-UX Technical Lead at bet365. Before the web, he worked as an underrated (and modest) TV actor and technology journalist, having graduated from Salford University with a degree in Media and Performance. He has written four equally underrated (his opinion) screenplays and still harbors the (fading) belief he might sell one. Outside of work, he enjoys simple pleasures: playing indoor football while his body and wife still allow it and wrestling with his two sons.

    Browse publications by this author
Latest Reviews (6 reviews total)
The book is great, it’s the publisher’s business practices that’s borderline unethical/ illegal. If you say in your book you give a discount on the Ebook, you should honour it.
I was not able to make the purchase. I wanted to give Packt my money, even monthly! I wanted the subscription. The website didn't allow me to.
This is my first book from Packt, I like the book, the material, and it's great content, one thing I don't like was the lack of images inside the book, when I read a book about Html & Css I need images for better understanding, examples link is not enough because people sometimes read from iPhones or iPads, on the bus or in the coffee shop.
Responsive Web Design with HTML5 and CSS - Third Edition
Unlock this book and the full library FREE for 7 days
Start now