Hello! HTML5 And CSS3 Hello A User Friendly Reference Guide R. Crowther (Manning, 2013) WW
User Manual:
Open the PDF directly: View PDF .Page Count: 561
A user-friendly reference guide
HTM L5
& CSS3
Rob Crowther
M AN N I N G
Hello! HTML5 & CSS3
Hello! HTML5 & CSS3
A user-friendly reference guide
Rob Crowther
MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in
quantity. For more information, please contact:
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 261
Shelter Island, NY 11964
Email: orders@manning.com
©2013 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without
prior written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
User Friendly artwork, characters, and strips used by permission from UserFriendly.Org.
All Rights Reserved.
Recognizing the importance of preserving what has been written, it is Manning’s policy to
have the books we publish printed on acid-free paper, and we exert our best efforts to that
end. Recognizing also our responsibility to conserve the resources of our planet, Manning
books are printed on paper that is at least 15 percent recycled and processed without
elemental chlorine.
Manning Publications Co.
20 Baldwin Road
PO Box 261
Shelter Island, NY 11964
Development editor:
Copyeditor:
Technical proofreader:
Typesetter:
Cover designer:
ISBN: 9781935182894
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 17 16 15 14 13 12
Cynthia Kane
Tiffany Taylor
Adam London
Marija Tudor
Marija Tudor
brief contents
PART 1 LEARNING HTML5 1
1
2
3
4
5
6
Introducing HTML5 markup 3
HTML5 forms 38
Dynamic graphics 73
Audio and video 119
Browser-based APIs 153
Network and location APIs 191
PART 2 LEARNING CSS3
7
8
9
10
11
231
New CSS language features 233
Layout with CSS3 271
Motion and color 313
Borders and backgrounds with CSS3
Text and fonts 392
v
351
contents
preface xv
acknowledgments xvii
about this book xix
PART 1 LEARNING HTML5 1
1 Introducing HTML5 markup
3
Why do we need new elements? 4
New elements for page structure 7
Sectioning content 7 ❍ Headings, headers, and the outlining
algorithm 9 ❍ Common page elements 15
The HTML DOCTYPE 17
New elements for content 18
Time 18 ❍ Images and diagrams with and
21 ❍ Emphasizing words and phrases
22
HTML5’s new global attributes 23
Accessibility with ARIA 24 ❍ Extending HTML with custom
attributes 26 ❍ Expressing more than just document
semantics with microdata 28
The HTML5 content model 29
Browser support 32
Supporting Internet Explorer 35 ❍ Enabling HTML5 support
in Internet Explorer with html5.js 36
Summary 36
vii
viii
contents
2 HTML5 forms
38
The limitations of HTML4 forms 39
Numbers, ranges, dates, and times 42
Validation 46
The required attribute 47 ❍ The min, max, and pattern
attributes 47 ❍ Taking advantage of validation with
CSS 49 ❍ Turning off validation 50
Email and URLs 51
Email addresses 51
❍
Web addresses
Elements for user feedback
The element 53
The element 56
Less-common form controls
Telephone numbers 57
59
❍
53
53
❍
The element 55
57
Color pickers
58
New attributes for the element 59
Placeholder text 59 ❍ Form autofocus 61 ❍ Protecting
private information with the autocomplete attribute 61
Extending forms with JavaScript 62
Customizing the validation messages 62 ❍ Triggering
validation with JavaScript 64 ❍ Responding to any
changes in value 64 ❍ Creating combo boxes with
65 ❍ Easy ways to work with form
values in JavaScript 67
Browser support and detecting HTML5 features 68
Browser inconsistencies 69 ❍ Detecting supported
features 69 ❍ The html5-now library 71
Summary 72
3 Dynamic graphics
73
Getting started with : shapes, images, and text 74
Drawing shapes
text 84
76
❍
Placing images
82
❍
Drawing
Advanced : gradients, shadows, and animation 87
Creating gradients 88 ❍ Drawing drop shadows 91
Transformations 92 ❍ Animation 94
contents
Getting started with SVG 96
Applying styles to SVG 98 ❍ Drawing common shapes 99
Images, text, and embedded content 101 ❍ Transforms,
gradients, patterns, and declarative animation 105
SVG vs. 112
Browser support 114
Supporting in older versions of IE with
explorercanvas 114 ❍ SVG in XML vs. SVG in HTML 115
Embedding SVG as an image 115 ❍ Referencing an SVG
image from CSS 116 ❍ Embedding SVG as an object 116
SVG support in older browsers with SVG Web and Raphaël 116
Summary 118
4 Audio and video
119
Audio and video on the modern web 119
The element 123
Common attributes: controls, autoplay, loop, and preload 124
Codecs and license issues 129 ❍ Using multiple sources 133
The element 134
element attributes 135 ❍ Containers, codecs,
and license issues 138 ❍ Easy encoding with Miro Video
Converter 139 ❍ Advanced encoding with FFmpeg 140
Using multiple sources 142
Controlling audio and video with JavaScript 144
Integrating media with other content 146
Browser support 150
Web server configuration for audio and video 151
Supporting legacy browsers with Flash video 152
Summary 152
5 Browser-based APIs
153
Rich-text editing with the contenteditable attribute 154
Basic text editing 155 ❍ The spellcheck attribute
Applying formatting to the editable text 160
Natural user interaction with drag-and-drop 164
Basic drag-and-drop
browsers 169
167
❍
Drag-and-drop in all
157
ix
x
contents
Managing the Back button with the history API 173
Updating page state 175 ❍ Using location.hash 176
Example: Implementing an undo feature 177
Getting semantic with the microdata API 179
Using a single microdata format 180
microdata formats 183
❍
Using multiple
Lag-free interfaces with web workers 185
Browser support 189
Summary 189
6 Network and location APIs
191
Finding yourself with the Geolocation API 192
Finding your location 193 ❍ Finding your location more
accurately 194 ❍ Finding your location continuously 195
Practical uses for geolocation 196
Communication in HTML5 200
Enabling more secure integration with cross-document
messaging 201 ❍ Real-time communication with the
WebSocket API 205
Offline web applications 208
Setting up a development environment 209
The application cache 211 ❍ Managing network
connectivity in offline apps 215
Storing data for offline use 222
Local storage 223
it all together 228
❍
Session storage 227
❍
Putting
Browser support 229
Summary 229
PART 2 LEARNING CSS3
231
7 New CSS language features
233
Choosing elements through their relationships 234
Selecting sets of elements with combinators
Selecting among a set of elements with
pseudo-classes 240
235
contents
Choosing elements by their attributes 251
Choosing what isn’t
255
❍
Pseudo-elements
257
Choosing elements based on user interaction 261
Styling form elements based on state 262
page based on the target of the URL 265
❍
Styling the
Browser support 267
Using jQuery to support older browsers
269
Summary 270
8 Layout with CSS3
271
Underused CSS2 layout features 272
Placing elements on a line with inline-block 272
element dimensions with display: table 275
❍
Grouping
CSS3 improvements to CSS2 approaches 279
Mixing different length units with calc
the box model 284
279
❍
Controlling
Using media queries for flexible layout 285
Resolution detection 287 ❍ Changing layout based on
orientation and aspect ratio 291 ❍ Additional
device-detection features 292
The future of CSS layout 293
Using flexible boxes for nested layout 294 ❍ Using the
CSS3 Grid Alignment module 298 ❍ Controlling content
flow with CSS3 Regions 303 ❍ Making complex shapes
with CSS3 Exclusions and Shapes 305
Browser support 308
inline-block in IE6 and IE7 309 ❍ calc in Chrome and
Firefox 310 ❍ box-sizing in Firefox and Safari 5 310
Flexboxes in Chrome, Firefox, IE, and Safari 310
Media queries and old browsers 311 ❍ Regions and
exclusions 311
Summary 311
9 Motion and color
313
Colors and opacity 314
Opacity
314
❍
RGBA 318
❍
HSL and HSLA
320
xi
xii
contents
CSS transforms 323
2D transforms 324
❍
3D transforms
328
CSS transitions 330
Transition timing functions 334 ❍ Transition
property 337 ❍ Transition delay 338 ❍ Triggering
transitions with JavaScript 339
CSS Animation 343
Browser support 346
Opacity in IE8 and earlier 346 ❍ Transforms, transitions,
and animations in current browsers 346 ❍ Using
modernizr.js and jQuery for animation in older
browsers 349
Summary 350
10 Borders and backgrounds with CSS3
351
Drop shadows with CSS3 352
Box shadows
352
❍
Text shadows
Easy rounded corners 358
New features for background images
356
361
Background size 361 ❍ Multiple backgrounds
Background origin and clipping 369
365
Selective background scaling with border images 371
Basic border-image 372 ❍ Stretching and repeating
border-image sections 374 ❍ Using border-image to
create common effects 377
Creating gradients with CSS 378
Browser support 384
Cross-browser drop shadows 385 ❍ Cross-browser
CSS3 gradients 386 ❍ Cross-browser backgrounds and
border-image 387 ❍ Supporting old versions of Internet
Explorer 388 ❍ CSS3 PIE for easy IE support 390
Summary 391
11 Text and fonts 392
Basic web fonts 393
Gaining control of fonts with the @font-face rule 394
Font formats: EOT, TTF/OTF, and WOFF 398
Browser support for downloadable fonts 399
contents
Making your life easier with font services 400
Downloadable kits: FontSquirrel 400 ❍ Free font services:
Google Web Fonts 403 ❍ Subscription font services:
Fontdeck 405
Advanced web typography 407
font-size-adjust 407
❍
Advanced font control
409
Text columns 416
Column count and width
Gaps and rules 419
416
❍
Column spans
Wrapping and overflow 420
Word wrap
420
❍
Text overflow
422
Browser support 423
Summary 423
Appendix A
Appendix B
Appendix C
Appendix D
Index 523
A history of web standards 425
HTML basics 441
CSS basics 467
JavaScript 491
418
xiii
xiv
contents
preface
I first saw the web in my final year of university in 1993-94. All the cool
kids (bear in mind, this was a Computer Science department) were playing with a strange bit of software called Mosaic on their Sun 4 workstations. I had some fun with it and created my first web page (a guide to
Edinburgh pubs), but it didn’t strike me as anything more than a curiosity and it certainly didn’t measure up to “proper” document preparation
formats like LaTeX. It’s not the first time I’ve been completely wrong
about technology—and it won’t be the last!
I went back to experimenting with websites in 1997, a full-on blinking,
scrolling plethora of tacky animated gifs which is thankfully long lost. As
I learned more about the web I stopped seeing it as a poor-quality typesetting system and started seeing it as a great equalizer. Not only was
visiting a web page something anyone could do, making a web page was also
something anyone could do. Since then I’ve been on a mission, not only to
learn as much as I can about making web pages, but to help others learn
how to make them, and this book is a natural extension of that mission.
HTML5 and CSS3 are fascinating to me not only because of their techni-
cal features, but because they represent growth in the web platform after
several years of stagnation. The more the web can do, the more content
can be shared across the world by ordinary people like you and me.
xv
xvi
preface
acknowledgments
I’d like to thank my Mum for inspiring my lifelong love of books, my Dad
for inspiring my lifelong love of computers, and my brother for underwriting my move to London and giving me a chance to get a full-time web
development job. Also sincere thanks to the rest of my family for being
there for me over the years.
A big thank you to Boyd Gilchrist who, while we were both at university,
patiently answered such questions as “What’s this web browser thing,
then?” and “HTML, what the fudge is that?” among many others I
couldn’t be bothered to research on my own in the pre-Google era. Also,
thanks to my other friends at university, especially Graham Barr who not
only put up with living with me for several years but also managed to
keep in touch long enough to read drafts of several chapters in this book.
I’d like to thank everyone at Net Resources, especially my tutor John
Ayscough; Richard O’Connor for giving me the subsequent placement
which was my first commercial web development experience; and Esther
Kuperij for talking him into it. My adventures in web standards have been
greatly aided by the vibrant London web developer community, particularly the London Web Standards and London Web Meetup groups.
Troy Mott at Manning is the person who originally got me involved with
this book project, though at times I’m not sure whether to blame him or
thank him for that! But Troy and all the other people I’ve worked with at
Manning have been massively supportive throughout the writing and
production processes. I’d especially like to thank Katharine Osborne,
Candace Gillhoolley, Cynthia Kane, Bert Bates, Katie Tennant, Tiffany
xvii
xviii
acknowledgments
Taylor, Martin Murtonen, Janet Vail, Mary Piergies, and of course
Marjan Bace, for making this book what it is.
Many people reviewed the manuscript at various stages of its development, and I would like to thank all the MEAP readers who provided
comments in the forum as well as the following peer reviewers for their
invaluable feedback: ‘Anil’ Radhakrishna, Braj Panda, Brian R. Bondy,
Curtis Miller, Dave Nicolette, Dave Pawson, David McWhirter, Diane
C. Leeper, Edward Welker, Eric Pascarello, Gary Rasmussen, Greg
Donald, Greg Vaughn, James Hatheway, Jason Jung, Jason Kaczor,
John Griffin, Keith Kim, Kieran Mathieson, Lester Lobo, Lisa Morgan,
Mike Greenhalgh, Nikolaos Kaintantzis, Rudy Pena, Sarah Forst, Stuart Caborn, Tijs Rademakers, and Yvonne Adams. Special thanks to
Adam London for his careful technical review of the final manuscript
and for testing the code.
Finally, I’d like to acknowledge J. D. “Illiad” Fraser of User Friendly for
letting Manning use the User Friendly cartoon characters in the Hello!
series and for allowing me to put my own words in the characters’
mouths.
about this book
You should read this book if you’re interested in learning about the new
features in HTML5 and CSS3 available to web developers and enjoy an
example-driven, visual approach to learning. Readers in any of the following categories should find this book useful:
❂
❂
❂
❂
❂
Experienced web developers
Novice web developers
App developers (iPhone, Android, Windows 8 Metro)
Interactive media designers
Web designers
Different readers will find different parts of the book interesting. Please
see the later section “Book structure and suggested reading order” for
further guidelines on how to navigate the book.
Extra content for beginners
This book focuses on the new features of HTML5 and CSS3; as such it
expects the reader to have a little experience with their predecessors. But
we will take things slowly, especially in the early chapters, and each feature
discussed will come with example code you can try yourself. If you know
what tags are and what a CSS rule looks like, then you should have few
problems. If you’re new to web development, then you’ll benefit from the
short introduction to HTML and CSS in appendixes B and C.
To use many of the new features in HTML5, it is helpful to have some
knowledge of JavaScript. If you are a complete beginner, then you will
xix
xx
about this book
still find this book useful as it mostly uses small examples which are
easy to experiment with. Appendix D is provided to get you started in
JavaScript.
Book structure and suggested reading order
This book is split into two sections: part 1 concentrates on HTML5 and
part 2 on CSS3. The HTML5 section has chapters on the new markup
features of HTML5, forms and form validation, HTML5’s new dynamic
graphics capabilities, using video and audio, new JavaScript APIs for
client-side development, and new APIs related to networking. As a
rough guideline, the early chapters require little-to-no knowledge of
JavaScript, with each successive chapter building your knowledge
base. The second section starts with a couple of chapters on the nuts
and bolts of CSS3 and selectors, followed by chapters on layout, motion
and color, borders and backgrounds, and fonts and text formatting.
Most of the chapters are self-contained,
although there are a few dependencies.
The following chapter diagrams show a
few suggested reading orders, based on your role and what you expect
to get out of the book. Each diagram consists of chapter numbers in
boxes as well as the recommended and optional steps, which are indicated by two types of arrows as shown in the key above.
If you are a ...
Read chapters in this order
WEB DEVELOPER
If you’re a web developer looking to get up to speed,
then you should have no problem reading the chapters in numerical order. The CSS used in chapters 2
through 6 should be easy for you to follow. If you’re
interested in the history of HTML and the standards
process, then you can read appendix A before you
dive in. It’s likely that appendixes B through D are
not going to tell you anything you don’t already know,
so there’s no need to bother with them.
start
here
1
2
3
A
4
5
9
10
8
11
7
6
about this book
If you are a ...
xxi
Read chapters in this order
NOVICE WEB DEVELOPER
If you’re a novice web developer, then a slightly different approach is recommended. Again, read
appendix A only if you’re interested in history, but do
read appendixes B, C, and D if you have little-to-no
experience with HTML, CSS, and JavaScript. Read
appendix C and chapter 7 right after chapter 1 to
build your familiarity with CSS so that the limited
amount of CSS used in chapters 2 through 6
doesn’t hold you back.
APP DEVELOPER
If your goal is to be an app developer, either targeting mobile devices or Windows 8 Metro style apps,
then the key chapters for you are 1 through 6 which
concentrate on the markup and programming
platform provided by HTML5. Include appendixes B
and D plus chapter 7 if you’re coming to HTML5 from
another platform. Chapter 8 discusses CSS layout,
which will be useful for apps. This diagram assumes
a graphic designer will handle the detailed design
work, so chapters 9 through 11 are not shown.
INTERACTIVE MEDIA DESIGNER
If you’re an interactive media designer who is a
heavy user of Flash for media, animation, or
interactive content, then you can safely skip chapters
2, 5, and 6. Chapter 3 deals with dynamic graphics
and 4 with audio and video, and chapters 9 and 10
deal with the more visual-impact aspects of CSS3.
Chapter 8 on layout will be of less interest to you,
but chapter 11 covers using custom fonts, so you
may want to read that section.
WEB DESIGNER
If you’re a pure web designer with no interest in
JavaScript, then you can read the book while
avoiding most of the code. Any snippets of
JavaScript you’ll come across in chapters 1 and 7
through 11 can be ignored unless you want to try
replicating CSS3 effects in JavaScript for
backwards compatibility.
start
here
1
7
A
B
C
d
2
8
6
5
4
3
9
10
11
start
here
1
A
4
d
B
8
7
start
here
B
11
start
here
A
B
6
5
3
4
C
1
A
3
2
C
d
10
9
7
1
7
8
C
9
11
10
xxii
about this book
Characters and conventions
This book uses many graphic elements and typographical conventions
to guide you and help you learn about HTML5 and CSS3. This section
summarizes what you can expect to see.
CHARACTERS
You’ll be helped along by the characters from the popular User Friendly
cartoons. In case you’re not familiar with this web comic, let me introduce each of the characters and explain their roles in this book.
A.J. is the Columbia Internet Web Developer. He loves com-
puter games, nifty art, and has a big-brother relationship with
the Dust Puppy. He’ll be your main guide through HTML5 and
CSS3, pointing out gotchas and giving you extra tips.
The Dust Puppy was born inside of a network server, a result
of the combination of dust, lint, and quantum events. He is
wide-eyed and innocent, with no real grasp of reality, but he’s
pretty cute and people love him. In this book, Dust Puppy’s
main role will be to help you move from one topic to the next,
summarizing what you’ve just learned and letting you know
what’s coming next.
Erwin is a highly advanced Artificial Intelligence (AI) that
resides somewhere on the network. He was created overnight
by the Dust Puppy, who was feeling kind of bored. Erwin will
help out whenever something needs looking up on the internet
or when you need to think like a computer.
Miranda is a trained Systems Technologist and an experienced
UNIX sysadmin. A.J. is her boyfriend and she’ll be helping him
out throughout the book.
about this book
xxiii
Greg is in charge of Technical Support at the company. He has
broad technical knowledge but no expertise in web development. A.J. is helping him learn about web development, and
he’ll ask questions when A.J. isn’t being clear.
Stef works as the Corporate Sales Manager. He can’t understand the way techies think, so he doesn’t get very far with
them. Although he admires the power of Microsoft’s marketing
muscle, he has a problem with Microsoft salesmen, probably
because they make much more money than he does.
Mike works as a System Administrator, and is responsible for
the smooth running of the network at the office. He will help us
out whenever we need to understand some details of server-side
setup.
Sid is a self-described “lichen of the tech-forest floor,” a longlived, deeply experienced and acerbic observer of the geek
gestalt. His history in computing involved vacuum tubes and,
later, punch cards. He carries with him an air of compassion
mixed with disdain for the younger geeks around him.
Pitr works with Mike as a System Administrator. For some reason he always wears dark glasses and has adopted a guttural
Eastern European accent. Pitr will take some time out from his
plans for world domination to keep A.J. in his place and to
demonstrate that attention to minor technical details that makes
geeks so well loved.
Crud Puppy is Dust Puppy’s evil twin and nemesis, born from
the crud in Stef’s keyboard. Whenever we need an antagonist,
Crud Puppy will be happy to oblige.
xxiv
about this book
CARTOONS & DIAGRAMS
There are many cartoons and diagrams in this book. The cartoons are
based on the actual User Friendly comic strips. Their intent is humorous
rather than educational as they poke fun at various aspects of web
development. A sample cartoon is shown below.
Diagrams are part of the text; they present information that’s easier to
understand in pictorial form. An example diagram follows.
DIAGRAMS WILL OFTEN BE DISCUSSED
BY CHARACTERS. LIKE THIS.
KEY FEATURES WILL BE
HIGHLIGHTED LIKE THIS.
CODE LISTINGS & SNIPPETS
Code listings and snippets and any occurrence of code in the text will
appear in the LucidaMonoEF font. Here is a typical code snippet:
HTML5 and CSS3
about this book
xxv
Longer listings will look like this:
LISTINGS WILL ALSO BE DISCUSSED BY
CHARACTERS. HERE IS A SIMPLE WEB PAGE.
Hello!
HTML5 and CSS3
MORE DETAILED LISTINGS HAVE
ANNOTATIONS JUST LIKE DIAGRAMS. THIS
ONE POINTS OUT THE EARLIER SNIPPET.
Code downloads
Up-to-date downloadable code samples and other news about the book
are available from the publisher’s website at www.manning.com/
HelloHTML5andCSS3.
Author Online
Purchase of Hello! HTML5 & CSS3 includes free access to a private web
forum run by Manning Publications where you can make comments
about the book, ask technical questions, and receive help from the
author and from other users. To access the forum and subscribe to it,
go to www.manning.com/HelloHTML5andCSS3. This page provides
information on how to get on the forum once you’re registered, what
kind of help is available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a
meaningful dialogue between individual readers and between readers
and the author can take place. It’s not a commitment to any specific
amount of participation on the part of the author, whose contribution to
the book’s forum remains voluntary (and unpaid). We suggest you try
asking the author some challenging questions, lest his interest stray!
The Author Online forum and the archives of previous discussions will
be accessible from the publisher’s website as long as the book is in print.
xxvi
about this book
About the author
Rob Crowther is a web developer and blogger based in London, UK.
Currently he works for a small software company building web applications for corporate clients such as BNP Paribas, BNY Mellon, Honeywell, and Young & Co.’s Brewery.
Part 1
Learning HTML5
his part of the book focuses on HTML5. Chapter 1 introduces you to
new and updated markup features in HTML5, chapter 2 discusses
forms and form validation, chapter 3 explores HTML5’s new dynamic
graphics capabilities, chapter 4 talks about how to use video and audio
on your web pages, and chapters 5 and 6 look at the new APIs you can
use for client-side development and networking.
2
CHAPTER
1
Introducing HTML5 markup
This chapter covers
• New semantic elements in HTML5
• Updated HTML4 elements
• New global attributes
• The HTML5 content model
• Getting new elements to work in old browsers
This chapter assumes you have some knowledge of previous versions of
HTML. If you’re new to HTML, check out appendix B—it should give
you enough information to understand this chapter.
3
4
CHAPTER 1
Introducing HTML5 markup
We’ll start with some background on how and why the particular set of
new elements in HTML5 was chosen. Then we’ll examine new elements
for the overall structure of web pages before moving on to elements,
both new and redefined, intended for particular bits of content. You’ll
then learn about the new attributes in HTML5. Next, we’ll spend a few
pages considering the more conceptual issue of the new approach to
element categorization in HTML5. Finally, you’ll go back to practicalities and learn how to make sure your new HTML5 content will work in
old browsers.
Why do we need new elements?
This section looks at some of the research that went into understanding
the document structures that web authors were trying to describe
semantically with HTML; this information was used to decide which
new elements should be added in HTML5. We’ll then look at each of
the new elements in turn.
What does semantic mean?
At heart, HTML is a way of describing hyperlinked documents: documents that
are linked together as part of a network of knowledge. The elements of HTML
are meant to mean something, and that meaning is what we refer to as the semantics. Because HTML describes documents, the semantics are along the lines
of “this content is a paragraph,” “this content is a level-one heading,” and “this
content is an unordered list.”
Being able to describe the structure of a document this way is valuable because
it lets you keep the details of how to best display content separate from the content itself. The result is that the same web page, if well structured, can easily be
read on a desktop computer, a mobile phone, and a text-to-speech converter.
Compare this to a document format like PDF, where the layout and content are
deeply interlinked because the fidelity of the eventual printed output is the primary goal. It’s usually awkward to read an A4 PDF on a mobile device because
there’s no option other than to view it at A4 size.
HTML4 has two built-in methods for extending the semantics of ele-
ments: the id and class attributes. The id attribute is a unique identifier, but, rather than a random string, the identifier can be a meaningful
word—in other words, it can have semantic value. The class isn’t
Why do we need new elements?
5
unique, but multiple classes can be applied to a single element like tagging in popular social network tools. Some examples are shown in the
following table.
Markup
Suggested meaning
A paragraph
A paragraph that represents a particular author
A paragraph that represents a biography
A paragraph that represents an author biography
No definitive standard sets down which values mean what,1 so one site
could use writer for the same thing another site uses author for, or two
sites could use author to mean something completely different. This
isn’t a huge issue, because HTML isn’t intended to describe real-world
things like authors, so the meaning behind those values is likely to be
site-specific anyway. But id and class attributes can also be used to
describe document features; for instance, a nav class would probably
indicate an element that contains navigation. If you were looking for
ideas for new elements to add to HTML to improve its ability to
describe documents, a survey of the sorts of values used in id and class
attributes would be a good place to start.
With this in mind, in 2005 several studies were done that attempted to
analyze how authors were using id and class values in markup on the
web. Two of these are of particular interest to us:
❂
❂
1
In November 2005, a study of 1,315 websites counted how often different values for the id attribute were used.
In December 2005, a study of slightly over a billion web pages analyzed, among other things, how often particular class names
appeared.
Although some have attempted it. See the discussion of microformats later in this chapter.
6
CHAPTER 1
Introducing HTML5 markup
The diagram that follows shows the top 20 results in each category
down each side and the corresponding new HTML5 elements along
with the IDs and classes that inspired them in the middle.
Many of the top IDs, like btamarker and nobulletcontent, are
automatically generated by software such as Microsoft
FrontPage and other office products. Their popularity is
therefore more an indication of the market penetration of
the products than author requirements or intentions.
New elements for page structure
7
In the next section, you’ll learn about some of the new elements that
have been added to HTML5 as a result of this research.
New elements for page structure
By page structure we mean the top-level items: the header, the footer, the
navigation, the main content, and so on. Let’s join A.J. and Greg, who
are discussing the research results from the previous section.
Sectioning content
It’s common for web pages to have many distinct sections. A blog
homepage usually has several blog posts, each a section in itself, and
each blog post may have a comments section or a related-posts section.
HTML4 offers only one type of element for this common need:
.
HTML5 adds two new elements:
and .
8
CHAPTER 1
Introducing HTML5 markup
element.
mean?
elements.
,
The
and elements are conceptually similar. Articles
and sections can be interchangeable—articles can exist happily within
sections, but articles can also be broken down into sections, and there’s
been a lot of discussion about whether HTML5 really needs both of
them. For now, though, we have both, and you’re probably asking
yourself how to decide which one to use. The key parts of the spec to
focus on when choosing one or the other are as follows:
❂
❂
An article is intended to be independently distributable or reusable.
A section is a thematic grouping of content.
New elements for page structure
9
Headings, headers, and the outlining algorithm
Heading elements provide an implicit structure for documents. A heading indicates the start of a new section and briefly describes the topic of
the text that follows. The level of a heading (levels 1 through 6 in
HTML) indicates an implicit hierarchy. This implicit structure is useful
for the automatic generation of a table of contents. Some websites,
such as Wikipedia, generate a table of contents for each page; screen
readers and other accessibility tools use the table of contents to allow
users to navigate the page more easily. HTML5 formalizes this implicit
structure with the outlining algorithm. In this section, you’ll learn
about this algorithm as well as how it interacts with the two new heading elements, and .
A element appears near the top of a document, a section, or an
article and usually contains the main heading and often some navigation and search tools. Here’s an example from the BBC website.
10
CHAPTER 1
Introducing HTML5 markup
Here’s how that might be marked up in HTML5:
You’ll learn more about
the element later
in this chapter. HTML5’s
new form elements will
be covered in depth in
chapter 2.
HTML5
(including next generation
additions still in
development)
Draft Standard —
12 May 2010
The element should be used
where you want a main heading
with one or more subheadings. For
an example, let’s look at the HTML5
spec:
New elements for page structure
11
The element can contain any content, but the element
can only contain other headers—that is,