April 20, 2023 by admin
HTML/CSS Reference for DMET 155 Introduction to Web
Beginning of Intermediate HTML
Text: Abbreviations, Quotations, and Code
The basics of defining text using paragraphs (as well as emphasis and line breaks) and headings was covered in the HTML Beginner Tutorial. And for the same reason we use p and h1, h2, etc, there are a number of other tags we should also use to specifically represent other text-types, such as abbreviations, quotations, and computer code.
Abbreviations
abbr is used to markup an abbreviation, a shortened form of a word or phrase.
The expanded phrase that the abbreviation represents can be defined in the value of the title attribute. This is optional but recommended.
<p>This web site is about <abbr title="HyperText Markup Language">HTML</abbr> and <abbr title="Cascading Style Sheets">CSS</abbr>.</p>
Quotations
blockquote and q are used for quotations. blockquote is generally used for standalone often multi-line quotations whereas q is used for shorter, in-line quotations.
If the source of the quotation can be found on the Web, the cite attribute can be used to point to its origin.
<p>So I asked Bob about quotations on the Web and he said <q>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium</q>. It said:</p>
<blockquote cite="https://ndangelo.com">
<p>blockquote and q are used for quotations. blockquote is generally used for standalone often multi-line quotations whereas q is used for shorter, in-line quotations.</p>
</blockquote>
Blockquotes work very nicely with the HTML5 elements figure and figcaption, enabling a nice, semantic way to group a quotation with a citation:
<figure>
<blockquote>[Big old quotation about evolution]</blockquote>
<figcaption>Charles Darwin</figcaption>
</figure>
Citations
To make things nice and confusing, as well as a cite attribute, there is also a cite tag. This can be used to define the title of a work, such as a book.
<p>According to <cite>My tax bill</cite>, Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium</q>.</p>
Code
code is used to represent any form of computer code. Further, var can be used for variables (which could be a variable in anything, not just in code – it could be a variable in an equation, for example), samp for sample output, and kbd (keyboard) for user input.
<p>If you add the line <code><var>provide</var> = true;</code> to the <code>planet</code> subroutine and then type <kbd>Help</kbd> into the console, Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium <samp>Help!</samp> error sit voluptatem.</p>
Preformatted text
pre is preformatted text and is unusual in HTML tags in that it takes notice of every character in it, including the white space (whereas other elements will ignore a consecutive space or a line-break, for example). It is most commonly used for blocks of code, where spacing, such as indentations, can be relevant.
<pre><code>
<div id="intro">
<h1>Some heading</h1>
<p>Some paragraph paragraph thing thing thingy.</p>
</div>
</code></pre>
As an example, pre and code are used extensively throughout this site. The code blocks, such as the one above, are code elements inside pre elements. In-line references to tags and properties are simply code elements, often inside a elements to link to the reference section.
Meta Tags
Meta tags don’t do anything to the content presented in the browser window, but search engines use them to catalog information about the web page.
There is one meta tag which can be used as many times as you desire inside a head element and they can contain the attributes charset, name, http-equiv, and content.
When the name or http-equiv attribute is used, which is then used in conjunction with them to apply meta data.
Names
The name attribute can be anything you like. The most commonly used names are author, description, and keywords. author is used to explicitly state one of the HTML page’s authors and description is often used by search engines (such as Google) to display a web page description in its search results.
The reason why meta tags used to be so important was because they were relied on by search engines to build a profile of a web page. The keywords meta data was used extensively, for example. Nowadays, however, most search engines use the actual content of the page itself.
HTTP Equivalents
The http-equiv attribute can be used instead of the name attribute and will make an HTTP header, which is information sent to the server where the web page is held. The attribute should rarely be used (although see charset note, below) but the value can be:
content-type, an encoding declaration, defining what character set is being used,default-style, the preferred stylesheet from a selection oflinkorstyleelements,- or
refresh, which defines how often (in seconds) a page automatically refreshes or if it should automatically redirect to another page. Not great for accessibility.
The charset attribute can be used as a shorthand method to define an HTML document’s character set, which is always a good thing to do. <meta charset="utf-8"> is the same as <meta http-equiv="content-type" content="text/html; charset=utf-8">.
<head>
<title>Air conditioners? YEAH conditioners!</title>
<meta charset="utf-8">
<meta http-equiv="refresh" content="3"><!--not recommended for sane people-->
<meta name="description" content="This is my really, really, REALLY exciting web page about air conditioners">
...
Tables: rowspan and colspan
Tables may have seemed complicated. It can be quite difficult to visualize a two-dimensional grid from one-dimensional lines of code.
Well, it gets trickier. All thanks to the rowspan and colspan attributes.
<table>
<tr>
<th>Column 1 heading</th>
<th>Column 2 heading</th>
<th>Column 3 heading</th>
</tr>
<tr>
<td>Row 2, cell 1</td>
<td colspan="2">Row 2, cell 2, also spanning Row 2, cell 3</td>
</tr>
<tr>
<td rowspan="2">Row 3, cell 1, also spanning Row 4, cell 1</td>
<td>Row 3, cell 2</td>
<td>Row 3, cell 3</td>
</tr>
<tr>
<td>Row 4, cell 2</td>
<td>Row 4, cell 3</td>
</tr>
</table>
The first difference is that the td tags of the first row have been replaced with th tags. Whereas a td is a standard data cell, th is a header cell. As with td elements, these must be enclosed inside tr elements.
Spanning columns and rows
colspan and rowspan attributes have also been used in some of the td tags. If you look at this code in a browser, you will see that on the second row there are now two cells instead of three, the second cell spanning the second and third column. The colspan attribute, which means “column span” will span the cell over the number of cells that is specified. This means, in this example, that there is no need for a third td element — two cells are merged into one.
The rowspan attribute is similar to colspan, except, obviously, it will span across rows rather than columns. Again, the cells that it spans should be removed. In this example, because it spans over the fourth row, there are only two cells in that row.
As with the simpler 3×4, 12-cell table, the numbers on these tables with merged cells should also add up. Although there are only 10 cells in this example, there are 2 spans.
Description Lists
Description lists are quite often forgotten. This is maybe because they are much more specific than ordered and unordered lists and therefore less useful, generally, but where there is a list of terms and descriptions (such as a glossary), a description list is your go-to-element.
dl gets the ball rolling, similar to the ul and ol elements, establishing the list. Rather than containing li elements, though, description lists have dt elements, which are the terms, followed by dd elements, which are the descriptions associated to the dt elements.
There doesn’t have to be one dt followed by one dd, there can be any number of either. For example, if there are a number of words that have the same meaning, there might be a number of dt’s followed by one dd. If you have one word that means various different things, there might be one dt followed by several dd’s.
<h1>Some random glossary thing</h1>
<dl>
<dt>HTML</dt>
<dd>Abbreviation for HyperText Markup Language - a language used to make web pages.</dd>
<dt>Dog</dt>
<dd>Any carnivorous animal belonging to the family Canidae.</dd>
<dd>The domesticated sub-species of the family Canidae, Canis lupus familiaris.</dd>
<dt>Moo juice</dt>
<dt>Cat beer</dt>
<dt>Milk</dt>
<dd>A white liquid produced by cows and used for human consumption.</dd>
</dl>
Text: Addresses, Definitions, Bi-directional, and Editorial
OK, so we should all be know by now that there are lots of tags for text. We’ve done paragraphs, we’ve done headings, we’ve even done abbreviations, quotations, and code. And there are several other, more obscure tags that can be used. Obscure because you won’t find them plastered around the Web, not because they are unhelpful. If you find you have text that fits these elements’ descriptions, you will have a nicer, richer, more meaningful HTML page if you use them.
Addresses
address should be used specifically for the contact details relating either to the entire web page (and so only used once) or to an article element (see Sectioning). It’s isn’t, as it might at first appear, for marking up any old address willy-nilly.
<h3>Author contact details</h3>
<address>
<ul>
<li>0123-456-7890</li>
<li>author_dude@noplaceinteresting.com</li>
<li>http://www.noplaceinteresting.com/contactme/</li>
</ul>
</address>
Definition terms
dfn is a definition term and is used to highlight the first use of a term. Like abbr, the title attribute can be used to describe the term.
<p>Bob's <dfn title="Dog">canine</dfn> mother and <dfn title="Horse">equine</dfn> father sat him down and carefully explained that he was an <dfn title="A mutation that combines two or more sets of chromosomes from different species">allopolyploid</dfn> organism.</p>
Bi-directional text
bdo can be used to reverse the direction of the text, and can be used to display languages that read right to left. The value of the required attribute dir can be ltr (left to right) or rtl (right to left).
<bdo dir="rtl">god lmth</bdo>
Editorial
ins and del are used to display editorial insertions and deletions respectively. Strictly speaking, they aren’t limited to text and can be used over whole swathes of content but, typically, they are used in moderation just like “Track Changes” feature in word processors tend to be.
They can have the attributes datetime to indicate when the edit was made and cite, to point to a description as to why the edit has been made.
<p>I have decided to <del datetime="2013-01-26">decrease</del> <ins cite="http://www.icecreamforall.com/changeofpolicy/">increase</ins> the amount of free ice cream that the State will provide for its citizens.</p>
As with traditional word processor-based editing, the ins element is typically shown underlined and the del element is usually displayed with a strikethrough.
And there’s yet more… HTML 5 brings with it even more text-related elements. See the final article on text in the HTML Advanced Guide, complete with a look at the reclassification of the dreaded “presentational” elements.
Sectioning
While headings do a grand, perfectly valid, job in defining the start of a new section or sub-section in a document, there are a number of elements that can be exploited to establish a cleaner, clearer semantic structure.
Whereas div elements can be used to contain sections, used primarily as scaffolding on which to hang CSS, they don’t hold a great deal of meaning. Sectioning involves a handful of tags that can be used to define specific parts of a page, such as articles, headers, footers, and navigation.
Articles and Sections
An article element can be used to mark up a standalone section of content. This could be used just once, if you think of a blog post as an article, for example, or a number of times, if you imagine replicating a traditional newspaper page with numerous articles.
A section element represents a more general section and could be used to split up an article, or to represent chapters, for example.
<article>
<section id="intro">
<p>[An introduction]</p>
</section>
<section id="main_content">
<p>[Content]</p>
</section>
<section id="related">
<ul>
<li><a href="that.html">That related article</a></li>
<li><a href="this.html">This related article</a></li>
</ul>
</section>
</article>
While divs could be used to make these separations (or even if you didn’t need these separations for styling), this provides a much richer, more meaningful document.
The HTML5 specifications suggest that you can use h1 elements at the start of each section, which would become a sub-heading of anything preceding that section (so, in the example above, if you had an h1 immediately following the opening article tag, an h1 immediately after an opening section tag would be a sub-heading of that initial h1). This screws backwards compatibility, however, and any user agents (including screen readers) that don’t understand this won’t apply properly structured heading levels. We suggest sticking to the headings levels you would use if you didn’t use sections (so h1, followed by h2, etc, regardless of the sectioning). This doesn’t break anything or detract from the meaning or semantics.
Headers and Footers
header and footer provide further specialized, self-descriptive, sections:
<body>
<article>
<header>
<h1>Alternatively…</h1>
<p>[An introduction]</p>
</header>
<section id="main_content">
<p>[Content]</p>
</section>
<footer>
<p>[End notes]</p>
</footer>
</article>
<footer>
<p>[Copyright bumf]</p>
</footer>
</body>
The footer is the footer of the section in which it is contained. So, in the above example, the first footer is the footer of the article and the second footer is the footer of the page.
Asides
An aside can be used to represent content that is related the content surrounding it. Think of pull-quotes or snippets of related information in an article:
<section id="main_content">
<h1>Tixall</h1>
<p>[All about Tixall]</p>
<aside>
<h2>Tixall Obelisk</h2>
<p>[A short note about Tixall Obelisk]</p>
</aside>
<p>[Maybe a bit more about Tixall]</p>
</section>
While we’re at this structure-love, if you want to include figures, there happens to be two tags for doing just that:
<figure>
<img src="obelisk.jpg">
<figcaption>Tixall Obelisk</figcaption>
</figure>
Note that the img element doesn’t need an alt attribute IF the figcaption (that’s “figure caption”, in case you need it spelling out) does that job.
Navigation
Finally, there’s nav, used to mark up a group of navigation links:
<nav id="main_nav">
<ul>
<li><a href="/tutorials/">Tutorials</a></li>
<li><a href="/techniques/">Techniques</a></li>
<li><a href="/examples/">Examples</a></li>
<li><a href="/references/">References</a></li>
</ul>
</nav>
This could also be used for in-page navigation (<a href="#overthere">... etc.) but it isn’t necessary for every group of links – it is designed for major groupings. A copyright, author, and contact link could sit happily by themselves in a footer element, for example.
If you want to style these new HTML 5 elements (and you probably do, right? It’s much nicer than using <div id="content">..., etc) you will experience a problem in older browsers, most notably Internet Explorer versions 8 and earlier, that don’t understand these tags.
HTML5Shiv can come to your rescue, however; a small piece of JavaScript, slotted in to your head element, that teaches the remedial browsers and holds their hands so that you can use new HTML 5 tags and style them up to your heart’s content with CSS.
It’s your call if you want to use a JavaScript fudge or stick with the safe old (and, again, perfectly valid) but semantically poorer headings and divs approach. This site, along with many others, chooses the former. Because HTML 5’s loveliness just about outweighs a hack’s ugliness.
From: https://www.htmldog.com/
End of Intermediate HTML
Beginning of Advanced HTML
Text: Time, Mark, and “Presentational”
HTML5 adds and amends a handful of tags relating to text. Many of the minor amendments, such as differing attributes in existing tags, have already been covered, but this page looks at two new tags — time and mark — as well as the re-definition of presentational tags.
Time
time is by far the chocolate ice cream sexiest sweet sugar lovely of these tags and is used to make dates and times super-semantically rich and mmm.
The text sandwiched in the middle of the opening and closing tag can be any format of date of time – the whole precise lot, or just one part, such as a day. It is made more helpful, however, by the datetime attribute, the value of which should be a machine-readable date and/or time.
<p>Written by Doctor Who on <time datetime="2052-11-21">Thursday 21st November 2052</time>.</p>
Valid datetime values can take the format of a year-month-day date (as above), of as a “fuzzy” date, such as “2052-11”, of a time, such as “09:30” (always using a 24-hour clock) or a combination, such as “2052-11-21 09:30”. This can also accommodate time zones and durations.
If the textual content of the time element is already machine readable, you don’t need the datetime attribute but it is required if it isn’t.
Mark
Text can be highlighted, as if with a marker pen, using mark:
<blockquote>
<p>He wants to play with his <mark>Legos</mark></p>
</blockquote>
<p>The person being quoted is clearly American because, for some odd reason, they pluralise "Lego".</p>
Yes, this is a form of emphasis, literally speaking, but it won’t always be considered emphasis in the original meaning (for example, the person being quoted above isn’t emphasizing “Legos”, the commenter is), hence its inclusion.
Conditional Comments
So, you’re looking for a filthy hack that allows you to target HTML solely at versions of Microsoft’s Internet Explorer browser, are you? How convenient.
Older versions of Internet Explorer are frequently either inept or naughty. Or both. But they are still popular so we don’t want to ignore them.
Conditional comments, which are nothing more than simple HTML comments that IE (up to version 9) happens to take a peep at, are used to throw a chunk of HTML at these browsers and only these browsers. Other well behaved, top-of-the-class browsers will simply see them as unremarkable comments and move along.
This web site currently uses conditional comments to make a handful of amendments for IE 8 and below, including a small extra stylesheet, and the HTML5 Shiv required for these browsers to take notice of some HTML5 elements. Go ahead – view the source.
They have become a commonly used method of latching extra CSS to a document to plaster over holes in these browsers’ display capabilities. So, for example, you might add something like this inside your head element:
<link href="everything.css" rel="stylesheet">
<!--[if IE]><link href="stupidie.css" rel="stylesheet"><![endif]-->
Everything between <!--[if IE]> and <![endif]--> will be picked up by Internet Explorer. So this will bolt on a CSS file as normal, and then, only if the browser is Internet Explorer (in practice, this will be Internet Explorer version 9 and below), it will also apply an extra CSS file patch.
You can also target specific versions of Internet Explorer:
<!--[if IE 6>…<!--[if IE 7>…<!--[if IE 8>…<!--[if IE 9>…
You can also target all versions that are greater or less than a certain number:
- eg.
<!--[if IE gt 6]>… for IE versions greater than 6 - eg.
<!--[if IE gte 8]>… for IE versions greater than or equal to than 8 - eg.
<!--[if IE lt 7]>… for IE versions less than 7 - eg.
<!--[if IE lte 7]>… for IE versions less than or equal to 7
There are actually more options than this which are largely totally unnecessary. Take a look at Microsoft’s own take on it if you really feel compelled to find out more.
Conditional comments really are horrible. Necessary, often, at the moment, but horrible. Like all hacks, it is best to avoid them wherever possible. They’re not really there for whacking completely different stylesheets in different browsers, for example. It’s more for small fallbacks so that you can use the scrumptious likes of CSS 3 without compromise. And don’t assume you have to accommodate every stone-age version of IE, either – try and figure out what is sensible for you to support. Are your web site visitors likely to be using IE6? Probably not.
Tables: Columns, Headers, and Footers
So you think you know how to make a table. Sure, you know the table, tr, td and th tags, you’ve even got the rowspan and colspan attributes in your pocket. You can make a really cute little plywood coffee table, but don’t you want to know how to make one of those polished solid wood, glass top dining tables that can take the weight of an oversized elephant?
The Columns Strike Back
Table rows tend to make table columns look rather stupid. They do all the work, as the table is built row by row, leaving the columns feeling quite rejected.
Luckily for those eager columns though, the colgroup and col tags have come to their rescue.
These tags allow you to define the table columns and style them as desired, which is particularly useful if you want certain columns aligned or colored differently, as, without this, you would need to target individual cells.
<table>
<colgroup>
<col>
<col class="alternative">
<col>
</colgroup>
<tr>
<td>This</td>
<td>That</td>
<td>The other</td>
</tr>
<tr>
<td>Ladybird</td>
<td>Locust</td>
<td>Lunch</td>
</tr>
</table>
In this example, the CSS class “alternative” styles will be applied to the second column, or the second cell in every row.
You can also use the span attribute in a similar way to rowspan and colspan. Using it with the colgroup tag will define the number of rows that the column group will belong to, for example <colgroup span="2"></colgroup> would group the first two columns. Using span in the col tag is usually more useful, and could, for example, be applied to the above example like this:
<table>
<colgroup>
<col>
<col span="2" class="alternative">
</colgroup>
<!-- and so on -->
This would apply “alternative” to the last two columns.
When span is used in colgroup, you shouldn’t then use col tags.
Caption interlude
A brief and easy accessibility consideration is to apply a caption to the table. The caption element defines the caption and should be used straight after the opening table tag.
<table>
<caption>Locust mating habits</caption>
<!-- etc. -->
A caption will appear above the table by default, although using the CSS caption-side: bottom will, well, do what you would expect.
The mightier figcaption would be preferable to caption if you are marking up a table as the sole content of a figure element. See the Sectioning page for more.
Headers and Footers
thead, tfoot and tbody allow you to separate the table into header, footer and body, which can be handy when dealing with larger tables.
Whereas thead needs to come first, tfoot can, in fact come before a tbody (and you can have more than one tbody, if it takes your fancy) although browsers will render the tfoot element at the bottom of the table.
<table>
<thead>
<tr>
<td>Header 1</td>
<td>Header 2</td>
<td>Header 3</td>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer 1</td>
<td>Footer 2</td>
<td>Footer 3</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
<!-- etc. -->
</tbody>
</table>
Accessible Links
There are a number of ways links — the absolutely fundamentally most important interactive element of web sites — can be made more accessible to those people with disabilities.
Tabbing
Users who do not or cannot use pointing devices can tab through links and, as such, links should be in a logical tabbing order. The tabindex attribute allows you to define this order although if the HTML is linear, as it should be, a logical tabbing order should automatically fall into place.
<ul>
<li><a href="here.html" tabindex="1">Here</a></li>
<li><a href="there.html" tabindex="3">There</a></li>
<li><a href="limbo.html" tabindex="2">Limbo</a></li>
</ul>
In this example (which is used purely as a demonstration – it would be quite dumb, practically speaking), tabbing would jump from “Here” to “Limbo” to “There”.
The good bit of link-accessibility advice is to write good link text. Have the words the a tags wrap around explain where the link will take the user. If someone is using a screen reader, having the links read out to them as they tab between them, the user will then know what they’re letting themselves in for if they select a link. “Click here” or random words aren’t especially helpful…
Link titles
If you have a link that isn’t self-descriptive or the link destination could benefit from being explained in more detail, you can add information to a link using the title attribute.
<p>I'm really bad at writing link text. <a href="inept.html" title="Why I'm rubbish at writing link text: An explanation and an apology.">Click here</a> to find out more.</p>
Another tip: Don’t have links open something in a new window or tab. It’s precious to think your page is important enough to stay alive while a user visits elsewhere anyway. We all know how to use the back button. We know how to close windows and tabs, too, but if you can’t see that that’s what has happened…
If you insist on doing this, at least mention it in a link title.
Accesskeys
Access keys allow easier navigation by assigning a keyboard shortcut to a link (which will usually gain focus when the user presses “Alt” or “Ctrl” + the access key).
<a href="somepage.html" accesskey="s">Some page</a>
For users who do not use pointing devices, this can be a quick way to navigate. The trouble is that there the user may not know what they are unless they are explicitly stated although some assistive software will tell the user what these are.
Skipping HTML
To aid tabbing, you can supply links that allow users to jump over chunks of your web page. You might want to allow someone to jump over a plethora of navigation links, for example, so they can just read a page’s main content rather than cycle through all of the links:
<header>
<h1>The Heading</h1>
<a href="#content">Skip to content</a>
</header>
<nav>
<!--loads of navigation stuff -->
</nav>
<section id="content">
<!--lovely content -->
</section>
You probably won’t want this link to be displayed visually – it’s a peculiar link to see for abled-bodied users and screen reader users won’t need to see it (it will be read out). So you can use CSS to render it invisible but it could also be beneficial to those with motor disabilities so you might also want to consider making it visible when it has focus from being tabbed to using the :focus CSS pseudo class.
Accessible Forms
Forms aren’t the easiest of things to use for people with disabilities. Navigating around a page with written content is one thing, hopping between form fields and inputting information is another. Because of this, it is a good idea to add a number of elements to the form.
Labels
Each form field should have its own explicit label. The label tag sorts this out, with a for attribute that associates it to a form element:
<form>
<label for="yourName">Your Name</label>
<input name="yourName" id="yourName">
<!-- etc. -->
Labels have the added bonus of visual browsers rendering the labels themselves clickable, putting the focus on the associated form field.
Both name and id attributs are typically required; the name for the form to handle that field and the id for the label to associate it to.
Field sets and legends
You can group fields, for example name (first, last, middle, title etc.) or address (line 1, line 2, county, country, postal code, country etc.) using the fieldset tag.
Within the field set, you can set a caption with the legend tag.
<form action="somescript.php" >
<fieldset>
<legend>Name</legend>
<p>First name <input name="firstName"></p>
<p>Last name <input name="lastName"></p>
</fieldset>
<fieldset>
<legend>Address</legend>
<p>Address <textarea name="address"></textarea></p>
<p>Postal code <input name="postcode"></p>
</fieldset>
<!-- etc. -->
Most browsers tend to represent field sets with a border surrounding them and the legend caption breaking the left of the top border by default. You can, of course, change this with CSS if you wish.
Option groups
The optgroup element groups options in a select box. It requires a label attribute, the value of which is displayed as a non-selectable pseudo-heading preceding that group in the drop-down list of visual browsers.
<select name="country">
<optgroup label="Africa">
<option value="gam">Gambia</option>
<option value="mad">Madagascar</option>
<option value="nam">Namibia</option>
</optgroup>
<optgroup label="Europe">
<option value="fra">France</option>
<option value="rus">Russia</option>
<option value="uk">UK</option>
</optgroup>
<optgroup label="North America">
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="usa">USA</option>
</optgroup>
</select>
Navigating fields
Like links, form fields (and field sets) need to be navigated to without the use of a pointing device, such as a mouse. The same methods used in links to make this task easier can be used on form elements — tab stops and access keys.
The accesskey and tabindex attributes can be added to the individual form tags such as input and also to legend tags.
<input name="firstName" accesskey="f" tabindex="1">
HTML5 Forms Pt. 1: Input Types
HTML5 greatly advances form controls, with numerous additional input types, several new attributes, and a handful of extra elements.
Getting this warning in early, in case you quite understandably decide that it would be a waste of time reading the rest of this page, a vast majority of this new gubbins will not yet work fully on all major browsers.
Additional input types
Basic form fields created using the input element include text, password, checkbox, radio, and submit. These types have been extended in HTML5 to accommodate more specific fields:
Search
Used for a search query text box, this performs exactly as a standard text input should.
<input type="search" name="search">
The main intention of the inclusion of this input type in the HTML5 specification is one of style. As well as making your HTML clearer, you can also target this element with a CSS attribute selector:
input[type=search] { background: url(magnifyingglass.png) right no-repeat) }
Telephone, URL, and email addresses
Other “special” text input types include tel, for telephone numbers, url, for web addresses, and email, for email addresses.
<input type="tel" name="telephone_number">
<input type="url" name="web_address">
<input type="email" name="email_address">
You can use the :valid and :invalid CSS3 pseudo classes to style these fields depending on whether their content is considered valid.
input[type=email]:valid { background: green }
input[type=email]:invalid { background: red }
This example will paint an email field’s background green if the entered text is recognized as an email address (such as “sausage@htmldog.com”) or red if it isn’t (if the user were to type “sausages?”, for example).
Numbers and ranges
A simple text box that also allows a user to directly type in a number, or cycle through numbers (usually using an up and down arrow to the side of the field), can be achieved with type="number". A further step attribute can be added to specify how much is added or subtracted from the number with each increment.
If you also want the number to have a minimum or maximum value, you can further use the min and max attributes.
<input type="number" name="quantity" step="2" min="20" max="30">
Once again, if this is supported, the user will be able either to type directly into the field or, if using the arrows, cycle between 20 and 30, two units at a time.
You can use the :valid and :invalid pseudo classes in relation to this, too. If the user were to type “12”, for example, that would be invalid, because it isn’t between 20 and 30. If they typed “23” that would also be invalid because it isn’t a multiple of 2.
An alternative to the digits-in-a-text-box approach can be achieved using type="range". By default, this should be displayed as a horizontal bar with a slider in the middle of it. The user can then adjust the slider left and right, the far left resulting in a value of “0” and the far right a value of “100”. This range can be adjusted using the min and max attributes.
<input type="range" name="temperature" min="15" max="25" step="0.5" value="18.5">
Dates and times
There are several input types for dates and times:
type="datetime"type="date"type="month"type="week"type="time"type="datetime-local"
If supported (they aren’t, widely, and they are also inconsistent between browsers), these will prompt the user to enter a date or time in a specific format, either by directly typing it in, cycling through one week/day/hour/minute/etc. at a time, or by selecting from a dropdown calendar.
step, min, and max attributes can be used with dates and times, too, as can the CSS pseudo classes to style according to validity.
Color
Finally, type="color" is designed to allow a user to select a color, sending a six-digit hex code as its value.
<input name="color" type="color" value="#ff8800">
HTML5 Forms Pt. 2: Attributes and Data Lists
Continuing from HTML5 Forms Pt. 1, in addition to the multitude of fresh new input types, there are also additional form-specific attributes at your disposal as well as data lists, a sort of text/select hybrid.
More attributes
As well as those attributes mentioned, both here and in earlier guides, there is a handful of additional attributes:
Placeholder text
The placeholder attribute can be used with text input fields (and their text-like cousins, such as type="email" and type="number") as well as textarea elements. It is intended as a hint, rather than a label, for which a label element should still be used.
<label for="email_address">Email address</label>
<input type="email" placeholder="you@somewhere.com" name="email_address" id="email_address">
Autofocus
You might want focus to land on a form field when a page loads. If you think of a search engine, for example, when you land on its home page you don’t normally need to click on the search box to start typing – you can do so straight away because it already has focus. The autofocus attribute is a quick way to achieve this effect.
<input name="query" autofocus>
Data lists
A data list takes the form of a list of suggestions that accompanies a text field:
<input name="country" list="country_name">
<datalist id="country_name">
<option value="Afghanistan">
<option value="Albania">
<option value="Algeria">
<option value="Andorra">
<option value="Armenia">
<option value="Australia">
<option value="Austria">
<option value="Azerbaijan">
<!-- etc. -->
</datalist>
The value of the list attribute in the input element (which could be any of the text-like input types) binds it to a datalist element with the corresponding ID (“country_name”, in this example). As a user types in the text field, if what they type matches the start of anything in the data list, those matches will be shown underneath the text field as suggestions. So, here, if “A” is typed, the 8 countries beginning with “a” are displayed. If “L” is typed after “A”, the list of suggestions will reduce to just “Albania” and “Algeria”, and so on. The data sent when the form is submitted will be whatever is in the text field – it could be something selected from the list or it could be something completely different, inputted by the user.
The good news is that many of the features outlined in these two HTML 5 Forms pages degrade gracefully. Those browsers that don’t support data lists still maintain the text box; unrecognised input types revert to text inputs, so you can use the likes of search, tel, and url as long as you aren’t relying on their special features; placeholder text simply won’t appear so as long as it isn’t essential, go for it.
Embedded Content: Video, Audio, and Canvas
HTML5 introduces a swathe of new tags to accommodate the increasingly interactive and multimedia nature of the Web. While there have been numerous ways to embed video, audio, and dynamic imagery in the past, the new web standard attempts to make this easier, more consistent, and more reliable.
The simplest embedded (foreign) content is an image, applied to a web page with the img element. In the olden days, object, along with various plugins and proprietary devil dust, was used to bash and smash video and audio into submission. Although not without its (compatibility) problems, there is now a much better method for using various types of media in web pages.
Video
<video src="kitties.mp4" controls></video>
Bam. There you go. Just like that. Simple.
This will embed a video, complete with controls, in browsers that support the HTML5 video tag and the video content type.
While HTML5 is pushing for a standard framework to play media, the media itself is not standardised across browsers. In practice, this means that it is unlikely all visitors will be able to experience your video (or audio) file. Some support WebM video, for example, while others support MPEG. Don’t lose too much sleep over this, though — see “Alternative content”, below.
The controls attribute is optional but if you don’t want it – if you really want to take control away from the user – you can just slap in an autoplay attribute:
<video src="kitties.mp4" autoplay></video>
This will play the video on page load, won’t display any controls, and will most likely annoy the hell out of your visitors. Of course you could, if you were kind, put in both the controls and autoplay attributes.
Other basic attributes at your disposal include width, height, loop, and muted.
<video src="kitties.mp4" width="300" height="200" loop muted autoplay controls></video>
If you insist on using autoplay, bringing muted (and controls) to the party as well is a nice gesture and is a convention that many sites employ. If you have a video in an aside, for example, it can begin playing but the user can then opt to follow it by de-muting the video via the controls, if they choose, decreasing the likelihood of irritation.
Poster
You can specify a placeholder image, which will be displayed before the video is played, with the poster attribute.
<video src="kitties.mp4" poster="fluffy.jpg" controls></video>
The specified image will stretch or shrink to fit the dimensions of the video, regardless of the original size of the image.
Fall-back content
So, yes, there is an opening and closing tag. Whatever could go in between them? Why, fall-back content: content that is displayed if the browser doesn’t understand the video element. That could be a few words, a chunk of HTML, or a “really funny” and “highly original” Lolcats image.
<video src="kitties.mp4" controls>
<img src="hahahaha.jpg" alt="Hilarious cat and caption saying 'soz'.">
</video>
Alternative content
As already noted, it’s not only compatibility with the tag we need to worry about, but also compatibility with the source video itself. Luckily, more than one video source file can be offered up with the source element along with indications of the requirements of the file in the value of the type attribute. The browser will then take the first one it’s happy with.
<video controls>
<source src="kitties.mp4" type="video/mp4; codecs='avc1, mp4a'">
<source src="kitties.webm" type="video/webm; codecs='vp8.0, vorbis'">
<p>Browser no likey HTML 5.</p>
</video>
Here, a browser should figure out if it can handle the “video/mp4” MIME type and if it has the stated codec to decipher it. If it doesn’t, it should move on to the next and try again with the details set out in the second source element.
Audio
Applying audio is just like applying video. Using the audio tag, the structure is the same as using video and the attributes src, controls, autoplay and loop can all be used in the same way.
<audio src="meow_mix.mp3" controls>
Your stupid browser doesn't support HTML 5 audio.
</audio>
Alternative content can also be defined in exactly the same way as with the video and source tags.
Much greater control can be exercised over video and audio using JavaScript, with the ability to manipulate aspects of playback and user controls in more detail.
Canvas
A major addition to HTML5 is the canvas element. It is designed to provide a canvas onto which JavaScript can be used to paint all manner of dynamic images such as graphs, animated sprites, or daft cat pictures.
<canvas id="wittykitty" width="800" height="450">
<!-- Fall-back content here, just like with video and audio -->
</canvas>
From: https://www.htmldog.com/
