At W3Schools you will find complete references about tags,
attributes, events, color names, entities, character-sets, URL encoding,
language codes, HTTP messages, and more.
An HTML element usually consists of a start tag and end tag,
with the content inserted in between:
<tagname>Content goes here...</tagname>
The HTML element is everything from the start tag to the end tag:
<p>My first paragraph.</p>
Start tag
Element content
End tag
<h1>
My First Heading
</h1>
<p>
My first paragraph.
</p>
<br>
HTML elements with no content are called empty elements. Empty elements do not have an end tag, such as the <br>
element (which indicates a line break).
Nested HTML Elements
HTML elements can be nested (elements can contain elements).
All HTML documents consist of nested HTML elements.
This example contains four HTML elements:
Example
<!DOCTYPE html>
<html> <body>
<h1>My First Heading</h1> <p>My first paragraph.</p>
The example above works in all browsers, because the closing tag is considered optional.
Never rely on this. It might produce unexpected results and/or errors if you forget the end tag.
Empty HTML Elements
HTML elements with no content are called empty elements.
<br> is an empty element without a closing tag (the <br> tag defines a line break).
Empty elements can be "closed" in the opening tag like this: <br />.
HTML5 does not require empty elements to be closed. But if you want stricter
validation, or if you need to make your document readable by XML parsers, you
must close all HTML elements properly.
Use Lowercase Tags
HTML tags are not case sensitive: <P> means the same as <p>.
The HTML5 standard does not require lowercase tags, but W3C
recommends lowercase in HTML, and demands lowercase for stricter document types like XHTML.
At W3Schools we always use lowercase tags.
HTML Attributes
Attributes provide additional information about HTML elements.
HTML Attributes
All HTML elements can have attributes
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes usually come in name/value pairs like: name="value"
The href Attribute
HTML links are defined with the <a> tag. The link address is specified in the href attribute:
Example
<a href="https://www.w3schools.com">This is a link</a>
You will learn more about styling later in this tutorial, and in our
CSS Tutorial.
The lang Attribute
The language of the document can be declared in the <html> tag.
The language is declared with the lang attribute.
Declaring a language is important for accessibility applications (screen readers) and search engines:
<!DOCTYPE html> <html lang="en-US"> <body>
...
</body> </html>
The first two letters specify the language (en). If there is a dialect, use two more letters (US).
The title Attribute
Here, a title attribute is added to the <p>
element.
The value of the title attribute will be displayed as a tooltip when
you mouse over the paragraph:
Example
<p title="I'm a tooltip"> This is a paragraph. </p>
Note: Metadata typically define the document title, character set, styles, links, scripts, and other meta information.
How to View HTML Source?
Have you ever seen a Web page and wondered "Hey! How did they do that?"
View HTML Source Code:
To find out, right-click in the page and select "View Page Source" (in
Chrome) or "View Source" (in IE), or similar in other browsers. This will open a window
containing the HTML source code of the page.
Inspect an HTML Element:
Right-click on an element (or a blank area), and choose "Inspect" or
"Inspect Element" to see what elements are made up of (you will see both
the HTML and the CSS). You can also edit the HTML or CSS on-the-fly in the
Elements or Styles panel that opens.
Note: Browsers display <strong> as <b>, and <em> as <i>.
However, there is a difference in the meaning of these tags:
<b> and <i> defines bold and italic text, but
<strong> and <em> means that the text is "important".
For 50 years, WWF has been protecting the future of nature.
The world's leading conservation organization,
WWF works in 100 countries and is supported by
1.2 million members in the United States and
close to 5 million globally.
The HTML <blockquote> element defines a section that
is quoted from another source.
Browsers usually indent <blockquote> elements.
Example
<p>Here is a quote from WWF's website:</p> <blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature. The world's
leading conservation organization, WWF works in 100 countries and is
supported by 1.2 million members in the United States and close to 5
million globally. </blockquote>
You can set the background color for HTML elements:
Hello World
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
The lightness off a color can be described as how much light you want to give the color, where 0% means no light (black), 50% means 50% light (neither dark nor light) 100% means full lightness (white).
CSS describes how HTML elements are to be displayed on screen,
paper, or in other media.
CSS saves a lot of work. It can control the layout of
multiple web pages all at once.
CSS can be added to HTML elements in 3 ways:
Inline - by using the style attribute in HTML elements
Internal - by using a <style> element in the <head> section
External - by using an external CSS file
The most common way to add CSS, is to keep the styles in separate CSS
files. However, here we will use inline and internal styling, because this is easier to
demonstrate, and easier for you to try it yourself.
Tip: You can learn much more about CSS in our CSS Tutorial.
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
This example sets the text color of the <h1> element to blue:
Example
<h1 style="color:blue;">This is a Blue Heading</h1>
The href attribute specifies the destination address (https://www.w3schools.com/html/)
of the link.
The link text is the visible part (Visit our HTML tutorial).
Clicking on the link text will send you to the specified address.
Note: Without a forward slash on subfolder addresses, you might generate two requests to the server.
Many servers will automatically add a forward slash to the address, and then create a new request.
Local Links
The example above used an absolute URL (A full web address).
A local link (link to the same web site) is specified with a relative URL (without http://www....).
The <img> tag is empty, it contains attributes only, and does not
have a closing tag.
The src attribute specifies the URL
(web address) of the image:
<img src="url">
The alt Attribute
The alt attribute provides an alternate text for an image, if the user for
some reason cannot view it (because of slow connection, an error in the src
attribute, or if the user uses a screen reader).
The value of the alt attribute should describe the image:
Example
<img src="img_chania.jpg" alt="Flowers
in Chania">
HTML5 introduced the <picture> element to add more flexibility when
specifying image resources.
The <picture> element contains a number of <source> elements, each referring
to different image sources. This way the browser can choose the image that best
fit the current view and/or device.
Each <source> element have attributes describing when their image is the
most suitable.
The browser will use the first <source> element with matching attribute
values, and ignore any following <source> elements.
Example
Show one picture if the browser window (viewport) is a minimum of 650
pixels, and another image if not, but larger than 465 pixels.
Note: Always specify an <img> element as the last child
element of the <picture> element. The <img> element is used by browsers that to
not support the <picture> element, or if none of the <source> tags matched.
HTML Screen Readers
A screen reader is a software program that reads the HTML code, converts the
text, and allows the user to "listen" to the content. Screen readers are useful
for people who are blind, visually impaired, or learning disabled.
Chapter Summary
Use the HTML <img> element to define an image
Use the HTML src attribute to define the URL of the image
Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed
Use the HTML width and height attributes to define the size of the image
Use the CSS width and height properties to define the size of the image (alternatively)
Use the CSS float property to let the image float
Use the HTML <map> element to define an image-map
Use the HTML <area> element to define the clickable areas in the image-map
Use the HTML <img>'s element usemap attribute to point to an image-map
Use the HTML <picture> element to show different images for different devices
Note: Loading images takes time. Large images can slow down your page. Use images carefully.
Each table row is defined with the <tr> tag. A table header is
defined with the <th> tag. By default, table headings are
bold and centered. A table data/cell is defined with the
<td> tag.
Every HTML element has a default display value depending on what type
of element it is. The default display value for most elements is block or inline.
Block-level Elements
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).
The <div> element is
often used as a container for other HTML elements.
The <div> element has no required attributes, but both style and class are common.
When used together with CSS, the <div> element can be used to style blocks of
content:
Example
<div style="background-color:black;color:white;padding:20px;">
<h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
</div>
The class attribute can be used on any HTML element.
Using The class Attribute in JavaScript
JavaScript can access elements with a specified class
name by using the getElementsByClassName() method:
Example
When a user clicks on a button, hide all elements with the class name
"city":
<script> function myFunction() { var x = document.getElementsByClassName("city"); for (var i = 0; i < x.length;
i++) { x[i].style.display = "none"; } } </script>
The <noscript> tag is used to provide an alternate content for users that
have disabled scripts in their browser or have a browser that doesn't support
client-side scripts:
It is a best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your current
base URL. All links will work on your own computer (localhost) as well as on
your current public domain and your future public domains.
HTML Head
The HTML <head> Element
The <head> element is a container for metadata (data
about data) and is placed between the <html> tag and the <body> tag.
HTML metadata is data about the HTML document. Metadata is not displayed.
Metadata typically define the document title, character set, styles, links, scripts, and other meta information.
The following tags describe metadata: <title>, <style>,
<meta>, <link>, <script>, and <base>.
The HTML <title> Element
The <title> element defines the title of the document,
and is required in all HTML/XHTML documents.
The <title> element:
defines a title in the browser tab
provides a title for the page when it is added to favorites
displays a title for the page in search engine results
W3Schools does not recommend omitting the <html> and <body>
tags. Omitting these tags can crash DOM or XML software and produce errors in older browsers
(IE9).
However, omitting the <head> tag has been a common practice for quite some
time now.
London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.
Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.
Websites often display content in multiple columns (like a magazine or newspaper).
HTML5 offers new semantic elements that define the different parts of a web page:
<header> - Defines a header for a document or a section
<nav> - Defines a container for navigation links
<section> - Defines a section in a document
<article> - Defines an independent self-contained article
<aside> - Defines content aside from the content (like a sidebar)
<footer> - Defines a footer for a document or a section
<details> - Defines additional details
<summary> - Defines a heading for the <details> element
HTML Layout Techniques
There are four different ways to create multicolumn layouts. Each way has its pros and cons:
HTML tables
CSS float property
CSS framework
CSS flexbox
Which One to Choose?
HTML Tables
The <table> element was not designed to be a layout tool! The purpose of the
<table> element is to display tabular data. So, do not use tables for your page layout! They will bring a mess into your code. And imagine how hard it will be to redesign your site after a couple of months.
Tip: Do NOT use tables for your page layout!
CSS Frameworks
If you want to create your layout fast, you can use a framework, like
W3.CSS or Bootstrap.
CSS Floats
It is common to do entire web layouts using the CSS float property. Float is easy to learn
- you just need to remember how the float and clear properties work.
Disadvantages: Floating elements are tied to the document flow, which may harm
the flexibility. Learn more about float in our CSS
Float and Clear chapter.
London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.
Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.
Use of flexbox ensures that elements behave predictably when the page layout
must accommodate different screen sizes and different display devices.
Disadvantages: Does not work in IE10 and earlier.
Learn more about flexbox in our
CSS Flexbox chapter.
Flexbox Example
City Gallery
London
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
Notice that in the example above, the image can be scaled up to be larger than its original size.
A better solution, in many cases, will be to use the max-width property instead.
Using the max-width Property
If the max-width property is set to 100%, the image will scale down if it has to, but never scale up to be larger than its original size:
In addition to resize text and images, it is also common to use media queries
in responsive web pages.
With media queries you can define completely different styles for different browser
sizes.
Example: resize the browser window to see that the three div elements below will display
horizontally on large screens and stacked vertically on small screens:
Left Menu
Main Content
Right Content
Example
<style> .left, .right { float:left;
width:20%; /*The width is 20%, by default*/ }
.main { float:left; width:60%; /*The width is 60%, by default*/ }
/*Use a media query to
add a breakpoint at 800px:*/ @media (max-width:800px) { .left,
.main, .right {
width:100%; /*The width is 100%, when the viewport is 800px or smaller*/
} } </style>
<div
class="w3-container w3-green"> <h1>W3Schools Demo</h1>
<p>Resize this responsive page!</p> </div>
<div
class="w3-row-padding"> <div class="w3-third"> <h2>London</h2> <p>London is the capital city of England.</p> <p>It is the most populous city in the United Kingdom, with a
metropolitan area of over 13 million inhabitants.</p> </div>
<div
class="w3-third"> <h2>Paris</h2> <p>Paris is
the capital of France.</p> <p>The Paris area is one of the largest
population centers in Europe, with more than 12 million
inhabitants.</p> </div>
<div class="w3-third">
<h2>Tokyo</h2> <p>Tokyo is the capital of Japan.</p> <p>It
is the center of the Greater Tokyo Area, and the most populous
metropolitan area in the world.</p> </div> </div>
Reserved characters in HTML must be replaced with character entities.
Characters that are not present on your keyboard can also be replaced by entities.
HTML Entities
Some characters are reserved in HTML.
If you use the less than (<) or greater than (>) signs in your text, the browser might mix them with tags.
Character entities are used to display reserved characters in HTML.
A character entity looks like this:
&entity_name;
OR
&#entity_number;
To display a less than sign (<) we must write: < or <
Advantage of using an entity name: An entity name is easy to remember. Disadvantage of using an entity name: Browsers may not support all entity names, but the support for numbers is good.
Non-breaking Space
A common character entity used in HTML is the non-breaking space:
A non-breaking space is a space that will not break into a new line.
Two words
separated by a non-breaking space will stick together (not break into a new
line). This
is handy when breaking the words might be disruptive.
Examples:
§ 10
10 km/h
10 PM
Another common use of the non-breaking space is to prevent that browsers truncate spaces in HTML pages.
If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text,
you can use the character entity.
The non-breaking hyphen (‑) lets you
use a hyphen character (‑) that won't break.
A diacritical mark is a "glyph" added to a letter.
Some diacritical marks, like grave ( ̀) and acute ( ́) are called accents.
Diacritical marks can appear both above and below a letter, inside a letter,
and between two letters.
Diacritical marks can be used in combination with alphanumeric characters, to produce a character that is not present in
the character set (encoding) used in the page.
Here are some examples:
Mark
Character
Construct
Result
̀
a
à
à
́
a
á
á
̂
a
â
â
̃
a
ã
ã
̀
O
Ò
Ò
́
O
Ó
Ó
̂
O
Ô
Ô
̃
O
Õ
Õ
You will see more HTML symbols in the next chapter of this tutorial.
HTML Symbols
HTML Symbol Entities
HTML entities were described in the previous chapter.
Many mathematical, technical, and currency symbols,
are not present on a normal keyboard.
To add such symbols to an HTML page, you can use an HTML entity name.
If no entity name exists, you can use an entity number, a decimal, or hexadecimal reference.
Example
<p>I will display €</p>
<p>I will display €</p>
<p>I will display €</p>
Will display as:
I will display €
I will display €
I will display €
To display an HTML page correctly, a web browser must know
which character set (character encoding) to use.
What is Character Encoding?
ASCII was the first character encoding standard (also called character
set). ASCII defined 128 different alphanumeric characters that could be used on the internet: numbers (0-9), English letters (A-Z), and some special
characters like ! $ + - ( ) @ < > .
ANSI (Windows-1252) was the original Windows character set, with support for 256 different
character codes.
ISO-8859-1 was the default character set for HTML 4. This character set
also supported 256 different character codes.
Because ANSI and ISO-8859-1 were so limited, HTML 4 also supported UTF-8.
UTF-8 (Unicode) covers almost all of the characters and symbols in the world.
The default character encoding for HTML5 is UTF-8.
The HTML charset Attribute
To display an HTML page correctly, a web browser must know the character set used in the page.
scheme - defines the type of Internet service (most common is http or https)
prefix - defines a domain prefix (default for http is www)
domain - defines the Internet domain name (like w3schools.com)
port - defines the port number at the host (default for http is 80)
path - defines a path at the server (If omitted: the root directory of the site)
filename - defines the name of a document or resource
Common URL Schemes
The table below lists some common schemes:
Scheme
Short for
Used for
http
HyperText Transfer Protocol
Common web pages. Not encrypted
https
Secure HyperText Transfer Protocol
Secure web pages. Encrypted
ftp
File Transfer Protocol
Downloading or uploading files
file
A file on your computer
URL Encoding
URLs can only be sent over the Internet using the
ASCII character-set. If a URL contains characters outside the ASCII set, the URL has to be
converted.
URL encoding converts non-ASCII characters into a format that can be transmitted over
the Internet.
URL encoding replaces non-ASCII characters with a "%" followed by
hexadecimal digits.
URLs cannot contain spaces. URL encoding normally replaces a space with a
plus (+)
sign, or %20.
Try It Yourself
If you click "Submit", the browser will URL encode the input
before it is sent to the server.
A page at the server will display the received
input.
Try some other input and click Submit again.
ASCII Encoding Examples
Your browser will encode input, according to
the character-set used in your page.
XHTML stands for EXtensible HyperText
Markup Language
XHTML is almost identical to HTML
XHTML is stricter than HTML
XHTML is HTML defined as an XML application
XHTML is supported by all major browsers
Why XHTML?
Many pages on the internet contain "bad" HTML.
This HTML code works fine in most browsers (even if it does not follow the HTML rules):
<html>
<head>
<title>This is bad HTML</title>
<body>
<h1>Bad HTML
<p>This is a paragraph
</body>
Today's market consists of different browser technologies. Some browsers run on computers, and some browsers run on mobile phones or other
small devices. Smaller devices often lack the resources or power to interpret "bad" markup.
XML is a markup language where documents must be marked up correctly (be "well-formed").
If you want to study XML, please read our XML tutorial.
By combining the strengths of HTML and XML, XHTML was developed.
XHTML is HTML redesigned as XML.
The Most Important Differences from HTML:
Document Structure
XHTML DOCTYPE is mandatory
The xmlns attribute in <html> is mandatory
<html>, <head>, <title>, and <body> are mandatory
XHTML Elements
XHTML elements must be properly nested
XHTML elements must always be closed
XHTML elements must be in lowercase
XHTML documents must have one root element
XHTML Attributes
Attribute names must be in lower case
Attribute values must be quoted
Attribute minimization is forbidden
<!DOCTYPE ....> Is Mandatory
An XHTML document must have an XHTML DOCTYPE declaration.
A complete list of all the XHTML Doctypes is found in our HTML Tags Reference.
The <html>, <head>, <title>, and <body> elements must also be present, and the xmlns attribute in <html>
must specify the xml namespace for the document.
This example shows an XHTML document with a minimum of required tags:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title of document</title>
</head>
<body> some content
</body>
</html>
XHTML Elements Must Be Properly Nested
In HTML, some elements can be improperly nested within each other, like this:
<b><i>This text is bold and italic</b></i>
In XHTML, all elements must be properly nested within each other, like this:
<b><i>This text is bold and italic</i></b>
XHTML Elements Must Always Be Closed
This is wrong:
<p>This is a paragraph
<p>This is another paragraph
This is correct:
<p>This is a paragraph</p>
<p>This is another paragraph</p>
Empty Elements Must Also Be Closed
This is wrong:
A break: <br>
A horizontal rule: <hr>
An image: <img src="happy.gif" alt="Happy face">
This is correct:
A break: <br />
A horizontal rule: <hr />
An image: <img src="happy.gif" alt="Happy face" />
This is how the HTML code above will be displayed in a browser:
The Action Attribute
The action attribute defines the action to be performed when the form is submitted.
Normally, the form data is sent to a web page on the server when the user clicks on the submit button.
In the example above, the form data is sent to a page on the server called "/action_page.php".
This page contains a server-side script that handles the form data:
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page.
The Target Attribute
The target attribute specifies if the submitted result will open in a new
browser tab, a frame, or in the current window.
The default value is "_self" which means the form will be submitted in the current window.
To make the form result open in a new browser tab, use the value "_blank":
The default method when submitting form data is GET.
However, when GET is used, the submitted form data will be visible in the page address
field:
/action_page.php?firstname=Mickey&lastname=Mouse
Notes on GET:
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user want to bookmark the result
GET is better for non-secure data, like query strings in Google
When to Use POST?
Always use POST if the form data contains sensitive or personal information.
The POST method does not display the submitted form data in the page address field.
Notes on POST:
POST has no size limitations, and can be used to send large amounts of data.
Form submissions with POST cannot be bookmarked
The Name Attribute
Each input field must have a name attribute to be submitted.
If the name attribute is omitted, the data of that input field will not be sent at all.
This example will only submit the "Last name" input field:
Example
<form action="/action_page.php"> First name:<br> <input type="text"
value="Mickey"><br> Last name:<br> <input
type="text" name="lastname" value="Mouse"><br><br> <input type="submit" value="Submit"> </form>
<form> Enter a date before 1980-01-01: <input type="date" name="bday" max="1979-12-31"><br> Enter a date after 2000-01-01: <input type="date" name="bday" min="2000-01-02"><br> </form>
The <input type="range"> defines a control for entering a number whose exact value is not important (like a slider control). Default
range is 0 to 100. However, you can set restrictions on what
numbers are accepted with the min, max, and step attributes:
With a maxlength attribute, the input field will not accept more than the
allowed number of characters.
The maxlength attribute does not provide any feedback. If you want to alert the user,
you must write JavaScript code.
Note: Input restrictions are not foolproof, and JavaScript provides many ways to
add illegal input. To safely restrict input, it must be checked by the receiver
(the server) as well!
HTML5 Attributes
HTML5 added the following attributes for <input>:
autocomplete
autofocus
form
formaction
formenctype
formmethod
formnovalidate
formtarget
height and width
list
min and max
multiple
pattern (regexp)
placeholder
required
step
and the following attributes for <form>:
autocomplete
novalidate
The autocomplete Attribute
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off.
When autocomplete is on, the browser automatically completes the input values based on values that the user has entered before.
Tip: It is possible to have autocomplete "on" for the form, and "off" for specific input fields, or vice versa.
The autocomplete attribute works with <form> and the
following <input> types: text, search, url, tel, email, password, datepickers, range, and color.
Example
An HTML form with autocomplete on (and off for one input field):
<form action="/action_page.php" autocomplete="on">
First name:<input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email" autocomplete="off"><br>
<input type="submit">
</form>
The formtarget attribute specifies a name or a keyword that indicates where
to display the response that is received after submitting the form.
The formtarget attribute overrides the target attribute of the <form> element.
The formtarget attribute can be used with type="submit" and type="image".
Example
A form with two submit buttons, with different target windows:
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit as normal">
<input type="submit" formtarget="_blank"
value="Submit to a new window">
</form>
The character encoding (charset) declaration is also very simple:
<meta charset="UTF-8">
HTML5 Example:
<!DOCTYPE html>
<html>
<head> <meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body> Content of the document......
</body>
</html>
The default character encoding in HTML5 is UTF-8.
New HTML5 Elements
The most interesting new HTML5 elements are:
New semantic
elements
like <header>, <footer>,
<article>, and <section>.
New attributes of form elements like number,
date, time, calendar, and range.
New graphic elements: <svg>
and <canvas>.
New multimedia elements: <audio> and
<video>.
In the next chapter, HTML5 Support, you will learn how
to "teach" older browsers to handle "unknown" (new) HTML elements.
New HTML5 API's (Application Programming Interfaces)
The most interesting new API's in HTML5 are:
HTML Geolocation
HTML Drag and Drop
HTML Local Storage
HTML Application Cache
HTML Web Workers
HTML SSE
Tip: HTML Local storage is a powerful replacement for cookies.
Removed Elements in HTML5
The following HTML4 elements have been removed in HTML5:
Removed Element
Use Instead
<acronym>
<abbr>
<applet>
<object>
<basefont>
CSS
<big>
CSS
<center>
CSS
<dir>
<ul>
<font>
CSS
<frame>
<frameset>
<noframes>
<strike>
CSS, <s>, or <del>
<tt>
CSS
In the chapter HTML5 Migration, you will learn how to
easily migrate from HTML4 to HTML5.
HTML History
Since the early days of the World Wide Web, there have been many versions of HTML:
Year
Version
1989
Tim Berners-Lee invented www
1991
Tim Berners-Lee invented HTML
1993
Dave Raggett drafted HTML+
1995
HTML Working Group defined HTML 2.0
1997
W3C Recommendation: HTML 3.2
1999
W3C Recommendation: HTML 4.01
2000
W3C Recommendation: XHTML 1.0
2008
WHATWG HTML5 First Public Draft
2012
WHATWG HTML5 Living Standard
2014
W3C Recommendation: HTML5
2016
W3C Candidate Recommendation: HTML 5.1
From 1991 to 1999, HTML developed from version 1 to version 4.
In year 2000, the World Wide Web Consortium (W3C) recommended XHTML 1.0. The XHTML syntax was strict, and the developers were forced to write valid and
"well-formed" code.
In 2004, W3C's decided to close down the
development of HTML, in favor of XHTML.
In 2004, WHATWG (Web Hypertext Application Technology Working Group) was formed.
The WHATWG wanted to develop HTML, consistent with how the web was used, while
being backward compatible with older versions of HTML.
In 2004 - 2006, the WHATWG gained support by the major
browser vendors.
In 2006, W3C announced that they would support WHATWG.
In 2008, the first HTML5 public draft was released.
In 2012, WHATWG and W3C decided on a separation:
WHATWG wanted to develop HTML as a "Living Standard". A living standard is always updated and improved.
New features can be added, but old functionality cannot be removed.
The JavaScript statement document.createElement("myHero") is needed to create a new element in IE 9, and earlier.
Problem With Internet Explorer 8
You could use the solution described above for all new HTML5 elements.
However, IE8 (and earlier) does not allow styling of unknown elements!
Thankfully, Sjoerd Visscher created the HTML5Shiv! The HTML5Shiv is a JavaScript workaround to enable styling of HTML5 elements
in versions of Internet Explorer prior to version 9.
You will require the HTML5shiv to provide compatibility for IE Browsers older than IE 9.
Syntax For HTML5Shiv
The HTML5Shiv is placed within the <head> tag.
The HTML5Shiv is a javascript file that is referenced in a <script> tag.
You should use the HTML5Shiv when you are using the new HTML5 elements such
as: <article>, <section>, <aside>, <nav>, <footer>.
<article> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </article>
<article> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </article>
<article> <h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p> </article>
The <article> element specifies independent, self-contained content.
An article should make sense on its own, and it should be possible to
read it independently from the rest of the web site.
Examples of where an <article> element can be used:
Forum post
Blog post
Newspaper article
Example
<article>
<h1>What Does WWF Do?</h1>
<p>WWF's mission is to stop the degradation of our planet's natural environment, and build a future in which humans live in harmony with nature.</p>
</article>
The <article>
element specifies independent, self-contained content.
The <section> element defines section in a document.
Can we use the definitions to decide how to nest those elements? No, we cannot!
So, on the Internet, you will find HTML pages with <section> elements
containing <article> elements, and <article> elements containing <sections> elements.
You will also find pages with <section> elements containing <section>
elements, and <article> elements containing <article> elements.
Example for a newspaper: The sport articles in the sport section,
may have a technical section in each article.
HTML5 <header> Element
The <header> element specifies a header for a document or section.
The <header> element should be used as a container for introductory content.
You can have several <header> elements in one document.
The following example defines a header for an article:
Example
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural environment, and build a future in which humans live in harmony with nature.</p>
</article>
The <img> element defines the image, the <figcaption>
element defines the caption.
Why Semantic Elements?
With HTML4, developers used their own id/class names to style
elements: header, top, bottom, footer, menu, navigation, main, container, content,
article, sidebar, topnav, etc.
This made it impossible for search engines to identify the correct web page
content.
With the new HTML5 elements (<header> <footer> <nav> <section> <article>), this
will become easier.
According to the W3C, a Semantic Web: "Allows data to be shared and reused across applications,
enterprises, and communities."
Semantic Elements in HTML5
Below is an alphabetical list of the new semantic elements in HTML5.
<div id="content">
<h2>News Section</h2> <div class="article"> <h2>News Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in porta lorem. Morbi condimentum est nibh, et consectetur tortor feugiat at.</p> </div> <div class="article"> <h2>News
Article</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in porta lorem. Morbi condimentum est nibh, et consectetur tortor feugiat at.</p> </div> </div>
<div id="footer">
<p>&copy; 2016 Monday Times. All rights reserved.</p> </div>
The new HTML5 semantic elements are supported in all modern browsers. In
addition, you can "teach" older browsers how to handle "unknown elements".
However, IE8 and earlier, does not allow styling of unknown elements. So, the
HTML5Shiv is a JavaScript workaround to enable styling of HTML5 elements in
versions of Internet Explorer prior to version 9.
<section> <h2>News Section</h2> <article> <h2>News Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in porta lorem. Morbi condimentum est nibh, et consectetur tortor feugiat at.</p> </article> <article> <h2>News Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in porta lorem. Morbi condimentum est nibh, et consectetur tortor feugiat at.</p> </article> </section>
The Difference Between <article> <section> and <div>
There is a confusing (lack of) difference in the HTML5
standard, between <article> <section> and <div>.
In the HTML5 standard, the <section> element is defined as a block of related
elements.
The <article>
element is defined as a complete, self-contained block of related elements.
The <div> element is defined as a block of children elements.
How to interpret that?
In the example above, we
have used <section> as a container for related <articles>.
But, we could have used <article> as a container for articles as well.
Here are some different examples:
<article> in <article>:
<article>
<h2>Famous Cities</h2>
<article> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </article>
<article> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </article>
<article> <h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p> </article>
<div class="city"> <h2>London</h2>
<p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </div>
<div class="city"> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </div>
<div class="city"> <h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p> </div>
<div class="city">
<h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </div>
<div class="city">
<h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </div>
<div class="city"> <h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p> </div>
</section>
<section> <h2>Famous Countries</h2>
<div class="country"> <h2>England</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </div>
<div class="country"> <h2>France</h2> <p>Paris is the capital and most populous city of France.</p> </div>
<div class="country">
<h2>Japan</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </div> </section>
Web developers are often uncertain about the coding style and syntax to use in HTML.
Between 2000 and 2010, many web developers converted from HTML to XHTML.
With XHTML, developers were forced to write valid and "well-formed" code.
HTML5 is a bit more sloppy when it comes to code validation.
Be Smart and Future Proof
A consistent use of style, makes it easier for others to understand your HTML.
In the future, programs like XML readers, may want to read your HTML.
Using a well-formed-"close to XHTML" syntax, can be smart.
Always keep your code tidy, clean, and well-formed.
Use Correct Document Type
Always declare the document type as the first line in your document:
<!DOCTYPE html>
If you want consistency with lower case tags, you can use:
<!doctype html>
Use Lower Case Element Names
HTML5 allows mixing uppercase and lowercase letters in element names.
We recommend using lowercase element names because:
Mixing uppercase and lowercase names is bad
Developers normally use lowercase names (as in XHTML)
Lowercase look cleaner
Lowercase are easier to write
Bad:
<SECTION> <p>This is a paragraph.</p> </SECTION>
Very Bad:
<Section> <p>This is a paragraph.</p> </SECTION>
Good:
<section> <p>This is a paragraph.</p> </section>
Close All HTML Elements
In HTML5, you don't have to close all elements (for example the <p> element).
We recommend closing all HTML elements.
Bad:
<section> <p>This is a paragraph. <p>This is a paragraph.
</section>
Good:
<section> <p>This is a paragraph.</p> <p>This is a paragraph.</p>
</section>
Close Empty HTML Elements
In HTML5, it is optional to close empty elements.
Allowed:
<meta
charset="utf-8">
Also Allowed:
<meta charset="utf-8" />
However, the closing slash (/) is REQUIRED in XHTML and XML.
If you expect XML software to access your page, it is a good idea to keep the
closing slash!
Use Lower Case Attribute Names
HTML5 allows mixing uppercase and lowercase letters in attribute names.
We recommend using lowercase attribute names because:
Mixing uppercase and lowercase names is bad
Developers normally use lowercase names (as in XHTML)
Lowercase look cleaner
Lowercase are easier to write
Bad:
<div CLASS="menu">
Good:
<div
class="menu">
Quote Attribute Values
HTML5 allows attribute values without quotes.
We recommend quoting attribute values because:
Mixing uppercase and lowercase values is bad
Quoted values are easier to read
You MUST use quotes if the value contains spaces
Very bad:
This will not work, because the value contains spaces:
<table class=table striped>
Bad:
<table class=striped>
Good:
<table
class="striped">
Image Attributes
Always add the "alt" attribute to images. This attribute is important when the image
for some reason cannot be displayed. Also, always define image width and height. It reduces flickering because the browser can reserve space for
the image before loading.
HTML5 allows spaces around equal signs. But space-less is easier to read, and
groups entities better together.
Bad:
<link
rel = "stylesheet" href = "styles.css">
Good:
<link rel="stylesheet" href="styles.css">
Avoid Long Code Lines
When using an HTML editor, it is inconvenient to scroll right and left to read the HTML code.
Try to avoid code lines longer than 80 characters.
Blank Lines and Indentation
Do not add blank lines without a reason.
For readability, add blank lines to separate large or logical code blocks.
For readability, add two spaces of indentation. Do not use the tab key.
Do not use unnecessary blank lines and indentation. It is not necessary to indent every
element:
Unnecessary:
<body>
<h1>Famous Cities</h1>
<h2>Tokyo</h2>
<p> Tokyo is the capital of Japan, the
center of the Greater Tokyo Area, and the most
populous metropolitan area in the world. It is the
seat of the Japanese government and the Imperial Palace,
and the home of the Japanese Imperial Family. </p>
</body>
Better:
<body>
<h1>Famous Cities</h1>
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the
center of the Greater Tokyo Area, and the most
populous metropolitan area in the world. It is the
seat of the Japanese government and the Imperial Palace,
and the home of the Japanese Imperial Family.</p>
</body>
Table Example:
<table> <tr> <th>Name</th>
<th>Description</th>
</tr> <tr> <td>A</td>
<td>Description of A</td>
</tr> <tr> <td>B</td>
<td>Description of B</td> </tr> </table>
Omitting tags is unfamiliar to web developers. It needs time to be established as a
guideline.
Meta Data
The <title> element is required in HTML5. Make the title as meaningful as possible:
<title>HTML5
Syntax and Coding Style</title>
To ensure proper interpretation, and correct search engine indexing, both the language and
the character encoding should be defined as early as possible in a document:
Some web servers (Apache, Unix) are case sensitive about file names: "london.jpg" cannot be accessed as
"London.jpg".
Other web servers (Microsoft, IIS) are not case sensitive: "london.jpg" can be accessed as
"London.jpg" or "london.jpg".
If you use a mix of upper and lower case, you have to be extremely consistent.
If you move from a case insensitive to a case sensitive server, even small
errors will break your web!
To avoid these problems, always use lower case file names.
File Extensions
HTML files should have a .html or .htm extension.
CSS files should have a .css extension.
JavaScript files should have a .js extension.
Differences Between .htm and .html
There is no difference between the .htm and .html extensions. Both will be
treated as HTML by any web browser or web server.
The differences are cultural:
.htm "smells" of early DOS systems where the system limited the extensions to
3 characters.
.html "smells" of Unix operating systems that did not have this limitation.
Technical Differences
When a URL does not specify a filename (like https://www.w3schools.com/css/),
the server returns a default filename. Common default filenames are index.html,
index.htm, default.html, and default.htm.
If your server is configured only with "index.html" as default filename, your
file must be named "index.html", not "index.htm."
However, servers can be configured with more than one default filename, and
normally you can set up as many default filenames as needed.
Anyway, the full extension for HTML files is .html, and there's no reason it
should not be used.
HTML5 Canvas
The HTML <canvas> element is used to draw graphics on a web page.
The graphic to the left is created with <canvas>. It shows four
elements: a red rectangle, a gradient rectangle,
a multicolor rectangle, and a multicolor text.
What is HTML Canvas?
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use
JavaScript to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Browser Support
The numbers in the table specify the first browser version that fully supports the
<canvas> element.
Element
<canvas>
4.0
9.0
2.0
3.1
9.0
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.
Note: Always specify an id attribute (to be referred to in a script),
and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.
SVG is a language for describing 2D graphics in XML.
Canvas draws 2D graphics, on the fly (with a JavaScript).
SVG is XML based, which means that every element is available within the SVG
DOM. You can attach JavaScript event handlers for an element.
In SVG, each drawn shape is remembered as an object. If attributes of an SVG
object are changed, the browser can automatically re-render the shape.
Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its
position should be changed, the entire scene needs to be redrawn, including any
objects that might have been covered by the graphic.
Comparison of Canvas and SVG
The table below shows some important differences between Canvas and SVG:
Canvas
SVG
Resolution dependent
No support for event handlers
Poor text rendering capabilities
You can save the resulting image as .png or .jpg
Well suited for graphic-intensive games
Resolution independent
Support for event handlers
Best suited for applications with large rendering areas (Google Maps)
Slow rendering if complex (anything that uses the DOM a lot will be slow)
Not suited for game applications
To learn more about SVG, please read our SVG Tutorial.
HTML Google Maps
Google Maps allows you to display maps on your web page:
A Basic Web Page
To demonstrate how to add a Google Map to a web page, we will use a basic
HTML page:
This example defines a Google Map centered in London, England:
Example
function myMap() {
var mapOptions = { center: new google.maps.LatLng(51.5, -0.12), zoom:
10, mapTypeId: google.maps.MapTypeId.HYBRID } var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
The mapOptions variable defines the properties for the map.
The center property specifies where to center the map (using
latitude and longitude coordinates).
The zoom property specifies the zoom level for the map (try to experiment with the
zoom level).
The mapTypeId property specifies the map type to display.
The following map types are supported: ROADMAP, SATELLITE, HYBRID, and TERRAIN.
The line: var map=new google.maps.Map(document.getElementById("map"),
mapOptions); creates a new map inside the <div> element with id="map",
using the parameters that are passed (mapOptions).
Add the Google Maps API
Finally, show the map on the page!
The functionality of the map is provided by a JavaScript library located at
Google. Add a script to refer to the Google Maps API with a callback to the
myMap function:
Multimedia on the web is sound, music, videos, movies, and animations.
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see.
Examples: Images, music,
sound, videos, records, films, animations, and more.
Web pages often contain multimedia elements of different types and formats.
In this chapter you will learn about the different multimedia formats.
Browser Support
The first web browsers had support for text only, limited to a single font in a single color.
Later came browsers with support for colors and fonts, and images!
Audio, video, and animation have been handled differently
by the major browsers. Different formats have been supported, and some formats require
extra helper programs (plug-ins) to work.
Hopefully this will become history. HTML5 multimedia promises an easier
future for multimedia.
Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.
The most common way to discover the type of a file, is to look at the file
extension.
Multimedia files have formats and different extensions
like: .swf, .wav, .mp3, .mp4, .mpg, .wmv, and .avi.
Common Video Formats
MP4 is the new and upcoming format for internet video.
MP4 is recommended by YouTube.
MP4 is supported by Flash Players.
MP4 is supported by HTML5.
Format
File
Description
MPEG
.mpg .mpeg
MPEG.
Developed by
the Moving Pictures Expert Group. The first popular video format on
the web. Used to be supported by all browsers, but it is
not supported in HTML5 (See MP4).
AVI
.avi
AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in video cameras and TV
hardware. Plays well on Windows computers, but not in web browsers.
WMV
.wmv
WMV (Windows Media Video). Developed by Microsoft. Commonly used in
video cameras and TV hardware. Plays well on Windows computers, but not in
web browsers.
QuickTime
.mov
QuickTime. Developed by Apple. Commonly used in video cameras and TV hardware.
Plays well on Apple computers, but not in web browsers. (See MP4)
RealVideo
.rm .ram
RealVideo. Developed by Real Media to allow video streaming with low
bandwidths. It is still used for online video and Internet TV, but does not play
in web browsers.
Flash
.swf .flv
Flash. Developed by Macromedia. Often requires an extra component (plug-in) to play in
web browsers.
Ogg
.ogg
Theora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.
WebM
.webm
WebM.
Developed by the web giants, Mozilla, Opera, Adobe, and Google. Supported by
HTML5.
MPEG-4 or MP4
.mp4
MP4.
Developed by
the Moving Pictures Expert Group. Based on QuickTime. Commonly used in newer video cameras and TV hardware.
Supported by all HTML5 browsers. Recommended by YouTube.
Only MP4, WebM, and Ogg video are supported by the HTML5 standard.
Audio Formats
MP3 is the newest format for compressed recorded music. The
term MP3 has become synonymous with digital music.
If your website is about recorded music, MP3 is the choice.
Format
File
Description
MIDI
.mid .midi
MIDI (Musical Instrument Digital Interface).
Main format for all electronic
music devices like synthesizers and PC sound cards. MIDI files do not contain sound, but digital notes that can be played by electronics.
Plays well on all computers and music hardware, but not in web browsers.
RealAudio
.rm .ram
RealAudio.
Developed by Real Media
to allow streaming of audio with low
bandwidths. Does not play in web browsers.
WMA
.wma
WMA (Windows Media Audio). Developed by Microsoft. Commonly used in music
players. Plays well on Windows computers, but not in
web browsers.
AAC
.aac
AAC (Advanced Audio Coding).
Developed by Apple as the default format for
iTunes. Plays well on Apple computers, but not in web browsers.
WAV
.wav
WAV.
Developed by IBM and Microsoft. Plays well on Windows, Macintosh, and Linux operating systems.
Supported by
HTML5.
Ogg
.ogg
Ogg.
Developed by the Xiph.Org Foundation. Supported by HTML5.
MP3
.mp3
MP3 files are actually the sound part of MPEG files.
MP3 is the most popular format for music players. Combines good
compression (small files) with high quality. Supported by all browsers.
MP4
.mp4
MP4
is a video format, but can also be used for audio. MP4
video is the upcoming video format on the internet. This leads to
automatic support for MP4 audio by all browsers.
Only MP3, WAV, and Ogg audio are supported by the HTML5 standard.
Before HTML5, a video could only be played in a browser with a plug-in (like flash).
The HTML5 <video> element specifies a standard way to embed a video in a web page.
Browser Support
The numbers in the table specify the first browser version that fully supports the
<video> element.
Element
<video>
4.0
9.0
3.5
4.0
10.5
The HTML <video> Element
To show a video in HTML, use the <video> element:
Example
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
The controls attribute adds video controls, like play, pause, and volume.
It is a good idea to always include width and height attributes. If height and width are not set, the page
might flicker while the video loads.
The <source> element allows you to specify alternative video
files which the browser may choose from. The browser will use the first recognized format.
The text between the <video> and </video> tags will only be displayed
in browsers that do not
support the <video> element.
HTML <video> Autoplay
To start a video automatically use the autoplay attribute:
Example
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Before HTML5, audio
files could only be played in a browser with a plug-in (like flash).
The HTML5 <audio> element specifies a standard way to embed audio
in a web page.
Browser Support
The numbers in the table specify the first browser version that fully supports the
<audio> element.
Element
<audio>
4.0
9.0
3.5
4.0
10.5
The HTML <audio> Element
To play an audio file in HTML, use the <audio> element:
Example
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio
files which the browser may choose from. The browser will use the first recognized format.
The text between the <audio> and </audio> tags will only be displayed
in browsers that do not
support the <audio> element.
HTML Audio - Browser Support
In HTML5, there are 3 supported audio formats: MP3, Wav, and Ogg.
The browser support for the different formats is:
Browser
MP3
Wav
Ogg
Internet Explorer
YES
NO
NO
Chrome
YES
YES
YES
Firefox
YES
YES
YES
Safari
YES
YES
NO
Opera
YES
YES
YES
HTML Audio - Media Types
File Format
Media Type
MP3
audio/mpeg
Ogg
audio/ogg
Wav
audio/wav
HTML Audio - Methods, Properties, and Events
HTML5 defines DOM methods, properties, and events for the <audio> element.
This allows you to load, play, and pause audios, as well as set duration and volume.
There are also DOM events that can notify you when an audio begins to play, is paused, etc.
You can have your video start playing automatically when a user visits that
page by adding a simple parameter to your YouTube URL.
Note: Take careful consideration when deciding to autoplay your videos.
Automatically starting a video can annoy your visitor and end up causing more harm than good.
Value 0 (default): The video will not play automatically when the player loads.
Value 1: The video will play automatically when the player loads.
The HTML Geolocation API is used to locate a user's position.
Locate the User's Position
The HTML Geolocation API is used to get the geographical position of a user.
Since this can compromise privacy, the position is not available unless the user approves it.
Note:Geolocation is most accurate for devices with GPS, like iPhone.
Browser Support
The numbers in the table specify the first browser version that fully supports
Geolocation.
API
Geolocation
5.0 - 49.0 (http) 50.0 (https)
9.0
3.5
5.0
16.0
Note: As of Chrome 50, the Geolocation API will only work on secure contexts such
as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the
requests to get the users location will no longer function.
Using HTML Geolocation
The getCurrentPosition() method is used to return the user's position.
The example below returns the latitude and longitude of the user's position:
Example
<script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } }
function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
} </script>
If supported, run the getCurrentPosition() method. If not, display a message to the user
If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)
The showPosition() function outputs the Latitude and Longitude
The example above is a very basic Geolocation script, with no error handling.
Handling Errors and Rejections
The second parameter of the getCurrentPosition() method is used to handle
errors. It specifies a function to run if it fails to get the user's location:
Example
function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML = "Location information is unavailable." break; case error.TIMEOUT: x.innerHTML = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML = "An unknown error occurred." break; }
}
Google Map Script
How to show an interactive Google Map with a marker, zoom and drag options.
Location-specific Information
This page has demonstrated how to show a user's position on a map.
Geolocation is also very useful for location-specific information, like:
Up-to-date local information
Showing Points-of-interest near the user
Turn-by-turn navigation (GPS)
The getCurrentPosition() Method - Return Data
The getCurrentPosition() method returns an object on success. The latitude,
longitude and accuracy properties are always returned. The other properties are returned
if available:
Property
Returns
coords.latitude
The latitude as a decimal number (always returned)
coords.longitude
The longitude as a decimal number (always returned)
coords.accuracy
The accuracy of position (always returned)
coords.altitude
The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy
The altitude accuracy of position (returned if available)
coords.heading
The heading as degrees clockwise from North (returned if available)
coords.speed
The speed in meters per second (returned if available)
timestamp
The date/time of the response (returned if available)
Geolocation Object - Other interesting Methods
The Geolocation object also has other interesting methods:
watchPosition() - Returns the current position of the user and continues to
return updated position as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.
The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):
Example
<script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } }
function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
} </script>
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.
In HTML5, drag and drop is part of the standard: Any element can be draggable.
Browser Support
The numbers in the table specify the first browser version that fully supports Drag and Drop.
API
Drag and Drop
4.0
9.0
3.5
6.0
12.0
HTML Drag and Drop Example
The example below is a simple drag and drop example:
Example
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
With web storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in
every server request. Web storage is more secure, and large amounts of data
can be stored locally, without affecting website performance.
Unlike cookies,
the storage limit is far larger (at least 5MB) and information is never
transferred to the server.
Web storage is per origin (per domain and protocol). All pages, from one
origin, can store and access the same data.
Browser Support
The numbers in the table specify the first browser version that fully supports
Web Storage.
API
Web Storage
4.0
8.0
3.5
4.0
11.5
HTML Web Storage Objects
HTML web storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
}
else {
// Sorry! No Web Storage support..
}
The localStorage Object
The localStorage object stores the data with no expiration date. The data
will not be deleted when the browser is closed, and will be available the next day, week, or year.
Example
// Store localStorage.setItem("lastname", "Smith"); // Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Create a localStorage name/value pair with name="lastname" and value="Smith"
Retrieve the value of "lastname" and insert it into the element with id="result"
The example above could also be written like this:
// Store localStorage.lastname = "Smith"; // Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
The syntax for removing the "lastname" localStorage item is as follows:
localStorage.removeItem("lastname");
Note: Name/value pairs are always stored as strings.
Remember to convert them to another format when needed!
The following example counts the number of times a user has clicked a button.
In this code the value string is converted to a number to be able to increase the counter:
Example
if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else { localStorage.clickcount = 1; }
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";
The sessionStorage object is equal to the localStorage object, except
that it stores the data for only one session. The data is deleted when the user closes the
specific browser tab.
The following example counts the number of times a user has clicked a button, in the current session:
Example
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1; }
else { sessionStorage.clickcount = 1; }
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
A web worker is a JavaScript running in the background, without affecting the performance of the page.
What is a Web Worker?
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.
A web worker is a JavaScript that runs in the background, independently
of other scripts, without affecting the performance of the page. You can continue to do whatever you want:
clicking, selecting things, etc., while the web worker runs in the background.
Browser Support
The numbers in the table specify the first browser version that fully support Web Workers.
API
Web Workers
4.0
10.0
3.5
4.0
11.5
HTML Web Workers Example
The example below creates a simple web worker that count numbers in the background:
Since web workers are in external files, they do not have access to the following JavaScript objects:
The window object
The document object
The parent object
HTML5 Server-Sent Events
Server-Sent Events allow a web page to get updates from a server.
Server-Sent Events - One Way Messaging
A server-sent event is when a web page automatically gets updates from a server.
This was also possible before, but the web page would have to ask if any updates were
available. With server-sent events, the updates come automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.
Browser Support
The numbers in the table specify the first browser version that fully support server-sent events.
API
SSE
6.0
Not supported
6.0
5.0
11.5
Receive Server-Sent Event Notifications
The EventSource object is used to receive server-sent event notifications:
Example
var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; };
The perfect solution for busy professionals who need to balance work, family, and career building.
More than 15 000 certificates already issued!
Document Your Skills
Knowledge is power, especially in the current job market. Documentation of your skills enables you to advance your career, or help you to start a new one.
Get a Certificate
Getting a certificate proves your commitment to upgrade your skills,
gives you the credibility needed for more responsibilities, larger projects, and a higher salary.
Take your exam online, at any time, and from any location
You Have Learned HTML, Now What?
This tutorial has taught you how to use HTML to create your own web site.
HTML is the universal markup language for the Web. HTML lets you format text, add graphics,
create links, input forms, frames and tables, etc., and save it all in a text file that any
browser can read and display.
CSS gives you total control of the layout, without messing up the document content.
To learn more about CSS, please visit our CSS tutorial.
Learn JavaScript
JavaScript makes your website more dynamic. A dynamic website can react to events and allow user interaction.
JavaScript is the most popular scripting language on the internet and it works with all major browsers.
If you want to learn more about JavaScript, please visit our JavaScript tutorial.
Publishing Your Website
To make your website available to the world, you must publish it.
For this, you have two options:
Use an Internet Service Provider
Host your own website
Using an Internet Service Provider
An Internet service provider (ISP) is a company that provides services for
accessing and using the Internet.
Internet services typically provided by ISPs include Internet access,
Internet transit, domain name registration, web hosting, Usenet service, and
colocation.
Using an Internet Service Provider (ISP) is the most common option.
Advantages:
Connection Speed - ISPs have very fast connections to the internet.
Powerful Hardware - ISPs have powerful web servers that can be shared by several clients.
You can also expect an effective load balancing and necessary backup servers
Security and Stability - ISPs are specialists on web hosting. Expect more than 99% up time, the latest software patches, and the best virus protection
Things to Consider:
24-hour support - The ISP should offer 24-hours support. Toll-free phone could also be vital
Daily Backup - The ISP must run a daily backup routine
Traffic Volume - Check the ISP's traffic volume restrictions (do not end up paying a fortune for unexpected
high traffic)
Bandwidth or Content Restrictions - Check the ISP's bandwidth and content restrictions (Is it possible to publish pictures, video, or sound?)
E-mail Capabilities - Make sure the ISP supports the e-mail capabilities you need
Database Access - Make sure the ISP supports the database access you need
Hosting Your Own Website
Hosting your own website, on your own server, is also an option.
Things to Consider:
Hardware Expenses - To run a "real" web site, you must buy powerful
server hardware (a low cost PC will not do the job). You will also
need a permanent (24/7) high-speed connection
Software Expenses - Server-licenses are often higher than client-licenses.
Server-licenses also might have limits on number of users
Labor Expenses - Don't expect low labor expenses. You have to install your own hardware and software.
You also have to deal with bugs and viruses, and keep your server constantly running
W3Schools' Online Certification
The perfect solution for professionals who need to balance work, family, and career building.
Fires when the user pastes some content in an element
Media Events
Events triggered by medias like videos, images and audio (applies to all HTML elements, but is most common in media elements,
like <audio>, <embed>, <img>, <object>, and <video>).
Fires when the user opens or closes the <details> element
HTML Color Names
Color Names Supported by All Browsers
All modern browsers support the following 140 color names (click on a color name, or a hex value, to view the color as the background-color along with different text colors):
The HTML5 <canvas> tag is used to draw graphics, on the fly, via scripting
(usually JavaScript).
However, the <canvas> element has no drawing abilities of its own (it is only
a container for graphics) - you must use a script to actually draw the graphics.
The getContext() method returns an object that provides methods and
properties for drawing on the canvas.
This reference will cover the properties and methods of the getContext("2d")
object, which can be used to draw text, lines, boxes, circles, and more - on the
canvas.
Browser Support
The numbers in the table specify the first browser version that fully supports the element.
Element
<canvas>
4.0
9.0
2.0
3.1
9.0
Internet Explorer 9, Firefox, Opera, Chrome, and Safari support <canvas> and
its properties and methods.
Note: Internet Explorer 8 and earlier versions, do not support the
<canvas> element.
Since URLs often contain characters outside the ASCII set, the URL has to be
converted into a valid ASCII format.
URL encoding replaces unsafe ASCII characters with a "%" followed by two
hexadecimal digits.
URLs cannot contain spaces. URL encoding normally replaces a space with a
plus (+) sign or with %20.
Try It Yourself
If you click the "Submit" button below, the browser will URL encode the input
before it is sent to the server. A page at the server will display the received
input.
Try some other input and click Submit again.
URL Encoding Functions
In JavaScript, PHP, and ASP there are functions that can be used to URL
encode a string.
In JavaScript you can use the encodeURI() function.
PHP has the rawurlencode() function, and ASP has the Server.URLEncode() function.
Click the "URL Encode" button to see how the JavaScript function encodes the
text.
Note: The JavaScript function encodes space as %20.
ASCII Encoding Reference
Your browser will encode input, according to
the character-set used in your page.
The ASCII control characters %00-%1F were originally designed to
control hardware devices.
Control characters have nothing to do inside a URL.
ASCII Character
Description
URL-encoding
NUL
null character
%00
SOH
start of header
%01
STX
start of text
%02
ETX
end of text
%03
EOT
end of transmission
%04
ENQ
enquiry
%05
ACK
acknowledge
%06
BEL
bell (ring)
%07
BS
backspace
%08
HT
horizontal tab
%09
LF
line feed
%0A
VT
vertical tab
%0B
FF
form feed
%0C
CR
carriage return
%0D
SO
shift out
%0E
SI
shift in
%0F
DLE
data link escape
%10
DC1
device control 1
%11
DC2
device control 2
%12
DC3
device control 3
%13
DC4
device control 4
%14
NAK
negative acknowledge
%15
SYN
synchronize
%16
ETB
end transmission block
%17
CAN
cancel
%18
EM
end of medium
%19
SUB
substitute
%1A
ESC
escape
%1B
FS
file separator
%1C
GS
group separator
%1D
RS
record separator
%1E
US
unit separator
%1F
HTML Language Code Reference
ISO Language Codes
The HTML lang attribute can be used to declare the language of a Web page or
a portion of a Web page. This is meant to assist search engines and browsers.
According to the W3C recommendation you should declare the primary language
for each Web page with the lang attribute inside the <html> tag, like this:
<html lang="en">
...
</html>
In XHTML, the language is declared inside the <html> tag as follows:
In HTML and XHTML they can be used in the lang and xml:lang attributes.
See also: next reference for country codes.
Language
ISO Code
Abkhazian
ab
Afar
aa
Afrikaans
af
Akan
ak
Albanian
sq
Amharic
am
Arabic
ar
Aragonese
an
Armenian
hy
Assamese
as
Avaric
av
Avestan
ae
Aymara
ay
Azerbaijani
az
Bambara
bm
Bashkir
ba
Basque
eu
Belarusian
be
Bengali (Bangla)
bn
Bihari
bh
Bislama
bi
Bosnian
bs
Breton
br
Bulgarian
bg
Burmese
my
Catalan
ca
Chamorro
ch
Chechen
ce
Chichewa, Chewa, Nyanja
ny
Chinese
zh
Chinese (Simplified)
zh-Hans
Chinese (Traditional)
zh-Hant
Chuvash
cv
Cornish
kw
Corsican
co
Cree
cr
Croatian
hr
Czech
cs
Danish
da
Divehi, Dhivehi, Maldivian
dv
Dutch
nl
Dzongkha
dz
English
en
Esperanto
eo
Estonian
et
Ewe
ee
Faroese
fo
Fijian
fj
Finnish
fi
French
fr
Fula, Fulah, Pulaar, Pular
ff
Galician
gl
Gaelic (Scottish)
gd
Gaelic (Manx)
gv
Georgian
ka
German
de
Greek
el
Greenlandic
kl
Guarani
gn
Gujarati
gu
Haitian Creole
ht
Hausa
ha
Hebrew
he
Herero
hz
Hindi
hi
Hiri Motu
ho
Hungarian
hu
Icelandic
is
Ido
io
Igbo
ig
Indonesian
id, in
Interlingua
ia
Interlingue
ie
Inuktitut
iu
Inupiak
ik
Irish
ga
Italian
it
Japanese
ja
Javanese
jv
Kalaallisut, Greenlandic
kl
Kannada
kn
Kanuri
kr
Kashmiri
ks
Kazakh
kk
Khmer
km
Kikuyu
ki
Kinyarwanda (Rwanda)
rw
Kirundi
rn
Kyrgyz
ky
Komi
kv
Kongo
kg
Korean
ko
Kurdish
ku
Kwanyama
kj
Lao
lo
Latin
la
Latvian (Lettish)
lv
Limburgish ( Limburger)
li
Lingala
ln
Lithuanian
lt
Luga-Katanga
lu
Luganda, Ganda
lg
Luxembourgish
lb
Manx
gv
Macedonian
mk
Malagasy
mg
Malay
ms
Malayalam
ml
Maltese
mt
Maori
mi
Marathi
mr
Marshallese
mh
Moldavian
mo
Mongolian
mn
Nauru
na
Navajo
nv
Ndonga
ng
Northern Ndebele
nd
Nepali
ne
Norwegian
no
Norwegian bokmål
nb
Norwegian nynorsk
nn
Nuosu
ii
Occitan
oc
Ojibwe
oj
Old Church Slavonic, Old Bulgarian
cu
Oriya
or
Oromo (Afaan Oromo)
om
Ossetian
os
Pāli
pi
Pashto, Pushto
ps
Persian (Farsi)
fa
Polish
pl
Portuguese
pt
Punjabi (Eastern)
pa
Quechua
qu
Romansh
rm
Romanian
ro
Russian
ru
Sami
se
Samoan
sm
Sango
sg
Sanskrit
sa
Serbian
sr
Serbo-Croatian
sh
Sesotho
st
Setswana
tn
Shona
sn
Sichuan Yi
ii
Sindhi
sd
Sinhalese
si
Siswati
ss
Slovak
sk
Slovenian
sl
Somali
so
Southern Ndebele
nr
Spanish
es
Sundanese
su
Swahili (Kiswahili)
sw
Swati
ss
Swedish
sv
Tagalog
tl
Tahitian
ty
Tajik
tg
Tamil
ta
Tatar
tt
Telugu
te
Thai
th
Tibetan
bo
Tigrinya
ti
Tonga
to
Tsonga
ts
Turkish
tr
Turkmen
tk
Twi
tw
Uyghur
ug
Ukrainian
uk
Urdu
ur
Uzbek
uz
Venda
ve
Vietnamese
vi
Volapük
vo
Wallon
wa
Welsh
cy
Wolof
wo
Western Frisian
fy
Xhosa
xh
Yiddish
yi, ji
Yoruba
yo
Zhuang, Chuang
za
Zulu
zu
HTTP Status Messages
When a browser requests a service from a web server, an error might occur.
This is a list of HTTP status messages that might be returned:
1xx: Information
Message:
Description:
100 Continue
The server has received the request headers, and the client should proceed to send the request body
101 Switching Protocols
The requester has asked the server to switch protocols
103 Checkpoint
Used in the resumable requests proposal to resume aborted PUT or POST requests
2xx: Successful
Message:
Description:
200 OK
The request is OK (this is the standard response for successful HTTP requests)
201 Created
The request has been fulfilled, and a new resource is
created
202 Accepted
The request has been accepted for processing, but the processing
has not been completed
203 Non-Authoritative Information
The request has been successfully processed, but is returning information that may be from another source
204 No Content
The request has been successfully processed, but is not returning any content
205 Reset Content
The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view
206 Partial Content
The server is delivering only part of the resource due to a range header sent by the client
3xx: Redirection
Message:
Description:
300 Multiple Choices
A link list. The user can select a link and go to that
location. Maximum five addresses
301 Moved Permanently
The requested page has moved to a new URL
302 Found
The requested page has moved temporarily to a new URL
303 See Other
The requested page can be found under a different URL
304 Not Modified
Indicates the requested page has not been modified since last requested
306 Switch Proxy
No longer used
307 Temporary Redirect
The requested page has moved temporarily to a new URL
308 Resume Incomplete
Used in the resumable requests proposal to resume aborted PUT or POST requests
4xx: Client Error
Message:
Description:
400 Bad Request
The request cannot be fulfilled due to bad syntax
401 Unauthorized
The request was a legal request, but the server is refusing to respond to it. For use when authentication is possible but has failed or not yet been provided
402 Payment Required
Reserved for future use
403 Forbidden
The request was a legal request, but the server is refusing to respond to it
404 Not Found
The requested page could not be found but may be available again in the future
405 Method Not Allowed
A request was made of a page using a request method not supported by that page
406 Not Acceptable
The server can only generate a response that is not
accepted by the client
407 Proxy Authentication Required
The client must first authenticate itself with the proxy
408 Request Timeout
The server timed out waiting for the request
409 Conflict
The request could not be completed because of a conflict
in the request
410 Gone
The requested page is no longer available
411 Length Required
The "Content-Length" is not defined. The server
will not accept the request without it
412 Precondition Failed
The precondition given in the request evaluated to false by
the server
413 Request Entity Too Large
The server will not accept the request, because the request entity is
too large
414 Request-URI Too Long
The server will not accept the request, because the URL is
too long. Occurs when you convert a POST request to a GET request with
a long query information
415 Unsupported Media Type
The server will not accept the request, because the media
type is not supported
416 Requested Range Not Satisfiable
The client has asked for a portion of the file, but the server cannot supply that portion
417 Expectation Failed
The server cannot meet the requirements of the Expect request-header field
5xx: Server Error
Message:
Description:
500 Internal Server Error
A generic error message, given when no more specific message is suitable
501 Not Implemented
The server either does not recognize the request method, or it lacks the ability to fulfill the request
502 Bad Gateway
The server was acting as a gateway or proxy and received an invalid response from the upstream server
503 Service Unavailable
The server is currently unavailable (overloaded or down)
504 Gateway Timeout
The server was acting as a gateway or proxy and did not receive a timely response from the upstream server
505 HTTP Version Not Supported
The server does not support the HTTP protocol version used in the request
511 Network Authentication Required
The client needs to authenticate to gain network access
HTTP Methods: GET vs. POST
The two most used HTTP methods are: GET and POST.
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable
communications between clients and servers.
HTTP works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a
computer that hosts a web site may be the server.
Example: A client (browser) submits an HTTP request to the server; then the server
returns a response to the client. The response contains status information about
the request and may also contain the requested content.
Two HTTP Request Methods: GET and POST
Two commonly used methods for a request-response between a client and server
are: GET and
POST.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource
The GET Method
Note that the query string (name/value pairs) is sent in the URL of
a GET request:
/test/demo_form.php?name1=value1&name2=value2
Some other notes on GET requests:
GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests should be used only to retrieve data
The POST Method
Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:
POST /test/demo_form.php HTTP/1.1
Host: w3schools.com name1=value1&name2=value2
Some other notes on POST requests:
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length
Compare GET vs. POST
The following table compares the two HTTP methods: GET and POST.
GET
POST
BACK button/Reload
Harmless
Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
Bookmarked
Can be bookmarked
Cannot be bookmarked
Cached
Can be cached
Not cached
Encoding type
application/x-www-form-urlencoded
application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
History
Parameters remain in browser history
Parameters are not saved in browser history
Restrictions on data length
Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)
No restrictions
Restrictions on data type
Only ASCII characters allowed
No restrictions. Binary data is also allowed
Security
GET is less secure compared to POST because data sent is part of the URL
Never use GET when sending passwords or other sensitive information!
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
Visibility
Data is visible to everyone in the URL
Data is not displayed in the URL
Other HTTP Request Methods
The following table lists some other HTTP request methods:
Method
Description
HEAD
Same as GET but returns only HTTP headers and no document body
PUT
Uploads a representation of the specified URI
DELETE
Deletes the specified resource
OPTIONS
Returns the HTTP methods that the server supports
CONNECT
Converts the request connection to a transparent TCP/IP tunnel
Pixels to Ems Conversion
The tool below allows you to work out the em sizes from pixels
(or vice versa).
Pixel to Em Converter
Set a default pixel size for body (usually 16px)
Then, convert a pixel value to em, based on the default pixel size
Or, convert an em value to pixels, based on the default pixel size
Set a default pixel size:
px
Convert PX to EM: px
Convert EM to PX: em
Result:
Body Font Size
In the table below, select a body font size in pixels (px) to display a
complete "px to em and percent" conversion table.
Tip: The default font size is usually 16px.
What is the difference between PX, EM and Percent?
Pixel
is a static measurement, while percent and EM are relative
measurements. The size of an EM or percent depends on its parent. If the text
size of body is 16 pixels, then 150% or 1.5 EM will be 24 pixels (1.5 * 16).
Look at CSS Units for more
measurement units.
Keyboard Shortcuts
Save time by using keyboard shortcuts.
Keyboard Shortcuts For Windows and Mac
Keyboard shortcuts are often used in modern operating systems and computer software programs.
Using keyboard shortcuts could save you a lot of time.
Basic Shortcuts
Description
Windows
Mac OS
Edit menu
Alt + E
Ctrl + F2 + F
File menu
Alt + F
Ctrl + F2 + E
View menu
Alt + V
Ctrl + F2 + V
Select all text
Ctrl + A
Cmd + A
Copy text
Ctrl + C
Cmd + C
Find text
Ctrl + F
Cmd + F
Find and replace text
Ctrl + H
Cmd + F
New Document
Ctrl + N
Cmd + N
Open a file
Ctrl + O
Cmd + O
Print options
Ctrl + P
Cmd + P
Save file
Ctrl + S
Cmd + S
Paste text
Ctrl + V
Cmd + V
Cut text
Ctrl + X
Cmd + X
Redo text
Ctrl + Y
Shift + Cmd + Z
Undo text
Ctrl + Z
Cmd + Z
Text Editing
Description
Windows
Mac OS
Cursor Movement
Go to the right or to the beginning of next line break
Right Arrow
Right Arrow
Go to the left or to the end of previous line break
Left Arrow
Left Arrow
Go up one row
Up Arrow
Up Arrow
Go down one row
Down Arrow
Down Arrow
Go to the beginning of the current line
Home
Cmd + Left Arrow
Go to the end of the current line
End
Cmd + Right Arrow
Go to the beginning of the document
Ctrl + Home
Cmd + Up Arrow
Go to the end of the document
Ctrl + End
Cmd + Down Arrow
Move up one frame
Page Up
Fn + Up Arrow
Move down one frame
Page Down
Fn + Down Arrow
Go to beginning of previous word
Ctrl + Left Arrow
Option + Left Arrow
Go to beginning of next word
Ctrl + Right Arrow
Option + Right Arrow
Go to beginning of line break
Ctrl + Up Arrow
Cmd + Left Arrow
Go to end of line break
Ctrl + Down Arrow
Cmd + Right Arrow
Text Selection
Select characters to the left
Shift + Left Arrow
Shift + Left Arrow
Select characters to the right
Shift + Right Arrow
Shift + Right Arrow
Select lines upwards
Shift + Up Arrow
Shift + Up Arrow
Select lines downwards
Shift + Down Arrow
Shift + Down Arrow
Select words to the left
Shift + Ctrl + Left
Shift + Opt + Left
Select words to the right
Shift + Ctrl + Right
Shift + Opt + Right
Select paragraphs to the left
Shift + Ctrl + Up
Shift + Opt + Up
Select paragraphs to the right
Shift + Ctrl + Down
Shift + Opt + Down
Select text between the cursor and the beginning of the current line
Shift + Home
Cmd + Shift + Left Arrow
Select text between the cursor and the end of the current line
Shift + End
Cmd + Shift + Right Arrow
Select text between the cursor and the beginning of the document
Shift + Ctrl + Home
Cmd + Shift + Up Arrow or Cmd + Shift + Fn + Left Arrow
Select text between the cursor and the end of the document
Shift + Ctrl + End
Cmd + Shift + Down Arrow or Cmd + Shift + Fn + Right Arrow
Select one frame at a time of text above the cursor
Shift + Page Up
Shift + Fn + Up Arrow
Select one frame at a time of text below the cursor
Shift + Page Down
Shift + Fn + Down Arrow
Select all text
Ctrl + A
Cmd + A
Find text
Ctrl + F
Cmd + F
Text Formatting
Make selected text bold
Ctrl + B
Cmd + B
Make selected text italic
Ctrl + I
Cmd + I
Underline selected text
Ctrl + U
Cmd + U
Make selected text superscript
Ctrl + Shift + =
Cmd + Shift + =
Make selected text subscript
Ctrl + =
Cmd + =
Text Editing
Delete characters to the left
Backspace
Backspace
Delete characters to the right
Delete
Fn + Backspace
Delete words to the right
Ctrl + Del
Cmd + Backspace
Delete words to the left
Ctrl + Backspace
Cmd + Fn + Backspace
Indent
Tab
Tab
Outdent
Shift + Tab
Shift + Tab
Copy text
Ctrl + C
Cmd + C
Find and replace text
Ctrl + H
Cmd + F
Paste text
Ctrl + V
Cmd + V
Cut text
Ctrl + X
Cmd + X
Redo text
Ctrl + Y
Shift + Cmd + Z
Undo text
Ctrl + Z
Cmd + Z
Web Browsers
Description
Windows
Mac OS
Navigation
Scroll down a frame
Space or Page Down
Space or Fn + Down Arrow
Scroll up a frame
Shift + Space or Page Up
Shift + Space or Fn + Up Arrow
Go to bottom of the page
End
Cmd + Down Arrow
Go to top of the page
Home
Cmd + Up Arrow
Go back
Alt + Left Arrow or Backspace
Cmd + Left Arrow
Go forward
Alt + Right Arrow or Shift + Backspace
Cmd + Right Arrow
Refresh a webpage
F5
Cmd + R
Refresh a webpage (no cache)
Ctrl + F5
Cmd + Shift + R
Stop
Esc
Esc
Toggle full-screen
F11
Cmd + Shift + F
Zoom in
Ctrl + +
Cmd + +
Zoom out
Ctrl + -
Cmd + -
Zoom 100% (default)
Ctrl + 0
Cmd + 0
Open homepage
Alt + Home
Option + Home or Option + Fn + Left Arrow
Find text
Ctrl + F
Cmd + F
Tab / Window Management
Open a new tab
Ctrl + T
Cmd + T
Close current tab
Ctrl + W
Cmd + W
Close all tabs
Ctrl + Shift + W
Cmd + Q
Close all tabs except the current tab
Ctrl + Alt + F4
Cmd + Opt + W
Go to next tab
Ctrl + Tab
Control + Tab or Cmd + Shift + Right Arrow
Go to previous tab
Ctrl + Shift + Tab
Shift + Control + Tab or Cmd + Shift + Left Arrow
Go to a specific tab number
Ctrl + 1-8
Cmd + 1-8
Go to the last tab
Ctrl + 9
Cmd + 9
Reopen the last closed tab
Ctrl + Shift + T
Cmd + Shift + T
Open a new window
Ctrl + N
Cmd + N
Close current window
Alt + F4
Cmd + W
Go to next window
Alt + Tab
Cmd + Tab
Go to previous window
Alt + Shift + Tab
Cmd + Shift + Tab
Reopen the last closed window
Ctrl + Shift + N
Open links in a new tab in the background
Ctrl + Click
Cmd + Click
Open links in a new tab in the foreground
Ctrl + Shift + Click
Cmd + Shift + Click
Print current webpage
Ctrl + P
Cmd + P
Save current webpage
Ctrl + S
Cmd + S
Address Bar
Cycle between toolbar, search bar, and page elements
Tab
Tab
Go to browser's address bar
Ctrl + L or Alt + D
Cmd + L
Focus and select the browser's search bar
Ctrl + E
Cmd + E / Cmd + K
Open the address bar location in a new tab
Alt + Enter
Opt + Enter
Display a list of previously typed addresses
F4
Add "www." to the beginning and ".com" to the end of the text typed in the
address bar (e.g., type "w3schools" and press Ctrl + Enter to open "www.w3schools.com")
Ctrl + Enter
Cmd + Enter or Control + Enter
Bookmarks
Open the bookmarks menu
Ctrl + B
Cmd + B
Add bookmark for current page
Ctrl + D
Cmd + Opt + B or Cmd + Shift + B
Open browsing history
Ctrl + H
Cmd + Shift + H or Cmd + Y
Open download history
Ctrl + J
Cmd + J or Cmd + Shift + J
Screenshots
Description
Windows
Mac OS
Save screenshot of the whole screen as file
Cmd + Shift + 3
Copy screenshot of the whole screen to the clipboard
PrtScr (Print Screen) or Ctrl + PrtScr
Cmd + Ctrl + Shift + 3
Save screenshot of window as file
Cmd + Shift + 4, then Space
Copy screenshot of window to the clipboard
Alt + PrtScr
Cmd + Ctrl + Shift + 4, then Space
Copy screenshot of wanted area to the clipboard
Cmd + Ctrl + Shift + 4
Save screenshot of wanted area as file
Cmd + Shift + 4
Note: Due to different keyboard setups, some shortcuts may not be compatible for all users.