news in HTML5 and CSS3

download news in HTML5 and CSS3

of 72

Transcript of news in HTML5 and CSS3

  • 8/14/2019 news in HTML5 and CSS3

    1/72

    HOME HTML CSS JAVASCRIPT JQUERY XML ASP.NET PHP SQL MORE... REFERENCES | EXAMPLES | FORUM | ABOUT

    SHARE THIS PAGE

    Like 70k

    CSS3 TutorialCSS3 HOMECSS3 Introduction

    CSS3 Borders

    CSS3 Bac kgrounds

    CSS3 Text Effects

    CSS3 Fonts

    CSS3 2D Transfor ms

    CSS3 3D Transforms

    CSS3 Transitions

    CS S3 Animation s

    CS S3 Multiple C olumns

    CS S3 User Inter face

    CSS3 Referen ces

    CSS3 ReferenceCS S3 Browser S upport

    CS S3 Selectors

    CS S3 Reference Aural

    CS S3 Web Safe Fonts

    CS S3 Units

    CS S3 Colors

    CSS3 Color Values

    CSS3 Color Names

    CSS3 Color HEX

    Previous Next Chapter

    CSS3 2D Transforms

    CSS3 TransformsWith CSS3 transform, we can move, sc ale, turn, spin, and stretch e lements.

    How Does it Work?

    A transform is an effect that lets an element ch ange shape , size and pos ition.You can transform your elements using 2D or 3 D transform ation.

    Browser SupportProperty Browser Suppor t

    transform

    Internet Explorer 10, Firefox, and Opera support the transform property.

    Chrome a nd Safari requires the p refix -webkit-.

    Note: Internet Explorer 9 req uires the p refix -ms-.

    2D TransformsIn this chapter you will learn about the 2d transform methods:

    translate()rotate()scale()skew()matrix()

    You will learn about 3D transforms in the next chapter.

    Example

    div{transform: rotate(30deg);-ms-transform: rotate(30deg); /* IE 9 */-webkit-transform: rotate(30deg); /* Safari and Chrome */}

    Try it yourself

    The translate() Method

    With the translate() method, the element moves from its current position, depending on the parameters given forthe left (X-axis) and the top (Y-axis) position:

    Example

    div{transform: translate(50px,100px);-ms-transform: translate(50px,100px); /* IE 9 */-webkit-transform: translate(50px,100px); /* Safari and Chrome */}

    Try it yourself

    WEB HOSTING

    Best Web Hosting

    eUK Web Hosting

    UK Rese ller Hos ting

    Cloud Hosting

    WEB BUILDING

    Download XML Editor

    FREE Website BUILDER

    FREE Website Cre ator

    Best Website Templates

    STATISTICS

    Browser Statistics

    OS Statistics

    Display Statistics

    Search w3schools.com:

    Nyelv kivlasztsa

    CSS3 2D Transforms 7/2/13

    http://www.w3schools.com/css3/css3_2dtransforms.asp 1 / 72

    http://www.w3schools.com/cssref/css_colorsfull.asphttp://www.w3schools.com/cssref/css_colors_legal.asphttp://www.w3schools.com/cssref/css_units.asphttp://www.w3schools.com/cssref/css3_browsersupport.asphttp://www.w3schools.com/cssref/css3_browsersupport.asphttp://www.w3schools.com/css3/css3_user_interface.asphttp://www.w3schools.com/css3/css3_animations.asphttp://www.w3schools.com/css3/css3_3dtransforms.asphttp://www.w3schools.com/css3/css3_fonts.asphttp://www.w3schools.com/css3/css3_backgrounds.asphttp://www.w3schools.com/css3/css3_intro.asphttp://www.w3schools.com/browsers/browsers_stats.asphttp://www.dreamtemplate.com/?ref=w3txtfreehttp://www.webhosting.uk.com/cloud-hosting.phphttp://void%280%29/http://www.w3schools.com/browsers/browsers_display.asphttp://www.w3schools.com/browsers/browsers_os.asphttp://www.w3schools.com/browsers/browsers_stats.asphttp://www.dreamtemplate.com/?ref=w3txtfreehttp://www.wix.com/eteamhtml/complete-solution?utm_campaign=ma_w3schools.com&experiment_id=ma_w3schools.comlink2_CShttp://www.wix.com/eteamhtml/400?utm_campaign=ma_w3schools.com&experiment_id=ma_w3schools.comlink1_400Html&embed_tags=camp&utm_camp=hOUdCO-AmAMQm__j8AMhttp://www.altova.com/ref/?s=w3s_text&q=xmlspyhttp://www.webhosting.uk.com/cloud-hosting.phphttp://www.heartinternet.co.uk/http://www.eukhost.com/http://www.lunarpages.com/id/w3schools/goto/w3schoolshttp://www.w3schools.com/css3/tryit.asp?filename=trycss3_transform_translatehttp://www.w3schools.com/css3/tryit.asp?filename=trycss3_transform1http://www.w3schools.com/css3/css3_3dtransforms.asphttp://www.w3schools.com/css3/css3_fonts.asphttp://www.w3schools.com/cssref/css_colorsfull.asphttp://www.w3schools.com/cssref/css_colornames.asphttp://www.w3schools.com/cssref/css_colors_legal.asphttp://www.w3schools.com/cssref/css_colors.asphttp://www.w3schools.com/cssref/css_units.asphttp://www.w3schools.com/cssref/css_websafe_fonts.asphttp://www.w3schools.com/cssref/css_ref_aural.asphttp://www.w3schools.com/cssref/css_selectors.asphttp://www.w3schools.com/cssref/css3_browsersupport.asphttp://www.w3schools.com/cssref/default.asphttp://www.w3schools.com/css3/css3_user_interface.asphttp://www.w3schools.com/css3/css3_multiple_columns.asphttp://www.w3schools.com/css3/css3_animations.asphttp://www.w3schools.com/css3/css3_transitions.asphttp://www.w3schools.com/css3/css3_3dtransforms.asphttp://www.w3schools.com/css3/css3_2dtransforms.asphttp://www.w3schools.com/css3/css3_fonts.asphttp://www.w3schools.com/css3/css3_text_effects.asphttp://www.w3schools.com/css3/css3_backgrounds.asphttp://www.w3schools.com/css3/css3_borders.asphttp://www.w3schools.com/css3/css3_intro.asphttp://www.w3schools.com/css3/default.asphttp://www.stumbleupon.com/submit?url=http://www.w3schools.com/css3/css3_2dtransforms.asp%26title%3DCSS3%202D%20Transformshttp://digg.com/submit?url=http://www.w3schools.com/css3/css3_2dtransforms.asp&title=CSS3%202D%20Transformshttp://www.reddit.com/submit?url=http://www.w3schools.com/css3/css3_2dtransforms.asphttp://delicious.com/save?v=5&noui&jump=close&url=http://www.w3schools.com/css3/css3_2dtransforms.asp&title=CSS3%202D%20Transformsmailto:?&subject=CSS3%202D%20Transforms&body=Take%20a%20look%20at%20this%20page%20at%20W3Schools.com:%20http://www.w3schools.com/css3/css3_2dtransforms.asphttp://twitter.com/home?status=Currently%20reading%20http://www.w3schools.com/css3/css3_2dtransforms.asphttp://www.facebook.com/sharer.php?u=http://www.w3schools.com/css3/css3_2dtransforms.asphttp://www.w3schools.com/about/default.asphttp://www.w3schools.com/forum/default.asphttp://www.w3schools.com/sitemap/default.asp#exampleshttp://www.w3schools.com/sitemap/default.asp#referenceshttp://www.w3schools.com/sitemap/default.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/php/default.asphttp://www.w3schools.com/aspnet/default.asphttp://www.w3schools.com/xml/default.asphttp://www.w3schools.com/jquery/default.asphttp://www.w3schools.com/js/default.asphttp://www.w3schools.com/css/default.asphttp://www.w3schools.com/html/default.asphttp://www.w3schools.com/default.asphttp://void%280%29/http://www.w3schools.com/
  • 8/14/2019 news in HTML5 and CSS3

    2/72

    The value translate(50px,100px) moves the element 50 pixels from the left, and 1 00 pixels from the top.

    The rotate() Method

    With the rotate () method, the element rotates c lockwise at a given degree. Negative values are a llowed and

    rotates the e lement counter-clockwise.

    Example

    div{transform: rotate(30deg);-ms-transform: rotate(30deg); /* IE 9 */-webkit-transform: rotate(30deg); /* Safari and Chrome */}

    Try it yourself

    The value rotate(30deg) rotates the element clockwise 30 degree s.

    The scale() Method

    With the s cale() method, the element increases or dec reases the size, dep ending on the pa rameters given for thewidth (X-axis) and the height (Y-axis):

    Example

    div{transform: scale(2,4);-ms-transform: scale(2,4); /* IE 9 */-webkit-transform: scale(2,4); /* Safari and Chrome */}

    Try it yourself

    The value s cale(2,4) transforms the width to be twice its original size , and the height 4 times its original size.

    The skew() Method

    With the skew() method, the element turns in a given angle, depending on the parameters given for the horizontal

    (X-axis) and the vertical (Y-axis) lines:

    Example

    div{transform: skew(30deg,20deg);-ms-transform: skew(30deg,20deg); /* IE 9 */-webkit-transform: skew(30deg,20deg); /* Safari and Chrome */}

    Try it yourself

    The value skew(30deg,20de g) turns the e lement 30 de grees around the X-axis, and 20 degree s aro und the Y-axis.

    The matrix() Method

    The matrix() method combines all of the 2D transform methods into one.

    CSS3 2D Transforms 7/2/13

    http://www.w3schools.com/css3/css3_2dtransforms.asp 2 / 72

    http://www.w3schools.com/css3/tryit.asp?filename=trycss3_transform_skewhttp://www.w3schools.com/css3/tryit.asp?filename=trycss3_transform_scalehttp://www.w3schools.com/css3/tryit.asp?filename=trycss3_transform_rotate
  • 8/14/2019 news in HTML5 and CSS3

    3/72

    REPORT ERROR | HOME | TOP | PRINT | FORUM | ABOUT | ADVERTISE WITH US

    Previous Next Chapter

    The matrix method take six parameters, containing mathematic functions, which allows you to: rotate, scale, move(translate), and skew e lements.

    Example

    How to rota te a div element 30 degrees , using the matrix method:

    div{transform:matrix(0.866,0.5,-0.5,0.866,0,0);-ms-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* IE 9 */-webkit-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* Safari and Chrome */}

    Try it yourself

    New Transform PropertiesThe following table lists all the transform properties:

    Property Descript ion CSS

    transform Applies a 2D or 3D transformation to an element 3

    transform-origin Allows you to change the position on transformed elements 3

    2D Transform MethodsFunct ion Descript ion

    matrix( n,n,n,n,n,n ) Defines a 2D transformation, using a matrix of six values

    translate( x,y ) Defines a 2D t rans la tion, moving the element a long the X- and the Y-axis

    translateX( n ) De fine s a 2D tra ns la tio n, mo ving the ele me nt a lo ng t he X- axis

    translateY( n ) De fine s a 2D tra ns la tio n, mo ving the ele me nt a lo ng t he Y- axis

    scale( x,y ) De fine s a 2D s ca le tra ns fo rma tio n, cha ng ing the ele me nts wid th a nd he ig ht

    scaleX( n ) De fines a 2D s cale tra ns formatio n, cha nging the ele me nt's width

    scaleY( n ) De fines a 2D s cale tra ns formatio n, cha nging the ele me nt's he ight

    rotate( angle ) De fine s a 2D ro ta tio n, the ang le is sp ec ifie d in the pa ra me te r

    skew( x-angle,y-angle ) Defines a 2D skew transformation along the X- and the Y-axis

    skewX( angle ) De fines a 2D s kew trans fo rma tio n a long the X-a xis

    skewY( angle ) De fines a 2D s kew trans fo rma tio n a long the Y-a xis

    Top 10 Tuto rials

    HTML Tutorial HTML5 Tutorial CSS Tutorial CSS3 Tutorial JavaScript Tutorial jQuery Tutorial SQL Tutorial PHP Tutorial ASP.NET Tutorial XML Tutorial

    To p 10 References

    HTML/HTML5 Reference CSS 1,2,3 Reference CSS 3 Browser Support JavaScript HTML DOM XML DOM PHP Reference jQuery Reference ASP.NET Referenc e HTML Colors

    Examples

    HTML Examples CSS Examples XML Examples JavaScript Examples HTML DOM Examples XML DOM Examples AJAX Examples ASP.NET Examples Razor Examples ASP Examples SVG Examples

    Quizzes

    HTML Quiz HTML5 Quiz XHTML Quiz CSS Quiz JavaScript Quiz jQuery Quiz XML Quiz ASP Quiz PHP Quiz SQL Quiz

    Color Picker

    Statistics

    Bro wser Statistics Browser OS Browser Display

    W3Scho ols is o ptimized for learning, testing, and training. Examples might be simplified to improve reading and basic unders tanding.Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.

    While using this site, you agree to have read and accepted our terms of use and privacy policy.Copyright 1999-2013 by Refsnes Data. All Rights Reserve d.

    CSS3 2D Transforms 7/2/13

    http://www.w3schools.com/css3/css3_2dtransforms.asp 3 / 72

    http://www.w3schools.com/about/about_copyright.asphttp://www.w3schools.com/about/about_privacy.asphttp://www.w3schools.com/about/about_copyright.asphttp://www.w3schools.com/about/about_advert.asphttp://www.w3schools.com/about/default.asphttp://www.w3schools.com/forum/default.asphttp://www.w3schools.com/css3/css3_2dtransforms.asp?output=printhttp://www.w3schools.com/default.asphttp://www.w3schools.com/css3/css3_2dtransforms.asphttp://www.w3schools.com/http://www.w3schools.com/browsers/browsers_display.asphttp://www.w3schools.com/browsers/browsers_os.asphttp://www.w3schools.com/browsers/browsers_stats.asphttp://www.w3schools.com/tags/ref_colorpicker.asphttp://www.w3schools.com/quiztest/quiztest.asp?qtest=SQLhttp://www.w3schools.com/quiztest/quiztest.asp?qtest=PHPhttp://www.w3schools.com/quiztest/quiztest.asp?qtest=ASPhttp://www.w3schools.com/quiztest/quiztest.asp?qtest=XMLhttp://www.w3schools.com/quiztest/quiztest.asp?qtest=jQueryhttp://www.w3schools.com/quiztest/quiztest.asp?qtest=JavaScripthttp://www.w3schools.com/quiztest/quiztest.asp?qtest=CSShttp://www.w3schools.com/quiztest/quiztest.asp?qtest=XHTMLhttp://www.w3schools.com/quiztest/quiztest.asp?qtest=HTML5http://www.w3schools.com/quiztest/quiztest.asp?qtest=HTMLhttp://www.w3schools.com/svg/svg_examples.asphttp://www.w3schools.com/asp/asp_examples.asphttp://www.w3schools.com/aspnet/webpages_examples.asphttp://www.w3schools.com/aspnet/aspnet_examples.asphttp://www.w3schools.com/ajax/ajax_examples.asphttp://www.w3schools.com/dom/dom_examples.asphttp://www.w3schools.com/htmldom/dom_examples.asphttp://www.w3schools.com/js/js_examples.asphttp://www.w3schools.com/xml/xml_examples.asphttp://www.w3schools.com/css/css_examples.asphttp://www.w3schools.com/html/html_examples.asphttp://www.w3schools.com/tags/ref_colornames.asphttp://www.w3schools.com/aspnet/webpages_ref_classes.asphttp://www.w3schools.com/jquery/jquery_ref_selectors.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/dom/dom_nodetype.asphttp://www.w3schools.com/jsref/default.asphttp://www.w3schools.com/jsref/default.asphttp://www.w3schools.com/cssref/css3_browsersupport.asphttp://www.w3schools.com/cssref/default.asphttp://www.w3schools.com/tags/default.asphttp://www.w3schools.com/xml/default.asphttp://www.w3schools.com/aspnet/default.asphttp://www.w3schools.com/php/default.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/jquery/default.asphttp://www.w3schools.com/js/default.asphttp://www.w3schools.com/css3/default.asphttp://www.w3schools.com/css/default.asphttp://www.w3schools.com/html/html5_intro.asphttp://www.w3schools.com/html/default.asphttp://www.w3schools.com/css3/css3_3dtransforms.asphttp://www.w3schools.com/css3/css3_fonts.asphttp://www.w3schools.com/cssref/css3_pr_transform-origin.asphttp://www.w3schools.com/cssref/css3_pr_transform.asphttp://www.w3schools.com/css3/tryit.asp?filename=trycss3_transform_matrix1
  • 8/14/2019 news in HTML5 and CSS3

    4/72

    T

    You are here: Home Dive Into HTML5

    WHAT DOES IT ALL MEAN?

    show table of contents

    DIVING IN

    his chapter will take an HTML page that has abso lutely nothing wrong with it, and improve it. Parts o f it willbecome shorter. Parts will become longer. All of it will become more semantic. Itll be awesome.

    Here is the page in question . Learn it. Live it. Love it. Open it in a new tab and dont come back until youve hit ViewSource at least once.

    THE DOCTYPE

    From the top:

    This is called the doctype. Theres a lo ng histo ry and a black art behind the doctype. While working o n InternetExplorer 5 for Mac, the developers at Microsoft found themselves with a surprising problem. The upcoming version of their browser had improved its standards support so much, older pages no longer rendered properly. Or rather, they renderedproperly (according to s pecifications ), but people expected them to render improperly . The pages themselves had beenauth ored based o n the qui rks of the dominant browsers of the day, primarily Netscape 4 and Internet Explorer 4. IE5/Macwas s o advanced, it actually broke the web.

    Micros o ft came up with a novel so lution. Before rendering a page, IE5/Mac loo ked at the doctype, which is typically thefirst line o f the HTML so urce (even before the element). Older pages (that relied o n the rendering quirks o f older

    brows ers) generally didnt have a do ctype at all. IE5/Mac rendered these pages like older bro wsers did. In o rder toactivate the new standards support, web page authors had to o pt in, by supplying the right doctype before the element.

    This idea spread like wildfire, and soo n all major browsers had two mo des: quirks m ode and standards m ode. Of course, this being the web, things quickly got o ut of hand. When Moz illa tried to ship versio n 1.1 o f their brows er, theydiscovered that there were pages being rendered in s tandards m ode that were actually relying o n o ne specific quirk.Mozilla had just fixed its rendering engine to eliminate this quirk, and thousands of pages broke all at once. Thus wascreated and I am not making this up almost standards mode .

    In his seminal work, Activating Browser Modes with Do ctype , Henri Sivonen summarizes the different modes:

    Quirks Mode

    In the Quirks mode, browsers violate contemporary Web format specifications in order to avoidbreaking pages authored according to practices that were prevalent in the late 1990s.

    Standards Mo deIn the Standards mode, browsers try to give conforming documents the specification-wise correcttreatment to the extent implemented in a particular brows er. HTML5 calls this mode the no quirksmode.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 4 / 72

    https://developer.mozilla.org/en/Gecko%27s_%22Almost_Standards%22_Modehttp://diveintohtml5.info/examples/blog-original.htmlhttp://hsivonen.iki.fi/doctype/https://developer.mozilla.org/en/Gecko%27s_%22Almost_Standards%22_Modehttp://diveintohtml5.info/examples/blog-original.htmlhttp://showtoc%28%29/http://diveintohtml5.info/table-of-contents.html#semanticshttp://diveintohtml5.info/index.html
  • 8/14/2019 news in HTML5 and CSS3

    5/72

    Almost Standards ModeFirefox, Safari, Chrome, Opera (since 7.5) and IE8 also have a mode known as Almost Standardsmode, that implements the vertical sizing of table cells traditionally and not rigorously according to theCSS2 specification. HTML5 calls this mode the limited quirks mode.

    (You should read the rest of Henris article, because Im simplifying immensely here. Even in IE5/Mac, there were a fewolder doctypes that didnt count as far as opting into standards support. Over time, the list of quirks grew, and so did thelist o f doctypes that triggered quirks mode. The last time I tried to count, there were 5 do ctypes that triggered almost

    standards mode, and 73 that triggered quirks mode. But I probably missed some, and Im not even going to talk aboutthe crazy things that Internet Explorer 8 does to switch between its four four! different rendering modes. Heres aflowchart . Kill it. Kill it with fire.)

    Now then. Where were we? Ah yes, the doctype:

    That happens to be one of the 15 doctypes that trigger standards mode in all modern browsers. There is nothing wrongwith it. If you like it, you can keep it. Or you can change it to the HTML5 doctype, which is shorter and sweeter and alsotriggers standards mo de in all m odern browsers.

    This is the HTML5 doctype:

    Thats it. Just 15 characters. Its so easy, you can type it by hand and not screw it up.

    THE ROOT ELEMENT

    An HTML page is a series o f nested elem ents . The entire structureof the page is like a tree. Some elements are siblings, like two

    branches that extend from the same tree trunk. Some elements can be children of other elements, like a smaller branchthat extends from a larger branch. (It works the other way too ; an element that contains o ther elements is called theparent node of its immediate child elements, and the ancestor of its grandchildren.) Elements that have no children arecalled leaf nodes. The outer-most element, which is the ancestor of all other elements on the page, is called the rootelement. The root element of an HTML page is always .

    In this example page , the root element looks like this:

    There is nothing wrong with this markup. Again, if you like it, you can keep it. It is valid HTML5. But parts of it are no longer necessary in HTML5, so you can save a few bytes by removing them.

    The first thing to discuss is the xmlns attribute. This is a vestige of XHTML 1.0 . It says that elements in this page are in the

    XHTML names pace, http://www.w3.org/1999/xhtml . But elements in HTML5 are always in this namespace , so you no

    longer need to declare it explicitly. Your HTML5 page will work exactly the same in all browsers, whether this attribute ispresent or not.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 5 / 72

    http://www.whatwg.org/specs/web-apps/current-work/multipage/infrastructure.html#xmlhttp://www.w3.org/TR/xhtml1/http://diveintohtml5.info/examples/blog-original.htmlhttp://hsivonen.iki.fi/doctype/ie8-mode.png
  • 8/14/2019 news in HTML5 and CSS3

    6/72

    Dropping the xmlns attribute leaves us with this ro ot elem ent:

    The two attributes here, lang and xml:lang , both define the language of this HTML page. ( en stands for English. No t

    writing in English? Find your language code .) Why two attributes for the same thing? Again, this is a vestige of XHTML.Only the lang attribute has any effect in HTML5. You can keep the xml:lang attribute if you like, but if you do, you need to

    ensure that it contains the same value as the lang attribute .

    To ease migration to and from XHTML, authors may specify an attribute in no namespace with no prefix andwith the literal localname "xml:lang" on HTML elements in HTML documents, but such attributes must onlybe specified if a lang attribute in no namespace is also specified, and both attributes must have the same

    value when com pared in an ASCII case-ins ensitive manner. The attribute in no names pace with no prefix andwith the literal localname "xml:lang" has no effect on language processing.

    Are you ready to dro p it? Its OK, jus t let it go . Go ing, go ing go ne! That leaves us with this root element:

    And thats all I have to say abo ut tha t.

    THE ELEMENT

    The first child of the roo t element is us ually the element. The element contains metadata information

    about the page, rather than the body of the page itself. (The body of the page is, unsurprisingly, contained in the element.) The element itself is rather boring, and it has nt changed in any interesting way in HTML5. The goo d s tuff

    is whats inside the element. And for that, we turn once again to our example page :

    My Weblog

    First up: the element.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 6 / 72

    http://diveintohtml5.info/examples/blog-original.htmlhttp://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-lang-and-xml:lang-attributeshttp://www.w3.org/International/questions/qa-choosing-language-tags
  • 8/14/2019 news in HTML5 and CSS3

    7/72

    CHARACTER ENCODING

    When you think of text, you probably think of characters and symbols I see on my computer screen. But computersdont deal in characters and symbols; they deal in bits and bytes. Every piece of text youve ever seen on a computer screen is actually stored in a particular character encoding . There are hundreds of different character encodings , someoptimized for particular languages like Russian or Chinese or English, and others that can be used for multiple languages.Roughly speaking, the character encoding provides a mapping between the stuff you see on your screen and the stuff your

    computer actually stores in memory and on disk.

    In reality, its mo re com plicated than that. The same character might appear in mo re than one encoding, but each encodingmight use a different sequence of bytes to actually store the character in memory or on disk. So, you can think of thecharacter encoding as a kind of decryption key for the text. Whenever someone gives you a sequence of bytes and claimsits text, you need to know what character encoding they used so you can decode the bytes into characters and displaythem (or process them, or whatever).

    So, how does your browser actually determine the character encoding of the stream of bytes that a web server sends? Imglad you asked. If youre familiar with HTTP headers, you m ay have seen a header like this:

    Content-Type: text/html; charset="utf-8"

    Briefly, this says that the web s erver thinks its s ending you an HTML do cument, and that it thinks the do cument uses the

    UTF-8 character encoding. Unfortunately, in the whole magnificent soup of the World Wide Web, few authors actually have

    control over their HTTP server. Think Blogger : the content is provided by individuals, but the servers are run by Go ogle. SoHTML 4 provided a way to s pecify the character encoding in the HTML docum ent itself. Youve probably seen this too :

    Briefly, this says that the web author thinks they have authored an HTML document using the UTF-8 character encoding.

    Both of these techniques still work in HTML5. The HTTP header is the preferred method, and it overrides the tag if

    present. But not everyone can s et HTTP headers, so the tag is still around. In fact, it got a little easier in HTML5.

    Now it loo ks like this:

    This works in all browsers. How did this shortened syntax come about? Here is the best explanation I could find :

    The rationale for the attribute combination is that UAs already implem ent it, becausepeople tend to leave things unquoted, like:

    There are even a few test cases if you dont believe that browsers already do this.

    ASK PROFESSOR MARKUP

    Q: I never use funny characters. Do I still need to declare my character encoding?

    A: Yes! You sho uld always specify a character encoding o n every HTML page you serve. Not specifying an encoding canlead to security vulnerabilities .

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 7 / 72

    http://openmya.hacker.jp/hasegawa/security/utf7cs.htmlhttp://simon.html5.org/test/html/parsing/encoding/http://lists.w3.org/Archives/Public/public-html/2007Jul/0550.htmlhttp://www.blogger.com/http://www.iana.org/assignments/character-sets
  • 8/14/2019 news in HTML5 and CSS3

    8/72

    To sum up: character encoding is complicated, and it has not been made any easier by decades of poorly written softwareused by copy-and-pasteeducated authors. You should always specify a character encoding o n every HTML document,or bad things will happen . You can do it with the HTTP Content-Type header, the declaration, o r the

    shorter declaration, but please do it. The web thanks you.

    FRIENDS & (LINK) RELATIONS

    Regular links ( ) simply point to another page. Link relations are a way to explain why youre pointing to another

    page. They finish the s entence Im po inting to this o ther page because...

    ...its a stylesheet containing CSS rules that your browser should apply to this document.

    ...its a feed that contains the sam e content as this page, but in a standard subscribable fo rmat.

    ...its a translation o f this page into ano ther language.

    ...its the s ame content as this page, but in PDF fo rmat.

    ...its the next chapter of an online book of which this page is also a part.

    And so on. HTML5 breaks link relatio ns into two categories :

    Two categories of links can be created using the link element. Links t o ext ernal resources are links toresources that are to be used to augment the current document, and hyperlink links are links to other docum ents. ...

    The exact behavior for links to external resources depends o n the exact relations hip, as defined for therelevant link type.

    Of the examples I just gave, only the first ( rel="stylesheet" ) is a link to an external resource. The rest are hyperlinks to

    other documents. You may wish to follow those links, or you may not, but theyre not required in order to view the current

    page.

    Most often, link relations are seen on elements within the of a page. Some link relations can also be used

    on elements, but this is uncom mo n even when allowed. HTML5 also allows s om e relations on elements, but

    this is even less common. (HTML 4 did not allow a rel attribute on elem ents.) See the full chart of link relations to

    check where you can use s pecific rel values.

    ASK PROFESSOR MARKUP

    Q: Can I make up my own link relations?

    A: There seem s to be an infini te s upply o f ideas for new link relations . In an attempt to prevent people from jus t m akingstuff up , the microformats community maintains a registry of proposed rel values and the HTML specification defines the

    process for getting them accepted .

    REL = STYLESHEET

    Lets look at the first link relation in our example page :

    This is the mo st frequently used link relation in the wo rld (literally). is for pointing to CSS

    rules that are stored in a separate file. One small optimization you can make in HTML5 is to drop the type attribute.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 8 / 72

    http://diveintohtml5.info/examples/blog-original.htmlhttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#other-link-typeshttp://microformats.org/wiki/existing-rel-values#HTML5_link_type_extensionshttp://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#linkTypeshttp://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#attr-link-relhttp://openmya.hacker.jp/hasegawa/security/utf7cs.html
  • 8/14/2019 news in HTML5 and CSS3

    9/72

    Theres only o ne s tylesheet language for the web, CSS, so thats the default value for the type attribute. This works in all

    browsers. (I suppose someone could invent a new stylesheet language someday, but if that happens, just add the typeattribute back.)

    REL = ALTERNATE

    Continuing with our example page :

    This link relation is also quite common. , com bined with either the RSS o r Atom media type in

    the type attribute, enables so mething called feed autodiscovery. It allows syndicated feed readers (like Google Reader )

    to discover that a site has a news feed of the latest articles. Some browsers also support feed autodiscovery bydisplaying a s pecial icon next to the URL. (Unlike with rel="stylesheet" , the type attribute matters here. Dont drop it!)

    The rel="alternate" link relation has always been a strange hybrid of use cases, even in HTML 4 . In HTML5, its

    definition has been clarified and extended to mo re accurately describe existing web co ntent. As yo u jus t saw, using

    rel="alternate" in co njunction with type=application/atom+xml indicates an Atom feed for the current page. But you

    can also use rel="alternate" in conjunction with other type attributes to indicate the sam e content in ano ther form at,

    like PDF.

    HTML5 also puts to rest a long-standing confusion about how to link to translations of documents. HTML 4 says to usethe lang attribute in conjunction with rel="alternate" to specify the language o f the linked do cument, but this is

    incorrect. The HTML 4 Errata document lists four outright errors in the HTML 4 specification. One of these outright errors ishow to specify the language of a document linked with rel="alternate" The correct way, described in the HTML 4 Errata

    and now in HTML5, is to use the hreflang attribute. Unfortunately, these errata were never re-integrated into the HTML 4

    spec, because no one in the W3C HTML Working Group was working on HTML anymore.

    OTHER LINK RELATIONS IN HTML5

    rel="author" is used to link to information about the author of the page. This can be a mailto: address, though it

    doesnt have to be. It could simply link to a contact form or about the author page.

    HTML 4 defined rel="start" , rel="prev" , and rel="next"to define relations between pages that are part of a s eries (likechapters of a book, or even posts on a blog). The only one that was ever used correctly was rel="next" . People used

    rel="previous" instead of rel="prev" ; they used rel="begin" and rel="first" instead of rel="start" ; they used

    rel="end" instead of rel="last" .

    Oh, and all by themselves they made up rel="up" to point to a parent page. The best way to think of rel="up" is

    to look at your breadcrumb navigation (or at least imagine it). Your home page is probably the first page in your breadcrumbs, and the current page is at the tail end. rel="up" points to the next-to-last page in the breadcrumbs.

    HTML5 includes rel="next" and rel="prev" , just like HTML 4, and supports rel="previous" for backward

    compatibility. The specification once had rel="first" , rel="last" , and rel="up" , too. However, based on the lack of

    interest from implementors and users the HTML Working Group decided to drop these values from the specification.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 9 / 72

    http://lists.w3.org/Archives/Public/public-html/2011Feb/att-0481/issue-118-decision.htmlhttp://www.w3.org/TR/html401/types.html#type-linkshttp://www.w3.org/MarkUp/html4-updates/erratahttp://www.w3.org/TR/html401/types.html#type-linkshttp://www.google.com/reader/http://diveintohtml5.info/examples/blog-original.html
  • 8/14/2019 news in HTML5 and CSS3

    10/72

    rel="icon" is the second m os t popular link relation , after rel="stylesheet" . It is usually found together with shortcut ,

    like so:

    All majo r browsers suppo rt this usage to as sociate a small ico n with the page. Us ually its dis played in the bro wserslocation bar next to the URL, or in the browser tab, or both.

    Also new in HTML5: the sizes attribute can be used in conjunction with the icon relationship to indicate the siz e o f the

    referenced icon .

    rel="license" was invented by the microformats community . It indicates that the referenced document provides thecopyright license terms under which the current document is pro vided.

    rel="nofollow" indicates that the link is not endorsed by the original author or publisher of the page, or that the link to thereferenced document was included primarily because o f a com mercial relationship between peo ple affiliated with the twopages. It was invented by Google and standardized within the microformats community . WordPress adds

    rel="nofollow" to links added by commenters. The thinking was that if nofollow links did not pass on PageRank,

    spammers would give up trying to post spam comments on weblogs. That didnt happen, but rel="nofollow" persists.

    rel="noreferrer" indicates that no referrer information is to be leaked when following the link. WebKit supportsrel="noreferrer" so it works on Google Chome and Safari (and hopefully on other WebKit-based browsers).[rel="noreferrer" test case ]

    rel="prefetch" indicates that preemptively fetching and caching thespecified resource is likely to be beneficial, as it is highly likely that

    the user will require this resource. Search engines sometimes add to the search results page if they feel that the top result is wildly mo re popular than any other. For example:

    using Firefox, search Go ogle for CNN , view the page source, and search for the keyword prefetch . Mozilla Firefox is theonly current browser that supports rel="prefetch" .

    rel="search" indicates that the referenced do cument provides an interface specifically for s earching the do cument and itsrelated resources. Specifically, if you want rel="search" to do anything useful, it should point to an OpenSearch

    document that describes how a browser could construct a URL to search the current site for a given keyword. OpenSearch(and rel="search" links that point to OpenSearch description documents) has been supported in Internet Explorer since

    version 7, Mozilla Firefox since version 2, and Google Chrome.

    rel="tag" indicates that the tag that the referenced document represents applies to the current document. Marking uptags (category keywords) with the rel attribute was invented by Technorati to help them categorize blog posts. Early

    blogs and tutorials thus referred to them as Technorati tags. (You read that right: a comm ercial company co nvinced theentire wo rld to add m etadata that made the com panys jo b easier. Nice work if you can get it!) The syntax was later standardized within the microformats community , where it was sim ply called rel="tag" . Most blogging systems that allow

    associating categories, keywords, or tags with individual posts will mark them up with rel="tag" links. Brows ers do no t

    do anything special with them; theyre really designed for search engines to use as a signal of what the page is about.

    NEW SEMANTIC ELEMENTS IN HTML5

    HTML5 is not just about making existing markup shorter (although it does a fair amount of that). It also defines new

    semantic elements.

    The section element represents a generic document o r application section. A section, in this co ntext, is a

    thematic grouping o f content, typically with a heading. Examples of s ections would be chapters, the tabbedpages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 10 / 72

    http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-section-elementhttp://microformats.org/wiki/rel-taghttp://www.powazek.com/2005/07/000532.htmlhttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#link-type-taghttp://www.opensearch.org/http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#link-type-searchhttp://www.google.com/search?q=cnnhttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#link-type-prefetchhttp://wearehugh.com/public/2009/04/rel-noreferrer.htmlhttp://webkit.org/blog/907/webkit-nightlies-support-html5-noreferrer-link-relation/http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#link-type-noreferrerhttp://www.wordpress.org/http://microformats.org/wiki/rel-nofollowhttp://googleblog.blogspot.com/2005/01/preventing-comment-spam.htmlhttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#link-type-nofollowhttp://microformats.org/wiki/rel-licensehttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#link-type-licensehttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#rel-iconhttp://code.google.com/webstats/2005-12/linkrels.htmlhttp://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#rel-icon
  • 8/14/2019 news in HTML5 and CSS3

    11/72

    into sections for an introduction, news items, contact information.

    The nav element represents a section of a page that links to other pages or to parts within the page: a

    section with navigation links. Not all groups of links on a page need to be in a nav element only

    sections that consist of major navigation blocks are appropriate for the nav element. In particular, it is

    comm on for footers to have a sho rt list of links to comm on pages of a s ite, such as the terms of service,the hom e page, and a co pyright page. The footer element alone is sufficient for such cases, without a navelement.

    The article element represents a component of a page that consists of a self-contained composition in a

    docum ent, page, application, o r site and that is intended to be independently distributable o r reusable, e.g.in syndication. This could be a forum post, a magazine or newspaper article, a Web log entry, a user-subm itted co mm ent, an interactive widget or gadget, or any o ther independent item o f content.

    The aside element represents a section o f a page that consis ts o f content that is tangentially related to the

    content around the aside element, and which could be cons idered separate from that content. Such

    sections are often represented as s idebars in printed typography. The element can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other

    content that is considered separate from the main content of the page.

    The hgroup element represents the heading of a section. The element is used to group a set of h1 h6elements when the heading has m ultiple levels, such as subheadings, alternative titles, o r taglines.

    The header element represents a group o f introductory o r navigational aids. A header element is intended

    to usually contain the sections heading (an h1 h6 element or an hgroup element), but this is no t required.

    The header element can also be used to wrap a sections table of contents, a search form, or any relevant

    logos.

    The footer element represents a footer for its nearest ancestor sectioning content or sectioning rootelement. A footer typically contains information about its section such as who wrote it, links to relateddocum ents, copyright data, and the like. Foo ters dont necessarily have to appear at the end o f a section,though they usually do . When the footer element co ntains entire sections, they represent appendices,

    indexes, long colophons, verbose license agreements, and other such content.

    The time element represents either a time on a 24 hour clock, or a precise date in the proleptic Gregorian

    calendar, optionally with a time and a time-zone offset.

    The mark element represents a run of text in one document marked or highlighted for reference purposes.

    I know yo ure anxious to s tart using these new elements, o therwise yo u wo uldnt be reading this chapter. But first we needto take a little detour.

    A LONG DIGRESSION INTO HOW BROWSERS HANDLE UNKNOWN ELEMENTS

    Every browser has a master list of HTML elements that it supports. For example, Mozilla Firefoxs list is stored innsElementTable.cpp . Elements not in this list are treated as unknown elements. There are two fundamental problemswith unknown elements:

    1. How should the element be styled? By default,

    has spacing on the top and bottom, is

    indented with a left margin, and is displayed in a larger font. But what default styles should be applied to

    unknown elements?2. What should t he e lement s DOM look like? Mozillas nsElementTable.cpp includes information about what

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 11 / 72

    http://mxr.mozilla.org/mozilla-central/source/parser/htmlparser/src/nsElementTable.cpphttp://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-mark-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-time-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-footer-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-header-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-hgroup-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-aside-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-article-elementhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-nav-element
  • 8/14/2019 news in HTML5 and CSS3

    12/72

    kinds o f other elements each element can contain. If you include m arkup like

    , the second paragraph

    element implicitly closes the first one, so the elements end up as siblings, not parent-and-child. But if you write

    , the span does not close the paragraph, because Firefox knows that

    is a block element that can

    contain the inline element . So, the ends up as a child of the

    in the DOM.

    Different brows ers ans wer these questions in different ways. (Shocking, I know.) Of the major bro wsers, Micros oft InternetExplorers answer to both questions is the most problematic, but every browser needs a little bit of help here.

    The first question should be relatively simple to answer: dont give any special styling to unknown elements. Just let theminherit whatever CSS properties are in effect wherever they appear on the page, and let the page author specify all stylingwith CSS. And that works, mo stly, but theres one little go tcha yo u need to be aware o f.

    PROFESSOR MARKUP SAYS

    All bro wsers render unkno wn elem ents inline, i.e. as if they had a display:inline CSS rule.

    There are s everal new elements defined in HTML5 which are block-level elements. That is, they can contain other block-level elements, and HTML5-compliant browsers will style them as display:block by default. If you want to use these

    elements in older browsers, you will need to define the display style manually:

    article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section { display:block;}

    (This code is lifted from Rich Clarks HTML5 Reset Stylesheet , which does many other things that are beyond the scope of

    this chapter.)

    But wait, it gets worse! Prior to version 9, Internet Explorer did not apply any styling on unknown elements. For example, if you had this markup:

    article { display: block; border: 1px solid red }...Welcome to Initech

    This is your first day.

    Internet Explorer (up to and including IE 8) will not treat the element as a block-level element, nor will it put a

    red bo rder around the article. All the style rules are s imply igno red. Internet Explorer 9 fixes this problem .

    The second problem is the DOM that browsers create when they encounter unknown elements. Again, the mostproblematic browser is older versions of Internet Explorer (before version 9, which fixes this problem too ). If IE 8 doesntexplicitly recognize the element name, it will insert the element into the DOM as an empty node with no children . All theelements that you wo uld expect to be direct children of the unknown elem ent will actually be inserted as s iblings ins tead.

    Here is some righteous ASCII art to illustrate the difference. This is the DOM that HTML5 dictates:

    article|

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 12 / 72

    http://msdn.microsoft.com/en-us/ie/hh410106#_HTML_Parsinghttp://msdn.microsoft.com/en-us/ie/hh410106#_HTML_Parsinghttp://html5doctor.com/html-5-reset-stylesheet/
  • 8/14/2019 news in HTML5 and CSS3

    13/72

    +--h1 (child of article)| || +--text node "Welcome to Initech"|+--p (child of article, sibling of h1) | +--text node "This is your " |

    +--span | | | +--text node "first day" | +--text node "."

    But this is the DOM that Internet Explorer actually creates:

    article (no children)h1 (sibling of article)|+--text node "Welcome to Initech"p (sibling of h1)|+--text node "This is your "|+--span| || +--text node "first day"|+--text node "."

    There is a wonderous workaround for this problem. If you create a dummy element with JavaScript before you

    use it in your page, Internet Explorer will magically recognize the element and let you style it with CSS. There is

    no need to ever insert the dummy element into the DOM. Simply creating the element once (per page) is enough to teachIE to style the element it doesnt recognize.

    article { display: block; border: 1px solid red }

    document.createElement("article");

    Welcome to Initech

    This is your first day.

    This works in all versions of Internet Explorer, all the way back to IE 6! We can extend this technique to create dummycopies of all the new HTML5 elements at once again, theyre never inserted into the DOM, so youll never see thesedummy elements and then just start using them without having to worry too much about non-HTML5-capable browsers.

    Remy Sharp has done just that, with his aptly named HTML5 enabling script . The script has gone through more than a

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 13 / 72

    http://remysharp.com/2009/01/07/html5-enabling-script/http://xopus.com/devblog/2008/style-unknown-elements.html
  • 8/14/2019 news in HTML5 and CSS3

    14/72

    dozen revisions since I started writing this book, but this is the basic idea:

    The bits are conditional comm ents . Internet Explorer interprets them like an ifstatement: if the current brows er is a version o f Internet Explorer less than versio n 9, then execute this block. Every other brows er will treat the entire block as an HTML comm ent. The net result is that Internet Explorer (up to and including version8) will execute this s cript, but other browsers will igno re the script altogether. This makes your page lo ad faster inbrowsers that dont need this hack.

    The JavaScript code itself is relatively straightforward. The variable e ends up as an array of strings like "abbr" ,

    "article" , "aside" , and so on. Then we loop through this array and create each of the named elements by calling

    document.createElement() . But since we ignore the return value, the elements are never inserted into the DOM. But this

    is eno ugh to get Internet Explorer to treat these elements the way we want them to be treated, once we actually use themlater in the page.

    That later bit is impo rtant. This script needs to be at the top o f your page, preferably in your element, not at the

    bottom. That way, Internet Explorer will execute the script before it parses your tags and attributes. If you put this s cript atthe bottom o f your page, it will be too late. Internet Explorer will have already misinterpreted your m arkup and cons tructedthe wrong DOM, and it wont go back and adjust it just because of this script.

    Remy Sharp has minified this script and hos ted it on Goo gle Project Hosting . (In case yo u were wondering, the scriptitself is open source and MIT-licensed, so you can use it in any project.) If you like, you can even hotlink the script bypointing directly to the ho sted versio n, like this:

    My Weblog

    Now were ready to start using the new semantic elements in HTML5.

    HEADERS

    Lets go back to our example page . Specifically, lets look at just the headers:

    My Weblog

    A lot of effort went into making this effortless.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 14 / 72

    http://diveintohtml5.info/examples/blog-original.htmlhttp://html5shiv.googlecode.com/svn/trunk/html5.jshttp://code.google.com/p/html5shiv/http://msdn.microsoft.com/en-us/library/ms537512
  • 8/14/2019 news in HTML5 and CSS3

    15/72

    Travel day

    I'm going to Prague!

    There is nothing wrong with this markup. If you like it, you can keep it. It is valid HTML5. But HTML5 provides so meadditional semantic elements for headers and sections.

    First off, lets get rid of that . This is a common pattern, but it doesnt mean anything. The div element

    has no defined semantics, and the id attribute has no defined semantics. (User agents are not allowed to infer any

    meaning from the value of the id attribute.) You could change this to and it would have the same

    sem antic value, i.e. , nothing.

    HTML5 defines a element for this purpos e. The HTML5 specification has real-world examples of using the

    element . Here is what it would look like on our example page :

    My Weblog

    A lot of effort went into making this effortless.

    Thats go od. It tells anyone who wants to kno w that this is a header. But what about that tagline? Another com mo n pattern,which up until now had no standard markup. Its a difficult thing to mark up. A tagline is like a subheading, but itsattached to the primary heading. That is, its a s ubheading that doesnt create its o wn section.

    Header elements like and give your page structure. Taken together, they create an outline that you can use to

    visualize (or navigate) your page. Screenreaders use document outlines to help blind users navigate through your page.There are online tools and browser extensions that can help you visualize your documents outline.

    In HTML 4, elements were the only way to create a document outline. The outline on the example page looks

    like this:

    My Weblog (h1) | +--Travel day (h2) | +--I'm going to Prague! (h2)

    Thats fine, but it means that theres no way to mark up the tagline A lot of effort went into making this effortless. If wetried to mark it up as an , it would add a phantom node to the document outline:

    My Weblog (h1)

    | +--A lot of effort went into making this effortless. (h2) | +--Travel day (h2) |

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 15 / 72

    http://chrispederick.com/work/web-developer/http://gsnedders.html5.org/outliner/http://diveintohtml5.info/examples/blog-original.htmlhttp://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-header-element
  • 8/14/2019 news in HTML5 and CSS3

    16/72

    +--I'm going to Prague! (h2)

    But thats no t the structure of the document. The tagline does no t represent a s ection; its jus t a subheading.

    Perhaps we could mark up the tagline as an and mark up each article title as an ? No, thats even worse:

    My Weblog (h1) |

    +--A lot of effort went into making this effortless. (h2) | +--Travel day (h3) | +--I'm going to Prague! (h3)

    Now we still have a phantom node in our document outline, but it has stolen the children that rightfully belong to the rootnode. And herein lies the problem: HTML 4 does not provide a way to mark up a subheading without adding it to thedocument outline. No matter how we try to shift things around, A lot of effort went into making this effortless is going toend up in that graph. And thats why we ended up with semantically meaningless markup like

    .

    HTML5 provides a solution for this: the element. The element acts as a wrapper for two or more

    related heading elements. What does related m ean? It means that, taken together, they only create a s ingle node in thedocument outline.

    Given this markup:

    My Weblog

    A lot of effort went into making this effortless.

    Travel day

    I'm going to Prague!

    This is the document outline that is created:

    My Weblog (h1 of its hgroup) |

    +--Travel day (h2) | +--I'm going to Prague! (h2)

    You can test your own pages in the HTML5 Outliner to ensure that youre using the heading elements properly.

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 16 / 72

    http://gsnedders.html5.org/outliner/
  • 8/14/2019 news in HTML5 and CSS3

    17/72

    ARTICLES

    Continuing with our example page , lets see what we can do about this markup:

    October 22, 2009

    Travel day

    Again, this is valid HTML5. But HTML5 pro vides a more specific elem ent for the common case o f m arking up an article on

    a page the aptly named element.

    October 22, 2009

    Travel day

    Ah, but i ts no t quite that s imple. There is one more change you should make. Ill sho w it to you first, then expla in it:

    October 22, 2009

    Travel day

    Did you catch that? I changed the element to an , and wrapped it inside a element. Youve already

    seen the element in action. Its purpose is to wrap all the elements that form the articles header (in this case,the articles publication date and title). Butbutbut shouldnt you only have one per document? Wont this screw

    up the document outline? No, but to understand why not, we need to back up a step.

    In HTML 4, the only way to create a document outline was with the elements. If you only wanted one root node

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 17 / 72

    http://diveintohtml5.info/examples/blog-original.html
  • 8/14/2019 news in HTML5 and CSS3

    18/72

    in your outline, you had to limit yourself to one in your markup. But the HTML5 specification defines an algorithm for

    generating a do cument outline that inco rporates the new s emantic elements in HTML5. The HTML5 algo rithm says that an

    element creates a new s ection, that is, a new no de in the do cument outline. And in HTML5, each section can

    have its own element.

    This is a drastic change from HTML 4, and heres why its a good thing. Many web pages are really generated bytemplates. A bit of content is taken from one so urce and inserted into the page up here; a bit of content is taken fromanother so urce and inserted into the page down there. Many tutorials are s tructured the same way. Heres s ome HTML

    markup. Just co py it and paste it into your page. Thats fine for sm all bits o f content, but what if the markup youre pas tingis an entire section? In that case, the tutorial will read something like this: Heres some HTML markup. Just copy it, pasteit into a text editor, and fix the heading tags s o they match the nesting level o f the corresponding heading tags in the pageyoure pasting it into.

    Let me put it ano ther way. HTML 4 has no generic heading element. It has six s trictly numbered heading elements,

    , which must be nes ted in exactly that o rder. That kind of sucks, especially if your page is as sem bled ins tead

    of authored. And this is the problem that HTML5 solves with the new sectioning elements and the new rules for theexisting heading elements. If youre using the new s ectioning elements, I can give you this markup:

    A syndicated post

    Lorem ipsum blah blah

    and you can copy it and paste it anywhere in your page without modification. The fact that it contains an element is

    not a problem, because the entire thing is contained within an . The element defines a self-

    contained node in the document outline, the element provides the title fo r that outline node, and all the o ther

    sectioning elem ents o n the page will remain at whatever nesting level they were at before.

    PROFESSOR MARKUP SAYS

    As with all things on the web, reali ty is a little more complica ted than Im letting on. The new explicitsectioning elements (like wrapped in ) may interact in unexpected ways with the old

    implicit sectioning elements ( by themselves). Your life will be simpler if you use one or the

    other, but not both. If you must use both on the same page, be sure to check the result in the HTML5Outliner and verify that your document outline makes sense.

    DATES AND TIMES

    This is exciting, right? I mean, its not skiing down Mount Everest naked while reciting the Star Spangled Banner backwards exciting, but its pretty exciting as far as s emantic markup go es. Lets co ntinue with our example page . Thenext line I want to highlight is this one:

    October 22, 2009

    Travel day

    Same o ld sto ry, right? A com mo n pattern designating the publication date of an article that has no sem antic markupto back it up, so authors resort to generic markup with custom class attributes. Again, this is valid HTML5. Youre not

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 18 / 72

    http://diveintohtml5.info/examples/blog-original.htmlhttp://gsnedders.html5.org/outliner/http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#headings-and-sections
  • 8/14/2019 news in HTML5 and CSS3

    19/72

  • 8/14/2019 news in HTML5 and CSS3

    20/72

    Travel day

    Lorem ipsum dolor sit amet

    NAVIGATION

    One of the most important parts of any web site is the navigation bar. CNN.com has tabs along the top of each

    page that link to the different news s ections Tech, Health, Spo rts, & c. Google search results pages have asimilar strip at the top of the page to try your search in different Google services Images, Video, Maps, & c. Andour example page has a navigation bar in the header that includes links to different sections of o ur hypothetical site ho me, blog, gallery, and about.

    This is how the navigation bar was originally marked up:

    home blog gallery about

    Again, this is valid HTML5. But whi le its marked up as a lis t o f fo ur items, there is no thing abo ut the lis t that tells you thatits part of the site navigation. Visually, you could guess that by the fact that its part of the page header, and by reading thetext of the links. But semantically, there is nothing to distinguish this lis t of links from any other.

    Who cares about the semantics of site navigation? For one, people with disabilities . Why is that? Consider this scenario:your motion is limited, and using a mouse is difficult or impossible. To compensate, you might use a browser add-on thatallows you to jump to (or jump past) major navigation links. Or consider this: if your sight is limited, you might use adedicated program called a screenreader that uses text-to-speech to speak and summarize web pages. Once you getpast the page title, the next impo rtant pieces o f information about a page are the majo r navigation links. If you want tonavigate quickly, youll tell your screenreader to jump to the navigation bar and start reading. If you want to browse quickly,you might tell your screenreader to jump over the navigation bar and start reading the main content. Either way, being ableto determine navigation links programmatically is important.

    So, while theres nothing wrong with using to mark up yo ur site navigation, theres no thing particularly

    right about it either. Its s uboptimal in ways that affect real people. HTML5 provides a sem antic way to mark up navigationsections: the element.

    home blog gallery about

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 20 / 72

    http://diveintoaccessibility.info/http://diveintohtml5.info/examples/blog-original.html
  • 8/14/2019 news in HTML5 and CSS3

    21/72

    ASK PROFESSOR MARKUP

    Q: Are skip links compatible with the element? Do I still need skip links in HTML5?

    A: Skip links allo w readers to skip over navigatio n sectio ns . They are helpful for d isabled users who use third- party

    software to read a web page aloud and navigate it without a mouse. ( Learn how and why to provide skip links .)

    Once screenreaders are updated to recognize the element, skip links will become obsolete, since the

    screenreader software will be able to automatically offer to skip over a navigation section marked up with the element. However, it will be a while before all the disabled users on the web upgrade to HTML5-savvy screenreader software, so you should continue to provide your own skip links to jump over sections.

    FOOTERS

    At lo ng las t, we have arrived at the end of our example page . The last thing I want to talk about is the last thing on thepage: the foo ter. The foo ter was o riginally marked up like this:

    20019 Mark Pilgrim

    This is valid HTML5. If you like it, you can keep it. But HTML5 provides a more specific element for this: the

    element.

    20019 Mark Pilgrim

    Whats appro priate to put in a element? Probably whatever youre putting in a now. OK,

    thats a circular answer. But really, thats it. The HTML5 specification says, A footer typically contains information about itssection s uch as who wrote it, links to related docum ents, copyright data, and the like. Thats whats in this example page:

    a short copyright statement and a link to an about-the-author page. Looking around at some popular sites, I see lots of footer potential.

    CNN has a foo ter that contains a co pyright statement, links to translations , and links to terms o f service, privacy,about us, contact us, and help pages. All totally appropriate m aterial.

    Google has a famously sparse home page, but at the bottom of it are links to Advertising Programs, BusinessSolutions, and About Google; a copyright statement; and a link to Googles privacy policy. All of that could bewrapped in a .

    My weblog has a footer with links to my other sites, plus a copyright statement. Definitely appropriate for a

    element. (Note that the links themselves should not be wrapped in a element, because they are

    not site navigation links; they are just a collection of links to my other projects on other sites.)

    Fat footers are all the rage these days. Take a look at the footer on the W3C site . It contains three columns, labeledNavigation, Contact W3C, and W3C Updates. The markup looks like this, more or less:

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 21 / 72

    http://www.w3.org/http://ui-patterns.com/pattern/FatFooterhttp://diveintomark.org/http://www.google.com/http://www.cnn.com/http://diveintohtml5.info/examples/blog-original.htmlhttp://www.webaim.org/techniques/skipnav/http://www.webaim.org/techniques/skipnav/
  • 8/14/2019 news in HTML5 and CSS3

    22/72

    Navigation Home Standards Participate Membership About W3C

    Contact W3C Contact Help and FAQ Donate Site Map

    W3C Updates Twitter Identi.ca

    Copyright 2009 W3C

    To convert this to semantic HTML5, I would make the following changes:

    Convert the o uter to a element.

    Convert the first two ins tances o f to elements, and the third instance to a

    element.

    Convert the headers to , since theyll no w each be inside a sectioning element. The element

    creates a section in the document outline, just like the element .

    The final markup might look something like this:

    Navigation

    Home Standards Participate Membership About W3C

    Contact W3C

    Contact Help and FAQ

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 22 / 72

  • 8/14/2019 news in HTML5 and CSS3

    23/72

    Donate Site Map

    W3C Updates

    Twitter

    Identi.ca

    Copyright 2009 W3C

    FURTHER READING

    Example pages used throughout this chapter:

    Original (HTML 4)Modified (HTML5)

    On character encoding:

    The Abso lute Minimum Every Software Developer Abso lutely, Pos itively Must Know About Unicode and Character Sets (No Excuses!) by Joel SpolskyOn the Goodness of Unicode , On Character Strings , and Characters vs. Bytes by Tim Bray

    On enabling new HTML5 in Internet Explorer:

    How to style unknown elements in IE by Sjoerd Visscher HTML5 shiv by John ResigHTML5 enabling script by Remy SharpThe Story of the HTML5 Shiv by Paul Irish

    On standards modes and doctype sniffing:

    Activating Browser Modes with Do ctype by Henri Sivonen. This is the only article you should read on the subject. Any article on do ctypes that doesnt reference Henris wo rk is guaranteed to be out o f date, incomplete, or wrong.

    HTML5-aware validator:

    html5.validator.nu

    This has been What Does It All Mean? The full table of contents has more if youd like to keep reading.

    DID YOU KNOW?

    In association with Google Press, OReilly is distributing this book in a variety of formats, including paper,ePub, Mobi, and DRM-free PDF. The paid edition is called HTML5: Up & Running, and it is available now.This chapter is included in the paid edition.

    If you liked this chapter and want to s how your appreciation, you can buy HTML5: Up & Running with this

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 23 / 72

    http://www.amazon.com/HTML5-Up-Running-Mark-Pilgrim/dp/0596806027?ie=UTF8&tag=diveintomark-20&creativeASIN=0596806027http://diveintohtml5.info/table-of-contents.htmlhttp://html5.validator.nu/http://hsivonen.iki.fi/doctype/http://paulirish.com/2011/the-history-of-the-html5-shiv/http://remysharp.com/2009/01/07/html5-enabling-script/http://ejohn.org/blog/html5-shiv/http://xopus.com/devblog/2008/style-unknown-elements.htmlhttp://www.tbray.org/ongoing/When/200x/2003/04/26/UTFhttp://www.tbray.org/ongoing/When/200x/2003/04/13/Stringshttp://www.tbray.org/ongoing/When/200x/2003/04/06/Unicodehttp://www.joelonsoftware.com/articles/Unicode.htmlhttp://diveintohtml5.info/examples/blog-html5.htmlhttp://diveintohtml5.info/examples/blog-original.html
  • 8/14/2019 news in HTML5 and CSS3

    24/72

    affiliate link o r buy an electronic edition directly from OReilly . Youll get a book, and Ill get a buck. I do no tcurrently accept direct donations.

    Copyright MMIXMMXI Mark Pilgrim

    Semantics - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/semantics.html#nav-element 24 / 72

    http://diveintohtml5.info/about.htmlhttp://oreilly.com/catalog/9780596806033
  • 8/14/2019 news in HTML5 and CSS3

    25/72

    Y

    You are here: Home Dive Into HTML5

    DETECTING HTML5 FEATURES

    show table of contents

    DIVING IN

    ou may well ask: How can I start using HTML5 if older browsers dont support it? But the question itself ismis leading. HTML5 is not o ne big thing; it is a co llection of individual features. So you cant detect HTML5support, because that doesnt make any sense. But you can detect support for individual features, likecanvas, video, or geolocation.

    DETECTION TECHNIQUES

    When your browser renders a web page, it constructs a Document Object Model (DOM), a collection of objects thatrepresent the HTML elements on the page. Every element every

    , every , every is represented in the

    DOM by a different object. (There are also global objects, like window and document , that arent tied to specific elements.)

    All DOM objects share a set o f co mmon pro perties, but some objectshave mo re than others. In browsers that suppo rt HTML5 features, certainobjects will have unique properties. A quick peek at the DOM will tell you which features are suppo rted.

    There are four basic techniques for detecting whether a browser supports a particular feature. From simplest to mostcomplex:

    1. Check if a certain property exists on a glo bal object (such as window o r navigator ).

    Example: testing for geolocation support

    2. Create an element, then check if a certain property exists o n that element.

    Example: testing for canvas support

    3. Create an element, check if a certain method exists o n that element, then call the method and check the value itreturns.

    Example : test ing which video formats are supported

    4. Create an element, set a property to a certain value, then check if the property has retained its value.

    Example: testing which types are supported

    MODERNIZR, AN HTML5 DETECTION LIBRARY

    Modernizr is an o pen so urce, MIT-licensed JavaScript library that detects suppo rt for many HTML5 & CSS3 features. Youshould always use the latest version. To use it, include the following element at the top of your page.

    Detecting HTML5 Features - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/detect.html#divingin 25 / 72

    http://diveintohtml5.info/index.htmlhttp://diveintohtml5.info/index.htmlhttp://diveintohtml5.info/table-of-contents.html#detecthttp://www.modernizr.com/http://showtoc%28%29/http://diveintohtml5.info/table-of-contents.html#detecthttp://diveintohtml5.info/index.html
  • 8/14/2019 news in HTML5 and CSS3

    26/72

    It goes to your

    Your browser supports the canvas API.

    Dive Into HTML5

    ...

    Modernizr runs automatically. There is no modernizr_init() function to call. When it runs, it creates a global object

    called Modernizr , that contains a set o f Boo lean properties fo r each feature it can detect. For example, if your browser

    supports the canvas API , the Modernizr.canvas property will be true . If your browser does not support the canvas API,

    the Modernizr.canvas property will be false .

    if (Modernizr.canvas) { // let's draw some shapes!} else { // no native canvas support available :(}

    CANVAS

    HTML5 defines the element as a resolution-dependent bitmap canvas that can be us ed for rendering graphs,game graphics, o r other visual images o n the fly. A canvas is a

    rectangle in your page where you can use JavaScript to drawanything you want. HTML5 defines a s et of functions (the canvas API) for drawing shapes , defining paths, creatinggradients, and applying transformations .

    Checking for the canvas API us es detection technique #2 . If your bro wser s upports the canvas API, the DOM object itcreates to represent a element will have a getContext() method . If your browser doesnt support the canvas

    API, the DOM object it creates for a element will only have the set of common properties, but not anything

    canvas-specific.

    function supports_canvas() { return !!document.createElement('canvas').getContext;}

    This function starts by creating a dummy element. But the element is never attached to your page, so no one

    will ever see it. Its just floating in memory, going nowhere and doing nothing, like a canoe on a lazy river.

    return !!document.createElement('canvas').getContext;

    As soon as you create the dum my element, you test for the presence of a getContext() method. This method

    will only exist if your browser supports the canvas API.

    return !!document.createElement('canvas').getContext;

    Finally, you us e the double-negative trick to force the result to a Bo o lean value ( true o r false ).

    Detecting HTML5 Features - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/detect.html#divingin 26 / 72

    http://diveintohtml5.info/canvas.html#shapeshttp://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.htmlhttp://diveintohtml5.info/canvas.html
  • 8/14/2019 news in HTML5 and CSS3

    27/72

    Your brows er supports the canvas text API.

    return !!document.createElement('canvas').getContext;

    This function will detect suppo rt for mo st o f the canvas API, including shapes , paths , gradients & patterns . It will not detectthe third-party explorercanvas library that implements the canvas API in Microsoft Internet Explorer.

    Instead of writing this function yo urself, you can use Modernizr to detect support for the canvas API.

    check for canvas support

    if (Modernizr.canvas) {

    // let's draw some shapes!} else { // no native canvas support available :(}

    There is a separate test for the canvas text API, which I will demonstrate next.

    CANVAS TEXT

    Even if your browser supports the canvas API , it might no t suppo rt the canvas text API.The canvas API grew over time, and the textfunctions were added late in the game.Some browsers shipped with canvas support before the text API was complete.

    Checking for the canvas text API uses detection technique #2 . If your bro wser s upports the canvas API, the DOM object itcreates to represent a element will have the getContext() method . If your browser doesnt support the canvas

    API, the DOM object it creates for a element will only have the set of common properties, but not anything

    canvas-specific.

    function supports_canvas_text() { if (!supports_canvas()) { return false; } var dummy_canvas = document.createElement('canvas'); var context = dummy_canvas.getContext('2d'); return typeof context.fillText == 'function';}

    The function starts by checking for canvas support , using the supports_canvas() function you just saw in the previous

    section. If your browser doesnt support the canvas API, it certainly wont support the canvas text API!

    if (!supports_canvas()) { return false; }

    Next, you create a dumm y element and get its drawing context. This is guaranteed to work, because the

    supports_canvas() function already checked that the getContext() method exists on all canvas objects.

    var dummy_canvas = document.createElement('canvas');

    var context = dummy_canvas.getContext('2d');

    Finally, you check whether the drawing context has a fillText() function. If it does, the canvas text API is available.

    Hooray!

    return typeof context.fillText == 'function';

    Detecting HTML5 Features - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/detect.html#divingin 27 / 72

    http://diveintohtml5.info/canvas.html#shapeshttp://diveintohtml5.info/canvas.html#iehttp://diveintohtml5.info/canvas.html#gradientshttp://diveintohtml5.info/canvas.html#pathshttp://diveintohtml5.info/canvas.html#shapes
  • 8/14/2019 news in HTML5 and CSS3

    28/72

    Your browser supports HTML5 video.

    Instead of writing this function yo urself, you can use Modernizr to detect support for the canvas text API.

    check for canvas text support

    if (Modernizr.canvastext) {

    // let's draw some text!} else { // no native canvas text support available :(

    }

    VIDEO

    HTML5 defines a new elem ent called for embedding video in your web pages. Embedding video used to be

    impossible without third-party plugins such as Apple QuickTime or Adobe Flash.

    The element is designed to be usable without any detection scripts.

    You can specify multiple video files, and browsers that suppo rt HTML5 videowill choose one based on what video formats they support. (See A gentleintroduction to video encoding part 1: container formats and part 2: lossyvideo codecs to learn about different video formats.)

    Browsers that dont support HTML5 video will ignore the element completely, but you can use this to your

    advantage and tell them to play video through a third-party plugin instead. Kroc Camen has designed a solution calledVideo for Everybody! that uses HTML5 video where available, but falls back to QuickTime or Flash in o lder browsers. Thissolution uses no JavaScript whatsoever, and it works in virtually every browser, including mobile browsers.

    If you want to do more with video than plop it on your page and play it, youll need to use JavaScript. Checking for videosupport uses detection technique #2 . If your browser supports HTML5 video, the DOM object it creates to represent a

    element will have a canPlayType() method. If your browser doesnt support HTML5 video, the DOM object itcreates for a element will have only the set of properties common to all elements. You can check for video

    support using this function:

    function supports_video() { return !!document.createElement('video').canPlayType;}

    Instead of writing this function yo urself, you can use Modernizr to detect suppo rt fo r HTML5 video.

    check for HTML5 video support

    if (Modernizr.video) {

    // let's play some video!} else { // no native video support available :( // maybe check for QuickTime or Flash instead}

    In the Video chapter , Ill explain another so lution that uses these detection techniques to convert elements to

    Flash-based video players, for the benefit of browsers that dont support HTML5 video.

    There is a s eparate test for detecting which video fo rmats yo ur brows er can play, which I will demo nstrate next.

    VIDEO FORMATS

    Detecting HTML5 Features - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/detect.html#divingin 28 / 72

    http://diveintohtml5.info/video.htmlhttp://camendesign.com/code/video_for_everybodyhttp://diveintomark.org/archives/2008/12/19/give-part-2-lossy-video-codecshttp://diveintomark.org/archives/2008/12/18/give-part-1-container-formats
  • 8/14/2019 news in HTML5 and CSS3

    29/72

    Your browser can play Ogg Theora video,but not H.264 video. Hey, you can play

    WebM video, too!

    Video formats are like written languages. An English newspaper may convey the same information as a Spanishnewspaper, but if you can only read English, only one of them will be useful to you! To play a video, your browser needsto understand the language in which the video was written.

    The language of a video is called a codec this is the algorithmused to encode the video into a stream of bits. There are dozens of codecs in use all over the world. Which one should you use? The

    unfortunate reality of HTML5 video is that browsers cant agree on asingle codec. However, they seem to have narrowed it down to two. Onecodec costs money (because of patent licensing), but it works in Safari

    and on the iPhone. (This one also works in Flash if you use a solution like Video for Everybody! ) The other codec is freeand works in open s ource brows ers like Chromium and Mozilla Firefox .

    Checking for video format support uses detection technique #3 . If your browser supports HTML5 video, the DOM object itcreates to represent a element will have a canPlayType() method. This method will tell you whether the browser

    supports a particular video format.

    This function checks for the patent-encumbered format supported by Macs and iPhones.

    function supports_h264_baseline_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');}

    The function starts by checking for HTML5 video support , using the supports_video() function you just saw in the

    previous section. If your browser doesnt support HTML5 video, it certainly wont support any video formats!

    if (!supports_video()) { return false; }

    Then the function creates a dummy element (but does nt attach it to the page, so it wont be visible) and calls the

    canPlayType() method. This method is guaranteed to be there, because the supports_video() function just checked for

    it.

    var v = document.createElement("video");

    A video format is really a combination of different things . In technica l terms, yo ure asking the bro wser whether i t can playH.264 Baseline video and AAC LC audio in an MPEG-4 container. (Ill explain what all that means in the Video chapter . Youmight also be interested in reading A gentle intro ductio n to video enco ding .)

    return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');

    The canPlayType() function does nt return true o r false . In recognition of how complex video formats are, the function

    returns a string:

    "probably" if the browser is fairly confident it can play this format

    "maybe" if the browser thinks it might be able to play this format

    "" (an empty string) if the browser is certain it cant play this format

    This second function checks for the open video format supported by Mozilla Firefox and other open source browsers. Theprocess is exactly the same; the only difference is the string you pass in to the canPlayType() function. In technical

    terms , youre asking the browser whether it can play Theora video and Vorbis audio in an Ogg container.

    Detecting HTML5 Features - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/detect.html#divingin 29 / 72

    http://diveintomark.org/tag/givehttp://diveintohtml5.info/video.htmlhttp://www.getfirefox.com/http://code.google.com/chromium/http://camendesign.com/code/video_for_everybodyhttp://www.apple.com/safari/
  • 8/14/2019 news in HTML5 and CSS3

    30/72

    Your browser supportsHTML5 s torage.

    function supports_ogg_theora_video() { if (!supports_video()) { return false; } var v = document.createElement("video");

    return v.canPlayType('video/ogg; codecs="theora, vorbis"');

    }

    Finally, WebM is a newly open-sourced (and non-patent-encumbered) video codec that will be included in the next versionof major browsers, including Chrome, Firefox , and Opera . You can use the same technique to detect support for openWebM video.

    function supports_webm_video() { if (!supports_video()) { return false; } var v = document.createElement("video");

    return v.canPlayType('video/webm; codecs="vp8, vorbis"');

    }

    Instead of writing this function yo urself, you can use Modernizr (1.5 or later) to detect support for different HTML5 videoformats.

    check for HTML5 video formats

    if (Modernizr.video) { // let's play some video! but what kind?

    if (Modernizr.video.webm) {

    // try WebM

    } else if (Modernizr.video.ogg) {

    // try Ogg Theora + Vorbis in an Ogg container

    } else if (Modernizr.video.h264){

    // try H.264 video + AAC audio in an MP4 container }}

    LOCAL STORAGE

    HTML5 storage provides a way for web sites to store information on your computer andretrieve it later. The concept is sim ilar to co okies, but its des igned for larger quantities o f information. Cookies are limited in size, and your browser sends them back to the webserver every time it requests a new page (which takes extra time and precious bandwidth).

    HTML5 sto rage stays o n your com puter, and web s ites can access it with J avaScript after thepage is lo aded.

    ASK PROFESSOR MARKUP

    Q: Is lo cal storage really part of HTML5? Why is it in a separate specification? A: The sho rt answer is yes , lo cal storage is part of HTML5. The slightly longer ans wer is that local storage used to bepart of the main HTML5 specification, but it was split out into a separate specification because some people in theHTML5 Working Group complained that HTML5 was too big. If that sounds like slicing a pie into more pieces to reducethe total number of calories well, welcome to the wacky world of standards.

    Checking for HTML5 storage support uses detection technique #1 . If your browser supports HTML5 storage, there will be a

    localStorage property on the global window object. If your browser doesnt support HTML5 storage, the localStorageproperty will be undefined. Due to an unfortunate bug in o lder versions of Firefox, this test will raise an exception if

    Detecting HTML5 Features - Dive Into HTML5 7/2/13

    http://diveintohtml5.info/detect.html#divingin 30 / 72

    http://dev.w3.org/html5/webstorage/http://labs.opera.com/news/2010/05/19/http://nightly.mozilla.org/webm/http://www.webmproject.org/
  • 8/14/2019 news in HTML5 and CSS3

    31/72

    Your browser supports web workers.

    cookies are disabled, so the entire test is wrapped in a try..catch s tatement.

    function supports_local_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch(e){ return false; }

    }

    Instead of writing this function yo urself, you can use Modernizr (1.1 or later) to detect support for HTML5 lo cal storage.

    check for HTML5 local storage

    if (Modernizr.localstorage) {

    // window.localStorage is available!} else { // no native support for local storage :( // try a fallback or another third-party solution}

    Note that JavaScript is case- sens itive. The Modernizr attribute is called localstorage (all lowercase), but the DOM

    property is called window.localStorage (mixed case).

    ASK PROFESSOR MARKUP

    Q: How secure is my HTML5 storage database? Can anyone read it? A: Anyone who has phys ical acces s to your computer can pro bably look at (o r even change) your HTML5 storage

    database. Within your browser, any web site can read and modify its own values, but sites cant access values stored byother sites. This is called a same-origin restriction .

    WEB WORKERS

    Web Workers provide a standard way for browsers to run JavaScript in thebackground. With web workers, you can spawn m ultiple threads that allrun at the same time, more or less. (Th