ArmenianChinese (Traditional)EnglishGermanRussian
HTML 5/2 -

HTML 5/2

HTML Tutorial & Video Lessons

HTML is the standard markup language for Web pages. With HTML you can create your own Website. HTML is easy to learn – You will enjoy it!

  1.  0:00 – Introduction  
  2.  1:33 – Basic structure of an HTML document
  3.  8:42 – Meta data and external imports
  4.  20:08 – Validation, semantics and accessibility
  5.  28:52 – Text
  6.  38:31 – Lists
  7.  43:54 – Pictures
  8.  49:44 – Table
  9.  57:24 – Links and buttons
  10.  1:03:56 – Useful tags
  11.  1:10:18 – Global site structure
  12.  1:17:48 – Shape
  13.  1:27:35 – Types of input fields
  14.  1:36:34 – Types of input fields
  15.  1:44:32 – Video and audio files
  16.  1:49:15 – Common and useful attributes

HTML Tutorial

HTML is the standard markup language for Web pages. With HTML you can create your own Website. HTML is easy to learn – You will enjoy it!

HTML Colors

HTML Colors

HTML colors are specified with predefined color names, or with RGB, HEX, HSL, RGBA, or HSLA values.


Color Names

In HTML, a color can be specified by using a color name:

Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
LightGray

Try it Yourself »

HTML supports 140 standard color names.


Background Color

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.

Example

<h1 style=”background-color:DodgerBlue;”>Hello World</h1>
<p style=”background-color:Tomato;”>Lorem ipsum…</p>

Try it Yourself »


Text Color

You can set the color of text:

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.

Example

<h1 style=”color:Tomato;”>Hello World</h1>
<p style=”color:DodgerBlue;”>Lorem ipsum…</p>
<p style=”color:MediumSeaGreen;”>Ut wisi enim…</p>

Try it Yourself »


 

Border Color

You can set the color of borders:

Hello World

Hello World

Hello World

Example

<h1 style=”border:2px solid Tomato;”>Hello World</h1>
<h1 style=”border:2px solid DodgerBlue;”>Hello World</h1>
<h1 style=”border:2px solid Violet;”>Hello World</h1>

Try it Yourself »


Color Values

In HTML, colors can also be specified using RGB values, HEX values, HSL values, RGBA values, and HSLA values.

The following three

elements have their background color set with RGB, HEX, and HSL values:

rgb(255, 99, 71)
#ff6347
hsl(9, 100%, 64%)

The following two

elements have their background color set with RGBA and HSLA values, which adds an Alpha channel to the color (here we have 50% transparency):

rgba(255, 99, 71, 0.5)
hsla(9, 100%, 64%, 0.5)

Example

<h1 style=”background-color:rgb(255, 99, 71);”></h1>
<h1 style=”background-color:#ff6347;”></h1>
<h1 style=”background-color:hsl(9, 100%, 64%);”></h1>

<h1 style=”background-color:rgba(255, 99, 71, 0.5);”></h1>
<h1 style=”background-color:hsla(9, 100%, 64%, 0.5);”></h1>

Try it Yourself »

Learn more about Color Values

You will learn more about RGBHEX and HSL in the next chapters.

HTML RGB and RGBA Colors

An RGB color value represents RED, GREEN, and BLUE light sources.

An RGBA color value is an extension of RGB with an Alpha channel (opacity).


RGB Color Values

In HTML, a color can be specified as an RGB value, using this formula:

rgb(red, greenblue)

Each parameter (red, green, and blue) defines the intensity of the color with a value between 0 and 255.

This means that there are 256 x 256 x 256 = 16777216 possible colors!

For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255), and the other two (green and blue) are set to 0.

Another example, rgb(0, 255, 0) is displayed as green, because green is set to its highest value (255), and the other two (red and blue) are set to 0.

To display black, set all color parameters to 0, like this: rgb(0, 0, 0).

To display white, set all color parameters to 255, like this: rgb(255, 255, 255).

Experiment by mixing the RGB values below:

 

rgb(255, 99, 71)

 

RED

255

GREEN

99

BLUE

71

Example

rgb(255, 0, 0)
rgb(0, 0, 255)
rgb(60, 179, 113)
rgb(238, 130, 238)
rgb(255, 165, 0)
rgb(106, 90, 205)

Try it Yourself »


ADVERTISEMENT

Shades of Gray

Shades of gray are often defined using equal values for all three parameters:

Example

rgb(60, 60, 60)
rgb(100, 100, 100)
rgb(140, 140, 140)
rgb(180, 180, 180)
rgb(200, 200, 200)
rgb(240, 240, 240)

Try it Yourself »


RGBA Color Values

RGBA color values are an extension of RGB color values with an Alpha channel – which specifies the opacity for a color.

An RGBA color value is specified with:

rgba(red, greenblue, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all):

Experiment by mixing the RGBA values below:

 

rgba(255, 99, 71, 0.5)

 

RED

255

GREEN

99

BLUE

71

ALPHA

0.5

Example

rgba(255, 99, 71, 0)
rgba(255, 99, 71, 0.2)
rgba(255, 99, 71, 0.4)
rgba(255, 99, 71, 0.6)
rgba(255, 99, 71, 0.8)
rgba(255, 99, 71, 1)

Try it Yourself »

HTML HEX Colors

A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.


HEX Color Values

In HTML, a color can be specified using a hexadecimal value in the form:

#rrggbb

Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as decimal 0-255).

For example, #ff0000 is displayed as red, because red is set to its highest value (ff), and the other two (green and blue) are set to 00.

Another example, #00ff00 is displayed as green, because green is set to its highest value (ff), and the other two (red and blue) are set to 00.

To display black, set all color parameters to 00, like this: #000000.

To display white, set all color parameters to ff, like this: #ffffff.

Experiment by mixing the HEX values below:

 

#ff6347

 

RED

ff

GREEN

63

BLUE

47

Example

#ff0000
#0000ff
#3cb371
#ee82ee
#ffa500
#6a5acd

Try it Yourself »


 

Shades of Gray

Shades of gray are often defined using equal values for all three parameters:

Example

#404040
#686868
#a0a0a0
#bebebe
#dcdcdc
#f8f8f8

Try it Yourself »

HTML HSL and HSLA Colors

HSL stands for hue, saturation, and lightness.

HSLA color values are an extension of HSL with an Alpha channel (opacity).


HSL Color Values

In HTML, a color can be specified using hue, saturation, and lightness (HSL) in the form:

hsl(huesaturationlightness)

Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.

Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.

Lightness is also a percentage value, 0% is black, and 100% is white.

Experiment by mixing the HSL values below:

 

hsl(0, 100%, 50%)

 

HUE

0

SATURATION

100%

LIGHTNESS

50%

Example

hsl(0, 100%, 50%)
hsl(240, 100%, 50%)
hsl(147, 50%, 47%)
hsl(300, 76%, 72%)
hsl(39, 100%, 50%)
hsl(248, 53%, 58%)

Try it Yourself »


Saturation

Saturation can be described as the intensity of a color.

100% is pure color, no shades of gray

50% is 50% gray, but you can still see the color.

0% is completely gray, you can no longer see the color.

Example

hsl(0, 100%, 50%)
hsl(0, 80%, 50%)
hsl(0, 60%, 50%)
hsl(0, 40%, 50%)
hsl(0, 20%, 50%)
hsl(0, 0%, 50%)

Try it Yourself »


 

Lightness

The lightness of 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).

Example

hsl(0, 100%, 0%)
hsl(0, 100%, 25%)
hsl(0, 100%, 50%)
hsl(0, 100%, 75%)
hsl(0, 100%, 90%)
hsl(0, 100%, 100%)

Try it Yourself »


Shades of Gray

Shades of gray are often defined by setting the hue and saturation to 0, and adjust the lightness from 0% to 100% to get darker/lighter shades:

Example

hsl(0, 0%, 20%)
hsl(0, 0%, 30%)
hsl(0, 0%, 40%)
hsl(0, 0%, 60%)
hsl(0, 0%, 70%)
hsl(0, 0%, 90%)

Try it Yourself »


HSLA Color Values

HSLA color values are an extension of HSL color values with an Alpha channel – which specifies the opacity for a color.

An HSLA color value is specified with:

hsla(hue, saturationlightness, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all):

Experiment by mixing the HSLA values below:

 

hsla(0, 100%, 50%, 0.5)

 

HUE

0

SATURATION

100%

LIGHTNESS

50%

ALPHA

0.5

Example

hsla(9, 100%, 64%, 0)
hsla(9, 100%, 64%, 0.2)
hsla(9, 100%, 64%, 0.4)
hsla(9, 100%, 64%, 0.6)
hsla(9, 100%, 64%, 0.8)
hsla(9, 100%, 64%, 1)

Try it Yourself »

HTML Links

HTML Links

Links are found in nearly all web pages. Links allow users to click their way from page to page.


HTML Links – Hyperlinks

HTML links are hyperlinks.

You can click on a link and jump to another document.

When you move the mouse over a link, the mouse arrow will turn into a little hand.

Note: A link does not have to be text. A link can be an image or any other HTML element!


HTML Links – Syntax

The HTML  tag defines a hyperlink. It has the following syntax:

<a href=”url>link text</a>

The most important attribute of the  element is the href attribute, which indicates the link’s destination.

The link text is the part that will be visible to the reader.

Clicking on the link text, will send the reader to the specified URL address.

Example

This example shows how to create a link to W3Schools.com:

<a href=”https://www.w3schools.com/”>Visit W3Schools.com!</a>

Try it Yourself »

By default, links will appear as follows in all browsers:

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red

Tip: Links can of course be styled with CSS, to get another look!


HTML Links – The target Attribute

By default, the linked page will be displayed in the current browser window. To change this, you must specify another target for the link.

The target attribute specifies where to open the linked document.

The target attribute can have one of the following values:

  • _self – Default. Opens the document in the same window/tab as it was clicked
  • _blank – Opens the document in a new window or tab
  • _parent – Opens the document in the parent frame
  • _top – Opens the document in the full body of the window

Example

Use target=”_blank” to open the linked document in a new browser window or tab:

<a href=”https://www.w3schools.com/” target=”_blank”>Visit W3Schools!</a>

Try it Yourself »


Absolute URLs vs. Relative URLs

Both examples above are using an absolute URL (a full web address) in the href attribute.

A local link (a link to a page within the same website) is specified with a relative URL (without the “https://www” part):

Example

<h2>Absolute URLs</h2>
<p><a href=”https://www.w3.org/”>W3C</a></p>
<p><a href=”https://www.google.com/”>Google</a></p>

<h2>Relative URLs</h2>
<p><a href=”html_images.asp”>HTML Images</a></p>
<p><a href=”/css/default.asp”>CSS Tutorial</a></p>

Try it Yourself »


ADVERTISEMENT

HTML Links – Use an Image as a Link

To use an image as a link, just put the  tag inside the  tag:

Example

<a href=”default.asp”>
<img src=”smiley.gif” alt=”HTML tutorial” style=”width:42px;height:42px;”>
</a>

Try it Yourself »


Link to an Email Address

Use mailto: inside the href attribute to create a link that opens the user’s email program (to let them send a new email):

Example

<a href=”mailto:[email protected]>Send email</a>

Try it Yourself »


Button as a Link

To use an HTML button as a link, you have to add some JavaScript code.

JavaScript allows you to specify what happens at certain events, such as a click of a button:

Example

<button onclick=”document.location=’default.asp'”>HTML Tutorial</button>

Try it Yourself »

Tip: Learn more about JavaScript in our JavaScript Tutorial.


Link Titles

The title attribute specifies extra information about an element. The information is most often shown as a tooltip text when the mouse moves over the element.

Example

<a href=”https://www.w3schools.com/html/” title=”Go to W3Schools HTML section”>Visit our HTML Tutorial</a>

Try it Yourself »


More on Absolute URLs and Relative URLs

Example

Use a full URL to link to a web page: 

<a href=”https://www.w3schools.com/html/default.asp”>HTML tutorial</a>

Try it Yourself »

Example

Link to a page located in the html folder on the current web site: 

<a href=”/html/default.asp”>HTML tutorial</a>

Try it Yourself »

Example

Link to a page located in the same folder as the current page: 

<a href=”default.asp”>HTML tutorial</a>

Try it Yourself »

You can read more about file paths in the chapter HTML File Paths.


Chapter Summary

  • Use the  element to define a link
  • Use the href attribute to define the link address
  • Use the target attribute to define where to open the linked document
  • Use the  element (inside ) to use an image as a link
  • Use the mailto: scheme inside the href attribute to create a link that opens the user’s email program

HTML Link Tags

TagDescription
 Defines a hyperlink

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Links – Different Colors

An HTML link is displayed in a different color depending on whether it has been visited, is unvisited, or is active.


HTML Link Colors

By default, a link will appear like this (in all browsers):

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red

You can change the link state colors, by using CSS:

Example

Here, an unvisited link will be green with no underline. A visited link will be pink with no underline. An active link will be yellow and underlined. In addition, when mousing over a link (a:hover) it will become red and underlined:

 

Try it Yourself »


 

Link Buttons

A link can also be styled as a button, by using CSS:

This is a link

To learn more about CSS, go to our CSS Tutorial.


HTML Link Tags

TagDescription
 Defines a hyperlink

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Links – Create Bookmarks

HTML links can be used to create bookmarks, so that readers can jump to specific parts of a web page.


Create a Bookmark in HTML

Bookmarks can be useful if a web page is very long.

To create a bookmark – first create the bookmark, then add a link to it.

When the link is clicked, the page will scroll down or up to the location with the bookmark.

Example

First, use the id attribute to create a bookmark:

<h2 id=”C4″>Chapter 4</h2>

Then, add a link to the bookmark (“Jump to Chapter 4”), from within the same page:

Example

<a href=”#C4″>Jump to Chapter 4</a>

Try it Yourself »

You can also add a link to a bookmark on another page:

<a href=”html_demo.html#C4″>Jump to Chapter 4</a>

 

Chapter Summary

  • Use the id attribute (id=”value“) to define bookmarks in a page
  • Use the href attribute (href=”#value“) to link to the bookmark

HTML Exercises

Test Yourself With Exercises

Exercise:

Use the correct HTML to make the text below into a link to “default.html”.

 >Visit our HTML tutorial.

Start the Exercise


HTML Link Tags

TagDescription
 Defines a hyperlink

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Images

HTML Images

Images can improve the design and the appearance of a web page.


 
 
 

Example

<img src=”pic_trulli.jpg” alt=”Italian Trulli”>

Try it Yourself »

Example

<img src=”img_girl.jpg” alt=”Girl in a jacket”>

Try it Yourself »

Example

<img src=”img_chania.jpg” alt=”Flowers in Chania”>

Try it Yourself »


HTML Images Syntax

The HTML  tag is used to embed an image in a web page.

Images are not technically inserted into a web page; images are linked to web pages. The  tag creates a holding space for the referenced image.

The  tag is empty, it contains attributes only, and does not have a closing tag.

The  tag has two required attributes:

  • src – Specifies the path to the image
  • alt – Specifies an alternate text for the image

Syntax

<img src=”url alt=”alternatetext>

The src Attribute

The required src attribute specifies the path (URL) to the image.

Note: When a web page loads, it is the browser, at that moment, that gets the image from a web server and inserts it into the page. Therefore, make sure that the image actually stays in the same spot in relation to the web page, otherwise your visitors will get a broken link icon. The broken link icon and the alt text are shown if the browser cannot find the image.

Example

<img src=”img_chania.jpg” alt=”Flowers in Chania”>

Try it Yourself »


 

The alt Attribute

The required 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”>

Try it Yourself »

If a browser cannot find an image, it will display the value of the alt attribute:

Example

<img src=”wrongname.gif” alt=”Flowers in Chania”>

Try it Yourself »

Tip: A screen reader is a software program that reads the HTML code, and allows the user to “listen” to the content. Screen readers are useful for people who are visually impaired or learning disabled.


Image Size – Width and Height

You can use the style attribute to specify the width and height of an image.

Example

<img src=”img_girl.jpg” alt=”Girl in a jacket” style=”width:500px;height:600px;”>

Try it Yourself »

Alternatively, you can use the width and height attributes:

Example

<img src=”img_girl.jpg” alt=”Girl in a jacket” width=”500″ height=”600″>

Try it Yourself »

The width and height attributes always define the width and height of the image in pixels.

Note: Always specify the width and height of an image. If width and height are not specified, the web page might flicker while the image loads.


Width and Height, or Style?

The widthheight, and style attributes are all valid in HTML.

However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:

Example

<!DOCTYPE html>
<html>
<head>
<style>
img {
  width: 100%;
}
</style>
</head>
<body>

<img src=”html5.gif” alt=”HTML5 Icon” width=”128″ height=”128″>

<img src=”html5.gif” alt=”HTML5 Icon” style=”width:128px;height:128px;”>

</body>
</html>

Try it Yourself »


Images in Another Folder

If you have your images in a sub-folder, you must include the folder name in the src attribute:

Example

<img src=”/images/html5.gif” alt=”HTML5 Icon” style=”width:128px;height:128px;”>

Try it Yourself »


Images on Another Server/Website

Some web sites point to an image on another server.

To point to an image on another server, you must specify an absolute (full) URL in the src attribute:

Example

<img src=”https://www.w3schools.com/images/w3schools_green.jpg” alt=”W3Schools.com”>

Try it Yourself »

Notes on external images: External images might be under copyright. If you do not get permission to use it, you may be in violation of copyright laws. In addition, you cannot control external images; it can suddenly be removed or changed.


Animated Images

HTML allows animated GIFs:

Example

<img src=”programming.gif” alt=”Computer Man” style=”width:48px;height:48px;”>

Try it Yourself »


Image as a Link

To use an image as a link, put the  tag inside the  tag:

Example

<a href=”default.asp”>
  <img src=”smiley.gif” alt=”HTML tutorial” style=”width:42px;height:42px;”>
</a>

Try it Yourself »


Image Floating

Use the CSS float property to let the image float to the right or to the left of a text:

Example

<p><img src=”smiley.gif” alt=”Smiley face” style=”float:right;width:42px;height:42px;”>
The image will float to the right of the text.</p>

<p><img src=”smiley.gif” alt=”Smiley face” style=”float:left;width:42px;height:42px;”>
The image will float to the left of the text.</p>

Try it Yourself »

Tip: To learn more about CSS Float, read our CSS Float Tutorial.


Common Image Formats

Here are the most common image file types, which are supported in all browsers (Chrome, Edge, Firefox, Safari, Opera):

AbbreviationFile FormatFile Extension
APNGAnimated Portable Network Graphics.apng
GIFGraphics Interchange Format.gif
ICOMicrosoft Icon.ico, .cur
JPEGJoint Photographic Expert Group image.jpg, .jpeg, .jfif, .pjpeg, .pjp
PNGPortable Network Graphics.png
SVGScalable Vector Graphics.svg

Chapter Summary

  • Use the HTML  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 or the CSS width and height properties to define the size of the image
  • Use the CSS float property to let the image float to the left or to the right

Note: Loading large images takes time, and can slow down your web page. Use images carefully.


HTML Exercises

Test Yourself With Exercises

Exercise:

Use the HTML image attributes to set the size of the image to 250 pixels wide and 400 pixels tall.

=”250″ =”400″>

Start the Exercise


HTML Image Tags

TagDescription
Defines an image
 Defines an image map
 Defines a clickable area inside an image map
 Defines a container for multiple image resources

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Image Maps

With HTML image maps, you can create clickable areas on an image.


Image Maps

The HTML 

 tag defines an image map. An image map is an image with clickable areas. The areas are defined with one or more 

 tags.

Try to click on the computer, phone, or the cup of coffee in the image below:

Workplace

Sun Mercury Venus

Example

Here is the HTML source code for the image map above:

<img src=”workplace.jpg” alt=”Workplace” usemap=”#workmap”>

<map name=”workmap”>
  <area shape=”rect” coords=”34,44,270,350″ alt=”Computer” href=”computer.htm”>
  <area shape=”rect” coords=”290,172,333,250″ alt=”Phone” href=”phone.htm”>
  <area shape=”circle” coords=”337,300,44″ alt=”Coffee” href=”coffee.htm”>
</map>

Try it Yourself »


 

How Does it Work?

The idea behind an image map is that you should be able to perform different actions depending on where in the image you click.

To create an image map you need an image, and some HTML code that describes the clickable areas.


 

The Image

The image is inserted using the  tag. The only difference from other images is that you must add a usemap attribute:

<img src=”workplace.jpg” alt=”Workplace” usemap=”#workmap”>

The usemap value starts with a hash tag # followed by the name of the image map, and is used to create a relationship between the image and the image map.

Tip: You can use any image as an image map!


Create Image Map

Then, add a 

 element.

The 

 element is used to create an image map, and is linked to the image by using the required name attribute:

<map name=”workmap”>

The name attribute must have the same value as the ‘s usemap attribute .


The Areas

Then, add the clickable areas.

A clickable area is defined using an 

 element.

Shape

You must define the shape of the clickable area, and you can choose one of these values:

  • rect – defines a rectangular region
  • circle – defines a circular region
  • poly – defines a polygonal region
  • default – defines the entire region

You must also define some coordinates to be able to place the clickable area onto the image. 


Shape=”rect”

The coordinates for shape="rect" come in pairs, one for the x-axis and one for the y-axis.

So, the coordinates 34,44 is located 34 pixels from the left margin and 44 pixels from the top:

 
 
 

Workplace

The coordinates 270,350 is located 270 pixels from the left margin and 350 pixels from the top:

 
 
 

Workplace

Now we have enough data to create a clickable rectangular area:

Example

<area shape=”rect” coords=”34, 44, 270, 350″ href=”computer.htm”>

Try it Yourself »

This is the area that becomes clickable and will send the user to the page “computer.htm”:

 

Workplace


Shape=”circle”

To add a circle area, first locate the coordinates of the center of the circle:

337,300

 
 
 

Workplace

Then specify the radius of the circle:

44 pixels

 
 

Workplace

Now you have enough data to create a clickable circular area:

Example

<area shape=”circle” coords=”337, 300, 44″ href=”coffee.htm”>

Try it Yourself »

This is the area that becomes clickable and will send the user to the page “coffee.htm”:

 

Workplace


Shape=”poly”

The shape="poly" contains several coordinate points, which creates a shape formed with straight lines (a polygon).

This can be used to create any shape.

Like maybe a croissant shape!

How can we make the croissant in the image below become a clickable link?

French Food

We have to find the x and y coordinates for all edges of the croissant:

French Food

The coordinates come in pairs, one for the x-axis and one for the y-axis:

Example

<area shape=”poly” coords=”140,121,181,116,204,160,204,222,191,270,140,329,85,355,58,352,37,322,40,259,103,161,128,147″ href=”croissant.htm”>

Try it Yourself »

This is the area that becomes clickable and will send the user to the page “croissant.htm”:

French Food


Image Map and JavaScript

A clickable area can also trigger a JavaScript function.

Add a click event to the 

 element to execute a JavaScript function:

Example

Here, we use the onclick attribute to execute a JavaScript function when the area is clicked:

<map name=”workmap”>
  <area shape=”circle” coords=”337,300,44″ href=”coffee.htm” onclick=”myFunction()”>
</map>

<script>
function myFunction() {
  alert(“You clicked the coffee cup!”);
}
</script>

Try it Yourself »


Chapter Summary

    • Use the HTML 

       

       element to define an image map

    • Use the HTML 
  •  element to define the clickable areas in the image map
  • Use the HTML usemap attribute of the  element to point to an image map

HTML Image Tags

TagDescription
Defines an image
 Defines an image map
 Defines a clickable area inside an image map
 Defines a container for multiple image resources

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Background Images

A background image can be specified for almost any HTML element.


Background Image on a HTML element

To add a background image on an HTML element, use the HTML style attribute and the CSS background-image property:

Example

Add a background image on a HTML element:

<p style=”background-image: url(‘img_girl.jpg’);”>

Try it Yourself »

You can also specify the background image in the 

HTML  Element

The HTML  element allows you to display different pictures for different devices or screen sizes.



The HTML Element

The HTML  element gives web developers more flexibility in specifying image resources.

The  element contains one or more  elements, each referring to different images through the srcset attribute. This way the browser can choose the image that best fits the current view and/or device.

Each  element has a media attribute that defines when the image is the most suitable.

Example

Show different images for different screen sizes:

<picture>
  <source media=”(min-width: 650px)” srcset=”img_food.jpg”>
  <source media=”(min-width: 465px)” srcset=”img_car.jpg”>
  <img src=”img_girl.jpg”>
</picture>

Try it Yourself »

Note: Always specify an  element as the last child element of the  element. The  element is used by browsers that do not support the  element, or if none of the  tags match.


 
 

When to use the Picture Element

There are two main purposes for the  element:

1. Bandwidth

If you have a small screen or device, it is not necessary to load a large image file. The browser will use the first  element with matching attribute values, and ignore any of the following elements.

2. Format Support

Some browsers or devices may not support all image formats. By using the  element, you can add images of all formats, and the browser will use the first format it recognizes, and ignore any of the following elements.

Example

The browser will use the first image format it recognizes:

<picture>
  <source srcset=”img_avatar.png”>
  <source srcset=”img_girl.jpg”>
  <img src=”img_beatles.gif” alt=”Beatles” style=”width:auto;”>
</picture>

Try it Yourself »

Note: The browser will use the first  element with matching attribute values, and ignore any following  elements.


HTML Image Tags

TagDescription
Defines an image
 Defines an image map
 Defines a clickable area inside an image map
 Defines a container for multiple image resources

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Tables

HTML Tables

HTML tables allow web developers to arrange data into rows and columns.


Example

CompanyContactCountry
Alfreds FutterkisteMaria AndersGermany
Centro comercial MoctezumaFrancisco ChangMexico
Ernst HandelRoland MendelAustria
Island TradingHelen BennettUK
Laughing Bacchus WinecellarsYoshi TannamuriCanada
Magazzini Alimentari RiunitiGiovanni RovelliItaly

Try it Yourself »


Define an HTML Table

A table in HTML consists of table cells inside rows and columns

Example

A simple HTML table:

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table>

Try it Yourself »


Video Introduction to HTML Tables

We have made a video tutorial that covers all the basics of HTML – in a new fun format :-}
Watch the chapter about HTML Tables for free!

More Videos

Subscribe to PRO for $4.99/month to access the full video with 22 chapters!

You also unlock powerful features, such as W3Schools ad-free and website hosting, and you can cancel the subscription at any time.

See the full details here.


Table Cells

Each table cell is defined by a 

 and a 

 tag.

td stands for table data.

Everything between 

 and 

 are the content of the table cell.

Example

<table>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td>Linus</td>
  </tr>
</table>

Try it Yourself »

Note: table data elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.


Table Rows

Each table row starts with a 

 and end with a 

 tag.

tr stands for table row.

Example

<table>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td>Linus</td>
  </tr>
  <tr>
    <td>16</td>
    <td>14</td>
    <td>10</td>
  </tr>
</table>

Try it Yourself »

You can have as many rows as you like in a table, just make sure that the number of cells are the same in each row.

Note: There are times where a row can have less or more cells than another. You will learn about that in a later chapter.


Table Headers

Sometimes you want your cells to be headers, in those cases use the 

 tag instead of the 

 tag:

Example

Let the first row be table headers:

<table>
  <tr>
    <th>Person 1</th>
    <th>Person 2</th>
    <th>Person 3</th>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td>Linus</td>
  </tr>
  <tr>
    <td>16</td>
    <td>14</td>
    <td>10</td>
  </tr>
</table>

Try it Yourself »

By default, the text in 

 elements are bold and centered, but you can change that with CSS.


HTML Exercises

Test Yourself With Exercises

Exercise:

Add a table row with two table headers.

The two table headers should have the value “Name” and “Age”.

 

Jill Smith50

Start the Exercise


HTML Table Tags

TagDescription
 Defines a table
 Defines a header cell in a table
 Defines a row in a table
  Defines a cell in a table
 Defines a table caption
 Specifies a group of one or more columns in a table for formatting
 

Specifies column properties for each column within a

element

 Groups the header content in a table
 Groups the body content in a table
 Groups the footer content in a table

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Table Borders

HTML tables can have borders of different styles and shapes.


How To Add a Border

When you add a border to a table, you also add borders around each table cell:

   
   
   

To add a border, use the CSS border property on tableth, and td elements:

Example

table, th, td {
  border: 1px solid black;
}

Try it Yourself »


Collapsed Table Borders

To avoid having double borders like in the example above, set the CSS border-collapse property to collapse.

This will make the borders collapse into a single border:

   
   
   

Example

table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

Try it Yourself »


 

Style Table Borders

If you set a background color of each cell, and give the border a white color (the same as the document background), you get the impression of an invisible border:

   
   
   

Example

table, th, td {
  border: 1px solid white;
  border-collapse: collapse;
}
th, td {
  background-color: #96D4D4;
}

Try it Yourself »


Round Table Borders

With the border-radius property, the borders get rounded corners:

   
   
   

Example

table, th, td {
  border: 1px solid black;
  border-radius: 10px;
}

Try it Yourself »


Skip the border around the table by leaving out table from the css selector:

   
   
   

Example

th, td {
  border: 1px solid black;
  border-radius: 10px;
}

Try it Yourself »


Dotted Table Borders

With the border-style property, you can set the appereance of the border.

   
   
   

The following values are allowed:

  • dotted     
  • dashed     
  • solid     
  • double     
  • groove     
  • ridge     
  • inset     
  • outset     
  • none     
  • hidden     

Example

 th, td {
  border-style: dotted;
}

Try it Yourself »


Border Color

With the border-color property, you can set the color of the border.

   
   
   

Example

 th, td {
  border-color: #96D4D4;
}

Try it Yourself »

HTML Table Sizes

HTML tables can have different sizes for each column, row or the entire table.


   
   
   
   
   
   
   
   

Use the style attribute with the width or height properties to specify the size of a table, row or column.


HTML Table Width

To set the width of a table, add the style attribute to the 

 element:

Example

Set the width of the table to 100%:

<table style=”width:100%”>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Try it Yourself »

Note: Using a percentage as the size unit for a width means how wide will this element be compared to its parent element, which in this case is the 

 element.

HTML Table Column WidthTo set the size of a specific column, add the style attribute on a 

 or 

 element:

Example

Set the width of the first column to 70%:

<table style=”width:100%”>
  <tr>
    <th style=”width:70%”>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Try it Yourself »


HTML Table Row Height

   
   
   
   
   
   

To set the height of a specific row, add the style attribute on a table row element:

Example

Set the height of the second row to 200 pixels:

<table style=”width:100%”>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr style=”height:200px”>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Try it Yourself »


HTML Exercises

Test Yourself With Exercises

Exercise:

Use CSS styles to make the table 300 pixels wide.

>  

    First Name    Last Name    Points  

 

    Jill    Smith    50  

 

Start the Exercise

HTML Table Headers

HTML tables can have headers for each column or row, or for many columns/rows.


EMILTOBIASLINUS
   
   
   
   
   
8:00  
9:00  
10:00  
11:00  
12:00  
13:00  
 MONTUEWEDTHUFRI
8:00     
9:00     
10:00     
11:00     
12:00     
DECEMBER
   
   
   
   
   

HTML Table Headers

Table headers are defined with th elements, each th element represents a table cell.

Example

<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Try it Yourself »


Vertical Table Headers

To use the first column as table headers, define the first cell in each row as a th element:

Example

<table>
  <tr>
    <th>Firstname</th>
    <td>Jill</td>
    <td>Eve</td>
  </tr>
  <tr>
    <th>Lastname</th>
    <td>Smith</td>
    <td>Jackson</td>
  </tr>
  <tr>
    <th>Age</th>
    <td>94</td>
    <td>50</td>
  </tr>
</table>

Try it Yourself »


 

Align Table Headers

By default, table headers are bold and centered:

FirstnameLastnameAge
JillSmith50
EveJackson94

To left-align the table headers, use the CSS text-align property:

Example

th {
  text-align: left;
}

Try it Yourself »


Header for Multiple Columns

You can have a header that spans over two or more columns.

NameAge
JillSmith50
EveJackson94

To do this, use the colspan attribute on the 

 element:

Example

<table>
  <tr>
    <th colspan=”2″>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

Try it Yourself »

You will learn more about colspan and rowspan in the Table colspan & rowspan chapter.


Table Caption

You can add a caption that serves as a heading for the entire table.

Monthly savings
MonthSavings
January$100
February$50

To add a caption to a table, use the 

 tag:

Example

<table style=”width:100%”>
  <caption>Monthly savings</caption>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$50</td>
  </tr>
</table>

Try it Yourself »

Note: The 

 tag should be inserted immediately after the  tag.


HTML Exercises

Test Yourself With Exercises

Exercise:

Add a table caption that says “Names”.

 

First NameLast NamePoints
JillSmith50

Start the Exercise

HTML Table Padding & Spacing

HTML tables can adjust the padding inside the cells, and also the space between the cells.


With Padding
hellohellohello
hellohellohello
hellohellohello
With Spacing
hellohellohello
hellohellohello
hellohellohello

HTML Table – Cell Padding

Cell padding is the space between the cell edges and the cell content.

By default the padding is set to 0.

To add padding on table cells, use the CSS padding property:

Example

th, td {
  padding: 15px;
}

Try it Yourself »

To add padding only above the content, use the padding-top property.

And the others sides with the padding-bottompadding-left, and padding-right properties:

Example

th, td {
  padding-top: 10px;
  padding-bottom: 20px;
  padding-left: 30px;
  padding-right: 40px;
}

Try it Yourself »


HTML Table – Cell Spacing

Cell spacing is the space between each cell.

By default the space is set to 2 pixels.

To change the space between table cells, use the CSS border-spacing property on the table element:

Example

table {
  border-spacing: 30px;
}

Try it Yourself »

HTML Table Colspan & Rowspan

HTML tables can have cells that spans over multiple rows and/or columns.


NAME 
   
   
   
   
APRIL  
  
  
   
   
2022
   
FIESTA 
 
   

HTML Table – Colspan

To make a cell span over multiple columns, use the colspan attribute:

Example

<table>
  <tr>
    <th colspan=”2″>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>43</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>57</td>
  </tr>
</table>

Try it Yourself »

Note: The value of the colspan attribute represents the number of columns to span.


HTML Table – Rowspan

To make a cell span over multiple rows, use the rowspan attribute:

Example

<table>
  <tr>
    <th>Name</th>
    <td>Jill</td>
  </tr>
  <tr>
    <th rowspan=”2″>Phone</th>
    <td>555-1234</td>
  </tr>
  <tr>
    <td>555-8745</td>
</tr>
</table>

Try it Yourself »

Note: The value of the rowspan attribute represents the number of rows to span.


 

HTML Exercises

Test Yourself With Exercises

Exercise:

Use the correct HTML attribute to make the first TH element span two columns.

      >Name                                      

 Age
JillSmith50
EveJackson94

Start the Exercise

HTML Table Styling

Use CSS to make your tables look better.


HTML Table – Zebra Stripes

If you add a background color on every other table row, you will get a nice zebra stripes effect.

1234
5678
9101112
13141516
17181920

To style every other table row element, use the :nth-child(even) selector like this:

Example

tr:nth-child(even) {
  background-color: #D6EEEE;
}

Try it Yourself »

Note: If you use (odd) instead of (even), the styling will occur on row 1,3,5 etc. instead of 2,4,6 etc.


HTML Table – Vertical Zebra Stripes

To make vertical zebra stripes, style every other column, instead of every other row.

1234
5678
9101112
13141516
17181920

Set the :nth-child(even) for table data elements like this:

Example

td:nth-child(even), th:nth-child(even) {
  background-color: #D6EEEE;
}

Try it Yourself »

Note: Put the :nth-child() selector on both th and td elements if you want to have the styling on both headers and regular table cells.


Combine Vertical and Horizontal Zebra Stripes

You can combine the styling from the two examples above and you will have stripes on every other row and every other column.

If you use a transparent color you will get an overlapping effect.

         
         
         
         
         

Use an rgba() color to specify the transparency of the color:

Example

tr:nth-child(even) {
  background-color: rgba(150, 212, 212, 0.4);
}

th:nth-child(even),td:nth-child(even) {
  background-color: rgba(150, 212, 212, 0.4);
}

Try it Yourself »


Horizontal Dividers

First NameLast NameSavings
PeterGriffin$100
LoisGriffin$150
JoeSwanson$300

If you specify borders only at the bottom of each table row, you will have a table with horizontal dividers.

Add the border-bottom property to all tr elements to get horizontal dividers:

Example

tr {
  border-bottom: 1px solid #ddd;
}

Try it Yourself »


Hoverable Table

Use the :hover selector on tr to highlight table rows on mouse over:

First NameLast NameSavings
PeterGriffin$100
LoisGriffin$150
JoeSwanson$300

Example

tr:hover {background-color: #D6EEEE;}

Try it Yourself »

HTML Table Colgroup

The 

 element is used to style specific columns of a table.


HTML Table Colgroup

If you want to style the two first columns of a table, use the 

 and 


 elements.

MONTUEWEDTHUFRISATSUN
1234567
891011121314
15161718192021
22232425262728

The 

 element should be used as a container for the column specifications.

Each group are specified with a 

 element.

The span attribute specifies how many columns that gets the style.

The style attribute specifies the style to give the columns.

Note: There is a very limited selection of legal CSS properties for colgroups.

Example

<table>
  <colgroup>
    <col span=”2″ style=”background-color: #D6EEEE”>
  </colgroup>
  <tr>
    <th>MON</th>
    <th>TUE</th>
    <th>WED</th>
    <th>THU</th>

Try it Yourself »

Note: The 

 tag must be a child of a 

 element and should be placed before any other table elements, like 

 etc., but after the 

 

 element, if present.


Legal CSS Properties

There are only a very limited selection of CSS properties that are allowed to be used in the colgroup:

width property
visibility property
background properties
border properties

All other CSS properties will have no effect on your tables.


 

Multiple Col Elements

If you want to style more columns with different styles, use more 

 elements inside the 


:

Example

<table>
  <colgroup>
    <col span=”2″ style=”background-color: #D6EEEE”>
    <col span=”3″ style=”background-color: pink”>
  </colgroup>
  <tr>
    <th>MON</th>
    <th>TUE</th>
    <th>WED</th>
    <th>THU</th>

Try it Yourself »


Empty Colgroups

If you want to style columns in the middle of a table, insert a “empty” 

 element (with no styles) for the columns before:

Example

<table>
  <colgroup>
    <col span=”3″>
    <col span=”2″ style=”background-color: pink”>
  </colgroup>
  <tr>
    <th>MON</th>
    <th>TUE</th>
    <th>WED</th>
    <th>THU</th>

Try it Yourself »


Hide Columns

You can hide columns with the visibility: collapse property:

Example

<table>
  <colgroup>
    <col span=”2″>
    <col span=”3″ style=”visibility: collapse”>
  </colgroup>
  <tr>
    <th>MON</th>
    <th>TUE</th>
    <th>WED</th>
    <th>THU</th>

Try it Yourself »

HTML Lists

HTML Lists

HTML lists allow web developers to group a set of related items in lists.


Example

An unordered HTML list:

  • Item
  • Item
  • Item
  • Item

An ordered HTML list:

  1. First item
  2. Second item
  3. Third item
  4. Fourth item

Try it Yourself »


Unordered HTML List

An unordered list starts with the 

    •  tag. Each list item starts with the 

  •  
    •  tag.

The list items will be marked with bullets (small black circles) by default:

Example

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Try it Yourself »


Ordered HTML List

An ordered list starts with the 

      1.  tag. Each list item starts with the 

  •  
      1.  tag.

The list items will be marked with numbers by default:

Example

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

The 

 tag defines the description list, the 

 tag defines the term (name), and the 

 

 tag describes each term:

Example

<dl>
  <dt>Coffee</dt>
  <dd>– black hot drink</dd>
  <dt>Milk</dt>
  <dd>– white cold drink</dd>
</dl>

Try it Yourself »


HTML List Tags

TagDescription
 Defines an unordered list
 Defines an ordered list
  •  
Defines a list item
 Defines a description list
 Defines a term in a description list
 Describes the term in a description list

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Unordered Lists

The HTML 

    •  tag defines an unordered (bulleted) list.

Unordered HTML List

An unordered list starts with the 

      •  tag. Each list item starts with the 

  •  
      •  tag.

The list items will be marked with bullets (small black circles) by default:

Example

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Try it Yourself »


Unordered HTML List – Choose List Item Marker

The CSS list-style-type property is used to define the style of the list item marker. It can have one of the following values:

ValueDescription
discSets the list item marker to a bullet (default)
circleSets the list item marker to a circle
squareSets the list item marker to a square
noneThe list items will not be marked

Example – Disc

<ul style=”list-style-type:disc;”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Try it Yourself »

Example – Circle

<ul style=”list-style-type:circle;”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Try it Yourself »

Example – Square

<ul style=”list-style-type:square;”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Try it Yourself »

Example – None

<ul style=”list-style-type:none;”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Try it Yourself »


 

Nested HTML Lists

Lists can be nested (list inside list):

Example

<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

Try it Yourself »

Note: A list item (

  • ) can contain a new list, and other HTML elements, like images and links, etc.

Horizontal List with CSS

HTML lists can be styled in many different ways with CSS.

One popular way is to style a list horizontally, to create a navigation menu:

Example

<!DOCTYPE html>
<html>
<head>
<style>
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #111111;
}
</style>
</head>
<body>

<ul>
  <li><a href=”#home”>Home</a></li>
  <li><a href=”#news”>News</a></li>
  <li><a href=”#contact”>Contact</a></li>
  <li><a href=”#about”>About</a></li>
</ul>

</body>
</html>

Try it Yourself »

Tip: You can learn much more about CSS in our CSS Tutorial.


Chapter Summary

        • Use the HTML  element to define an unordered list
        • Use the CSS list-style-type property to define the list item marker
        • Use the HTML 
        •  
        •  element to define a list item
        • Lists can be nested
        • List items can contain other HTML elements
        • Use the CSS property float:left to display a list horizontally

HTML List Tags

TagDescription
 Defines an unordered list
 Defines an ordered list
  •  
Defines a list item
 Defines a description list
 Defines a term in a description list
 Describes the term in a description list

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Ordered Lists

The HTML 

    1.  tag defines an ordered list. An ordered list can be numerical or alphabetical.

Ordered HTML List

An ordered list starts with the 

      1.  tag. Each list item starts with the 

  •  
      1.  tag.

The list items will be marked with numbers by default:

Example

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


Ordered HTML List – The Type Attribute

The type attribute of the 

        1.  tag, defines the type of the list item marker:
TypeDescription
type=”1″The list items will be numbered with numbers (default)
type=”A”The list items will be numbered with uppercase letters
type=”a”The list items will be numbered with lowercase letters
type=”I”The list items will be numbered with uppercase roman numbers
type=”i”The list items will be numbered with lowercase roman numbers

Numbers:

<ol type=”1″>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Uppercase Letters:

<ol type=”A”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Lowercase Letters:

<ol type=”a”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Uppercase Roman Numbers:

<ol type=”I”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Lowercase Roman Numbers:

<ol type=”i”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


 

Control List Counting

By default, an ordered list will start counting from 1. If you want to start counting from a specified number, you can use the start attribute:

Example

<ol start=”50″>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


Nested HTML Lists

Lists can be nested (list inside list):

Example

<ol>
  <li>Coffee</li>
  <li>Tea
    <ol>
      <li>Black tea</li>
      <li>Green tea</li>
    </ol>
  </li>
  <li>Milk</li>
</ol>

Try it Yourself »

Note: A list item (

  • ) can contain a new list, and other HTML elements, like images and links, etc.

Chapter Summary

          • Use the HTML  element to define an ordered list
          • Use the HTML type attribute to define the numbering type
          • Use the HTML 
          •  
          •  element to define a list item
          • Lists can be nested
          • List items can contain other HTML elements

HTML List Tags

TagDescription
 Defines an unordered list
 Defines an ordered list
  •  
Defines a list item
 Defines a description list
 Defines a term in a description list
 Describes the term in a description list

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Ordered Lists

The HTML 

    1.  tag defines an ordered list. An ordered list can be numerical or alphabetical.

Ordered HTML List

An ordered list starts with the 

      1.  tag. Each list item starts with the 

  •  
      1.  tag.

The list items will be marked with numbers by default:

Example

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


Ordered HTML List – The Type Attribute

The type attribute of the 

        1.  tag, defines the type of the list item marker:
TypeDescription
type=”1″The list items will be numbered with numbers (default)
type=”A”The list items will be numbered with uppercase letters
type=”a”The list items will be numbered with lowercase letters
type=”I”The list items will be numbered with uppercase roman numbers
type=”i”The list items will be numbered with lowercase roman numbers

Numbers:

<ol type=”1″>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Uppercase Letters:

<ol type=”A”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Lowercase Letters:

<ol type=”a”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Uppercase Roman Numbers:

<ol type=”I”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »

Lowercase Roman Numbers:

<ol type=”i”>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


 

Control List Counting

By default, an ordered list will start counting from 1. If you want to start counting from a specified number, you can use the start attribute:

Example

<ol start=”50″>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Try it Yourself »


Nested HTML Lists

Lists can be nested (list inside list):

Example

<ol>
  <li>Coffee</li>
  <li>Tea
    <ol>
      <li>Black tea</li>
      <li>Green tea</li>
    </ol>
  </li>
  <li>Milk</li>
</ol>

Try it Yourself »

Note: A list item (

  • ) can contain a new list, and other HTML elements, like images and links, etc.

Chapter Summary

          • Use the HTML  element to define an ordered list
          • Use the HTML type attribute to define the numbering type
          • Use the HTML 
          •  
          •  element to define a list item
          • Lists can be nested
          • List items can contain other HTML elements

HTML List Tags

TagDescription
 Defines an unordered list
 Defines an ordered list
  •  
Defines a list item
 Defines a description list
 Defines a term in a description list
 Describes the term in a description list

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Forms

HTML Forms

An HTML form is used to collect user input. The user input is most often sent to a server for processing.


Example




Try it Yourself »


The

Element

The HTML 

 element is used to create an HTML form for user input:

<form>
.
form elements
.
</form>

The 

 element is a container for different types of input elements, such as: text fields, checkboxes, radio buttons, submit buttons, etc.

All the different form elements are covered in this chapter: HTML Form Elements.


The Element

The HTML  element is the most used form element.

An  element can be displayed in many ways, depending on the type attribute.

Here are some examples:

TypeDescription
Displays a single-line text input field
Displays a radio button (for selecting one of many choices)
Displays a checkbox (for selecting zero or more of many choices)
Displays a submit button (for submitting the form)
Displays a clickable button

All the different input types are covered in this chapter: HTML Input Types.


 

Text Fields

The  defines a single-line input field for text input.

Example

A form with input fields for text:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

Note: The form itself is not visible. Also note that the default width of an input field is 20 characters.


The

Notice the use of the  element in the example above.

The  tag defines a label for many form elements.

The  element is useful for screen-reader users, because the screen-reader will read out loud the label when the user focus on the input element.

The  element also help users who have difficulty clicking on very small regions (such as radio buttons or checkboxes) – because when the user clicks the text within the  element, it toggles the radio button/checkbox.

The for attribute of the  tag should be equal to the id attribute of the  element to bind them together.


Radio Buttons

The  defines a radio button.

Radio buttons let a user select ONE of a limited number of choices.

Example

A form with radio buttons:

<p>Choose your favorite Web language:</p>

<form>
  <input type=”radio” id=”html” name=”fav_language” value=”HTML”>
  <label for=”html”>HTML</label><br>
  <input type=”radio” id=”css” name=”fav_language” value=”CSS”>
  <label for=”css”>CSS</label><br>
  <input type=”radio” id=”javascript” name=”fav_language” value=”JavaScript”>
  <label for=”javascript”>JavaScript</label>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

Choose your favorite Web language:

 
 
 


Checkboxes

The  defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example

A form with checkboxes:

<form>
  <input type=”checkbox” id=”vehicle1″ name=”vehicle1″ value=”Bike”>
  <label for=”vehicle1″> I have a bike</label><br>
  <input type=”checkbox” id=”vehicle2″ name=”vehicle2″ value=”Car”>
  <label for=”vehicle2″> I have a car</label><br>
  <input type=”checkbox” id=”vehicle3″ name=”vehicle3″ value=”Boat”>
  <label for=”vehicle3″> I have a boat</label>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

 
 
 


The Submit Button

The  defines a button for submitting the form data to a form-handler.

The form-handler is typically a file on the server with a script for processing input data.

The form-handler is specified in the form’s action attribute.

Example

A form with a submit button:

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:


The Name Attribute for

Notice that each input field must have a name attribute to be submitted.

If the name attribute is omitted, the value of the input field will not be sent at all.

Example

This example will not submit the value of the “First name” input field: 

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” value=”John”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »


HTML Exercises

Test Yourself With Exercises

Exercise:

In the form below, add an input field with the type “button” and the value “OK”.

<>

Start the Exercise

HTML Form Attributes

This chapter describes the different attributes for the HTML 

 element.


The Action Attribute

The action attribute defines the action to be performed when the form is submitted.

Usually, the form data is sent to a file on the server when the user clicks on the submit button.

In the example below, the form data is sent to a file called “action_page.php”. This file contains a server-side script that handles the form data:

Example

On submit, send form data to “action_page.php”:

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »

Tip: If the action attribute is omitted, the action is set to the current page.


The Target Attribute

The target attribute specifies where to display the response that is received after submitting the form.

The target attribute can have one of the following values:

ValueDescription
_blankThe response is displayed in a new window or tab
_selfThe response is displayed in the current window
_parentThe response is displayed in the parent frame
_topThe response is displayed in the full body of the window
framenameThe response is displayed in a named iframe

The default value is _self which means that the response will open in the current window.

Example

Here, the submitted result will open in a new browser tab:

<form action=”/action_page.php” target=”_blank”>

Try it Yourself »


The Method Attribute

The method attribute specifies the HTTP method to be used when submitting the form data.

The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with method="post").

The default HTTP method when submitting form data is GET. 

Example

This example uses the GET method when submitting the form data:

<form action=”/action_page.php” method=”get”>

Try it Yourself »

Example

This example uses the POST method when submitting the form data:

<form action=”/action_page.php” method=”post”>

Try it Yourself »

Notes on GET:

  • Appends the form data to the URL, in name/value pairs
  • NEVER use GET to send sensitive data! (the submitted form data is visible in the URL!)
  • The length of a URL is limited (2048 characters)
  • Useful for form submissions where a user wants to bookmark the result
  • GET is good for non-secure data, like query strings in Google

Notes on POST:

  • Appends the form data inside the body of the HTTP request (the submitted form data is not shown in the URL)
  • POST has no size limitations, and can be used to send large amounts of data.
  • Form submissions with POST cannot be bookmarked

Tip: Always use POST if the form data contains sensitive or personal information!


 

The Autocomplete Attribute

The autocomplete attribute specifies whether a form should have autocomplete on or off.

When autocomplete is on, the browser automatically complete values based on values that the user has entered before.

Example

A form with autocomplete on:

<form action=”/action_page.php” autocomplete=”on”>

Try it Yourself »


The Novalidate Attribute

The novalidate attribute is a boolean attribute.

When present, it specifies that the form-data (input) should not be validated when submitted.

Example

A form with a novalidate attribute:

<form action=”/action_page.php” novalidate>

Try it Yourself »


HTML Exercises

Test Yourself With Exercises

Exercise:

Add a submit button, and specify that the form should go to “/action_page.php”.

=”/action_page.php”>
Name:
<>

Start the Exercise


List of All

Attributes
AttributeDescription
accept-charsetSpecifies the character encodings used for form submission
actionSpecifies where to send the form-data when a form is submitted
autocompleteSpecifies whether a form should have autocomplete on or off
enctypeSpecifies how the form-data should be encoded when submitting it to the server (only for method=”post”)
methodSpecifies the HTTP method to use when sending form-data
nameSpecifies the name of the form
novalidateSpecifies that the form should not be validated when submitted
relSpecifies the relationship between a linked resource and the current document
targetSpecifies where to display the response that is received after submitting the form

HTML Form Elements


This chapter describes all the different HTML form elements.


The HTML

Elements

The HTML 

 element can contain one or more of the following form elements:

HTML Input Types

This chapter describes the different types for the HTML  element.


HTML Input Types

Here are the different input types you can use in HTML:

Tip: The default value of the type attribute is “text”.


Input Type Text

 defines a single-line text input field:

Example

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:


Input Type Password

 defines a password field:

Example

<form>
  <label for=”username”>Username:</label><br>
  <input type=”text” id=”username” name=”username”><br>
  <label for=”pwd”>Password:</label><br>
  <input type=”password” id=”pwd” name=”pwd”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

Username:

Password:

The characters in a password field are masked (shown as asterisks or circles).


ADVERTISEMENT

Input Type Submit

 defines a button for submitting form data to a form-handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form’s action attribute:

Example

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

If you omit the submit button’s value attribute, the button will get a default text:

Example

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit”>
</form>

Try it Yourself »


Input Type Reset

 defines a reset button that will reset all form values to their default values:

Example

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit” value=”Submit”>
  <input type=”reset”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

 

If you change the input values and then click the “Reset” button, the form-data will be reset to the default values.


Input Type Radio

 defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:

Example

<p>Choose your favorite Web language:</p>

<form>
  <input type=”radio” id=”html” name=”fav_language” value=”HTML”>
  <label for=”html”>HTML</label><br>
  <input type=”radio” id=”css” name=”fav_language” value=”CSS”>
  <label for=”css”>CSS</label><br>
  <input type=”radio” id=”javascript” name=”fav_language” value=”JavaScript”>
  <label for=”javascript”>JavaScript</label>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

 
 
 


Input Type Checkbox

 defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example

<form>
  <input type=”checkbox” id=”vehicle1″ name=”vehicle1″ value=”Bike”>
  <label for=”vehicle1″> I have a bike</label><br>
  <input type=”checkbox” id=”vehicle2″ name=”vehicle2″ value=”Car”>
  <label for=”vehicle2″> I have a car</label><br>
  <input type=”checkbox” id=”vehicle3″ name=”vehicle3″ value=”Boat”>
  <label for=”vehicle3″> I have a boat</label>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

 
 
 


Input Type Button

 defines a button:

Example

<input type=”button” onclick=”alert(‘Hello World!’)” value=”Click Me!”>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:


Input Type Color

The  is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.

Example

<form>
  <label for=”favcolor”>Select your favorite color:</label>
  <input type=”color” id=”favcolor” name=”favcolor”>
</form>

Try it Yourself »


Input Type Date

The  is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”birthday”>Birthday:</label>
  <input type=”date” id=”birthday” name=”birthday”>
</form>

Try it Yourself »

You can also use the min and max attributes to add restrictions to dates:

Example

<form>
  <label for=”datemax”>Enter a date before 1980-01-01:</label>
  <input type=”date” id=”datemax” name=”datemax” max=”1979-12-31″><br><br>
  <label for=”datemin”>Enter a date after 2000-01-01:</label>
  <input type=”date” id=”datemin” name=”datemin” min=”2000-01-02″>
</form>

Try it Yourself »


Input Type Datetime-local

The  specifies a date and time input field, with no time zone.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”birthdaytime”>Birthday (date and time):</label>
  <input type=”datetime-local” id=”birthdaytime” name=”birthdaytime”>
</form>

Try it Yourself »


Input Type Email

The  is used for input fields that should contain an e-mail address.

Depending on browser support, the e-mail address can be automatically validated when submitted.

Some smartphones recognize the email type, and add “.com” to the keyboard to match email input.

Example

<form>
  <label for=”email”>Enter your email:</label>
  <input type=”email” id=”email” name=”email”>
</form>

Try it Yourself »


Input Type File

The  defines a file-select field and a “Browse” button for file uploads.

Example

<form>
  <label for=”myfile”>Select a file:</label>
  <input type=”file” id=”myfile” name=”myfile”>
</form>

Try it Yourself »


Input Type Hidden

The  defines a hidden input field (not visible to a user).

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.

A hidden field often stores what database record that needs to be updated when the form is submitted.

Note: While the value is not displayed to the user in the page’s content, it is visible (and can be edited) using any browser’s developer tools or “View Source” functionality. Do not use hidden inputs as a form of security!

Example

<form>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <input type=”hidden” id=”custId” name=”custId” value=”3487″>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »


Input Type Month

The  allows the user to select a month and year.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”bdaymonth”>Birthday (month and year):</label>
  <input type=”month” id=”bdaymonth” name=”bdaymonth”>
</form>

Try it Yourself »


Input Type Number

The  defines a numeric input field.

You can also set restrictions on what numbers are accepted.

The following example displays a numeric input field, where you can enter a value from 1 to 5:

Example

<form>
  <label for=”quantity”>Quantity (between 1 and 5):</label>
  <input type=”number” id=”quantity” name=”quantity” min=”1″ max=”5″>
</form>

Try it Yourself »


Input Restrictions

Here is a list of some common input restrictions:

AttributeDescription
checkedSpecifies that an input field should be pre-selected when the page loads (for type=”checkbox” or type=”radio”)
disabledSpecifies that an input field should be disabled
maxSpecifies the maximum value for an input field
maxlengthSpecifies the maximum number of character for an input field
minSpecifies the minimum value for an input field
patternSpecifies a regular expression to check the input value against
readonlySpecifies that an input field is read only (cannot be changed)
requiredSpecifies that an input field is required (must be filled out)
sizeSpecifies the width (in characters) of an input field
stepSpecifies the legal number intervals for an input field
valueSpecifies the default value for an input field

You will learn more about input restrictions in the next chapter.

The following example displays a numeric input field, where you can enter a value from 0 to 100, in steps of 10. The default value is 30:

Example

<form>
  <label for=”quantity”>Quantity:</label>
  <input type=”number” id=”quantity” name=”quantity” min=”0″ max=”100″ step=”10″ value=”30″>
</form>

Try it Yourself »


Input Type Range

The  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 minmax, and step attributes:

Example

<form>
  <label for=”vol”>Volume (between 0 and 50):</label>
  <input type=”range” id=”vol” name=”vol” min=”0″ max=”50″>
</form>

Try it Yourself »


Input Type Search

The  is used for search fields (a search field behaves like a regular text field).

Example

<form>
  <label for=”gsearch”>Search Google:</label>
  <input type=”search” id=”gsearch” name=”gsearch”>
</form>

Try it Yourself »


Input Type Tel

The  is used for input fields that should contain a telephone number.

Example

<form>
  <label for=”phone”>Enter your phone number:</label>
  <input type=”tel” id=”phone” name=”phone” pattern=”[0-9]{3}-[0-9]{2}-[0-9]{3}”>
</form>

Try it Yourself »


Input Type Time

The  allows the user to select a time (no time zone).

Depending on browser support, a time picker can show up in the input field.

Example

<form>
  <label for=”appt”>Select a time:</label>
  <input type=”time” id=”appt” name=”appt”>
</form>

Try it Yourself »


Input Type Url

The  is used for input fields that should contain a URL address.

Depending on browser support, the url field can be automatically validated when submitted.

Some smartphones recognize the url type, and adds “.com” to the keyboard to match url input.

Example

<form>
  <label for=”homepage”>Add your homepage:</label>
  <input type=”url” id=”homepage” name=”homepage”>
</form>

Try it Yourself »


Input Type Week

The  allows the user to select a week and year.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”week”>Select a week:</label>
  <input type=”week” id=”week” name=”week”>
</form>

Try it Yourself »


HTML Exercises

Test Yourself With Exercises

Exercise:

In the form below, add an input field for text, with the name “username” .

<>

Start the Exercise


HTML Input Type Attribute

TagDescription
Specifies the input type to display

HTML Input Attributes

This chapter describes the different attributes for the HTML  element.


The value Attribute

The input value attribute specifies an initial value for an input field:

Example

Input fields with initial (default) values:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”>
</form>

Try it Yourself »


The readonly Attribute

The input readonly attribute specifies that an input field is read-only.

A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).

The value of a read-only input field will be sent when submitting the form!

Example

A read-only input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John” readonly><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”>
</form>

Try it Yourself »


The disabled Attribute

The input disabled attribute specifies that an input field should be disabled.

A disabled input field is unusable and un-clickable.

The value of a disabled input field will not be sent when submitting the form!

Example

A disabled input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John” disabled><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”>
</form>

Try it Yourself »


ADVERTISEMENT

The size Attribute

The input size attribute specifies the visible width, in characters, of an input field.

The default value for size is 20.

Note: The size attribute works with the following input types: text, search, tel, url, email, and password.

Example

Set a width for an input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” size=”50″><br>
  <label for=”pin”>PIN:</label><br>
  <input type=”text” id=”pin” name=”pin” size=”4″>
</form>

Try it Yourself »


The maxlength Attribute

The input maxlength attribute specifies the maximum number of characters allowed in an input field.

Note: When a maxlength is set, the input field will not accept more than the specified number of characters. However, this attribute does not provide any feedback. So, if you want to alert the user, you must write JavaScript code.

Example

Set a maximum length for an input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” size=”50″><br>
  <label for=”pin”>PIN:</label><br>
  <input type=”text” id=”pin” name=”pin” maxlength=”4″ size=”4″>
</form>

Try it Yourself »


The min and max Attributes

The input min and max attributes specify the minimum and maximum values for an input field.

The min and max attributes work with the following input types: number, range, date, datetime-local, month, time and week.

Tip: Use the max and min attributes together to create a range of legal values.

Example

Set a max date, a min date, and a range of legal values:

<form>
  <label for=”datemax”>Enter a date before 1980-01-01:</label>
  <input type=”date” id=”datemax” name=”datemax” max=”1979-12-31″><br><br>

  <label for=”datemin”>Enter a date after 2000-01-01:</label>
  <input type=”date” id=”datemin” name=”datemin” min=”2000-01-02″><br><br>

  <label for=”quantity”>Quantity (between 1 and 5):</label>
  <input type=”number” id=”quantity” name=”quantity” min=”1″ max=”5″>
</form>

Try it Yourself »


The multiple Attribute

The input multiple attribute specifies that the user is allowed to enter more than one value in an input field.

The multiple attribute works with the following input types: email, and file.

Example

A file upload field that accepts multiple values:

<form>
  <label for=”files”>Select files:</label>
  <input type=”file” id=”files” name=”files” multiple>
</form>

Try it Yourself »


The pattern Attribute

The input pattern attribute specifies a regular expression that the input field’s value is checked against, when the form is submitted.

The pattern attribute works with the following input types: text, date, search, url, tel, email, and password.

Tip: Use the global title attribute to describe the pattern to help the user.

Tip: Learn more about regular expressions in our JavaScript tutorial.

Example

An input field that can contain only three letters (no numbers or special characters):

<form>
  <label for=”country_code”>Country code:</label>
  <input type=”text” id=”country_code” name=”country_code”
  pattern=”[A-Za-z]{3}” title=”Three letter country code”
>

</form>

Try it Yourself »


The placeholder Attribute

The input placeholder attribute specifies a short hint that describes the expected value of an input field (a sample value or a short description of the expected format).

The short hint is displayed in the input field before the user enters a value.

The placeholder attribute works with the following input types: text, search, url, tel, email, and password.

Example

An input field with a placeholder text:

<form>
  <label for=”phone”>Enter a phone number:</label>
  <input type=”tel” id=”phone” name=”phone”
  placeholder=”123-45-678″
  pattern=”[0-9]{3}-[0-9]{2}-[0-9]{3}”
>

</form>

Try it Yourself »


The required Attribute

The input required attribute specifies that an input field must be filled out before submitting the form.

The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

Example

A required input field:

<form>
  <label for=”username”>Username:</label>
  <input type=”text” id=”username” name=”username” required>
</form>

Try it Yourself »


The step Attribute

The input step attribute specifies the legal number intervals for an input field.

Example: if step=”3″, legal numbers could be -3, 0, 3, 6, etc.

Tip: This attribute can be used together with the max and min attributes to create a range of legal values.

The step attribute works with the following input types: number, range, date, datetime-local, month, time and week.

Example

An input field with a specified legal number intervals:

<form>
  <label for=”points”>Points:</label>
  <input type=”number” id=”points” name=”points” step=”3″>
</form>

Try it Yourself »

Note: Input restrictions are not foolproof, and JavaScript provides many ways to add illegal input. To safely restrict input, it must also be checked by the receiver (the server)!


The autofocus Attribute

The input autofocus attribute specifies that an input field should automatically get focus when the page loads.

Example

Let the “First name” input field automatically get focus when the page loads:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” autofocus><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname”>
</form>

Try it Yourself »


The height and width Attributes

The input height and width attributes specify the height and width of an  element.

Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. Without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images load).

Example

Define an image as the submit button, with height and width attributes:

<form>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <input type=”image” src=”img_submit.gif” alt=”Submit” width=”48″ height=”48″>
</form>

Try it Yourself »


The list Attribute

The input list attribute refers to a  element that contains pre-defined options for an element.

Example

An element with pre-defined values in a:

<form>
  <input list=”browsers”>
  <datalist id=”browsers”>
    <option value=”Internet Explorer”>
    <option value=”Firefox”>
    <option value=”Chrome”>
    <option value=”Opera”>
    <option value=”Safari”>
  </datalist>
</form>

Try it Yourself »


The autocomplete Attribute

The input autocomplete attribute specifies whether a form or an input field should have autocomplete on or off.

Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.

The autocomplete attribute works with 

 and the following  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”>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <label for=”email”>Email:</label>
  <input type=”email” id=”email” name=”email” autocomplete=”off”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »

Tip: In some browsers you may need to activate an autocomplete function for this to work (Look under “Preferences” in the browser’s menu).


HTML Exercises

Test Yourself With Exercises

Exercise:

In the input field below, add placeholder that says “Your name here”.

>

Start the Exercise


HTML Form and Input Elements

TagDescription
 Defines an HTML form for user input
Defines an input control

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Input form* Attributes

This chapter describes the different form* attributes for the HTML  element.


The form Attribute

The input form attribute specifies the form the  element belongs to.

The value of this attribute must be equal to the id attribute of the

element it belongs to.

Example

An input field located outside of the HTML form (but still a part of the form):

<form action=”/action_page.php” id=”form1″>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <input type=”submit” value=”Submit”>
</form>

<label for=”lname”>Last name:</label>
<input type=”text” id=”lname” name=”lname” form=”form1″>

Try it Yourself »


The formaction Attribute

The input formaction attribute specifies the URL of the file that will process the input when the form is submitted.

Note: This attribute overrides the action attribute of the 

 element.

The formaction attribute works with the following input types: submit and image.

Example

An HTML form with two submit buttons, with different actions:

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <input type=”submit” value=”Submit”>
  <input type=”submit” formaction=”/action_page2.php” value=”Submit as Admin”>
</form>

Try it Yourself »


The formenctype Attribute

The input formenctype attribute specifies how the form-data should be encoded when submitted (only for forms with method=”post”).

Note: This attribute overrides the enctype attribute of the 

 element.

The formenctype attribute works with the following input types: submit and image.

Example

A form with two submit buttons. The first sends the form-data with default encoding, the second sends the form-data encoded as “multipart/form-data”:

<form action=”/action_page_binary.asp” method=”post”>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <input type=”submit” value=”Submit”>
  <input type=”submit” formenctype=”multipart/form-data”
  value=”Submit as Multipart/form-data”
>

</form>

Try it Yourself »


 

The formmethod Attribute

The input formmethod attribute defines the HTTP method for sending form-data to the action URL.

Note: This attribute overrides the method attribute of the 

 element.

The formmethod attribute works with the following input types: submit and image.

The form-data can be sent as URL variables (method=”get”) or as an HTTP post transaction (method=”post”).

Notes on the “get” method:

  • This method appends the form-data to the URL in name/value pairs
  • This method is useful for form submissions where a user want to bookmark the result
  • There is a limit to how much data you can place in a URL (varies between browsers), therefore, you cannot be sure that all of the form-data will be correctly transferred
  • Never use the “get” method to pass sensitive information! (password or other sensitive information will be visible in the browser’s address bar)

Notes on the “post” method:

  • This method sends the form-data as an HTTP post transaction
  • Form submissions with the “post” method cannot be bookmarked
  • The “post” method is more robust and secure than “get”, and “post” does not have size limitations

Example

A form with two submit buttons. The first sends the form-data with method=”get”. The second sends the form-data with method=”post”:

<form action=”/action_page.php” method=”get”>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <input type=”submit” value=”Submit using GET”>
  <input type=”submit” formmethod=”post” value=”Submit using POST”>
</form>

Try it Yourself »


The formtarget Attribute

The input formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form.

Note: This attribute overrides the target attribute of the 

 element.

The formtarget attribute works with the following input types: submit and image.

Example

A form with two submit buttons, with different target windows:

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <input type=”submit” value=”Submit”>
  <input type=”submit” formtarget=”_blank” value=”Submit to a new window/tab”>
</form>

Try it Yourself »


The formnovalidate Attribute

The input formnovalidate attribute specifies that an element should not be validated when submitted.

Note: This attribute overrides the novalidate attribute of the 

 element.

The formnovalidate attribute works with the following input types: submit.

Example

A form with two submit buttons (with and without validation):

<form action=”/action_page.php”>
  <label for=”email”>Enter your email:</label>
  <input type=”email” id=”email” name=”email”><br><br>
  <input type=”submit” value=”Submit”>
  <input type=”submit” formnovalidate=”formnovalidate”
  value=”Submit without validation”
>

</form>

Try it Yourself »


The novalidate Attribute

The novalidate attribute is a 

 attribute.

When present, novalidate specifies that all of the form-data should not be validated when submitted.

Example

Specify that no form-data should be validated on submit:

<form action=”/action_page.php” novalidate>
  <label for=”email”>Enter your email:</label>
  <input type=”email” id=”email” name=”email”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »


HTML Form and Input Elements

TagDescription
 Defines an HTML form for user input
Defines an input control

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Graphics

HTML Canvas Graphics

The HTML  element is used to draw graphics on a web page.

The graphic to the left is created with . It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.

 

What is HTML Canvas?

The HTML  element is used to draw graphics, on the fly, via JavaScript.

The  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  element.

Element     
 4.09.02.03.19.0

Canvas Examples

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.

The markup looks like this:

<canvas id=”myCanvas” width=”200″ height=”100″></canvas>

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.

Here is an example of a basic, empty canvas:

Example

<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #000000;”>
</canvas>

Try it Yourself »


 

Add a JavaScript

After creating the rectangular canvas area, you must add a JavaScript to do the drawing.

Here are some examples:

Draw a Line

Example

Try it Yourself »


Draw a Circle

Example

Try it Yourself »


Draw a Text

Example

Try it Yourself »


Stroke Text

Example

Try it Yourself »


Draw Linear Gradient

Example

Try it Yourself »


Draw Circular Gradient

Example

Try it Yourself »


Draw Image

Try it Yourself »


HTML Canvas Tutorial

To learn more about , please read our HTML Canvas Tutorial.

HTML SVG Graphics

SVG defines vector-based graphics in XML format.


What is SVG?

  • SVG stands for Scalable Vector Graphics
  • SVG is used to define graphics for the Web
  • SVG is a W3C recommendation

The HTML Element

The HTML  element is a container for SVG graphics.

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.


Browser Support

The numbers in the table specify the first browser version that fully supports the  element.

Element     
 4.09.03.03.210.1

SVG Circle

Example

<!DOCTYPE html>
<html>
<body>

<svg width=”100″ height=”100″>
  <circle cx=”50″ cy=”50″ r=”40″ stroke=”green” stroke-width=”4″ fill=”yellow” />
</svg>

</body>
</html>

Try it Yourself »


 

SVG Rectangle

Example

<svg width=”400″ height=”100″>
  <rect width=”400″ height=”100″ style=”fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)” />
</svg>

Try it Yourself »


SVG Rounded Rectangle

Example

<svg width=”400″ height=”180″>
  <rect x=”50″ y=”20″ rx=”20″ ry=”20″ width=”150″ height=”150″
  style=”fill:red;stroke:black;stroke-width:5;opacity:0.5″ /
>

</svg>

Try it Yourself »


SVG Star

Example

<svg width=”300″ height=”200″>
  <polygon points=”100,10 40,198 190,78 10,78 160,198″
  style=”fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;” /
>

</svg>

Try it Yourself »


SVG Logo

SVG

Example

<svg height=”130″ width=”500″>
  <defs>
    <linearGradient id=”grad1″ x1=”0%” y1=”0%” x2=”100%” y2=”0%”>
      <stop offset=”0%” style=”stop-color:rgb(255,255,0);stop-opacity:1″ />
      <stop offset=”100%” style=”stop-color:rgb(255,0,0);stop-opacity:1″ />
    </linearGradient>
  </defs>
  <ellipse cx=”100″ cy=”70″ rx=”85″ ry=”55″ fill=”url(#grad1)” />
  <text fill=”#ffffff” font-size=”45″ font-family=”Verdana” x=”50″ y=”86″>SVG</text>
  Sorry, your browser does not support inline SVG.
</svg>

Try it Yourself »


Differences Between SVG and Canvas

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:

CanvasSVG
  • 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

SVG Tutorial

To learn more about SVG, please read our SVG Tutorial.

HTML Media

HTML Multimedia

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, like images, music, sound, videos, records, films, animations, and more.

Web pages often contain multimedia elements of different types and 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, fonts, images, and 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: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.


Common Video Formats

Videoformats

There are many video formats out there.

The MP4, WebM, and Ogg formats are supported by HTML.

The MP4 format is recommended by YouTube.

FormatFileDescription
MPEG.mpg
.mpeg
MPEG. Developed by the Moving Pictures Expert Group. The first popular video format on the web. Not supported anymore in HTML.
AVI.aviAVI (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.wmvWMV (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.movQuickTime. Developed by Apple. Commonly used in video cameras and TV hardware. Plays well on Apple computers, but not in web browsers.
RealVideo.rm
.ram
RealVideo. Developed by Real Media to allow video streaming with low bandwidths. 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.oggTheora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML.
WebM.webmWebM. Developed by Mozilla, Opera, Adobe, and Google. Supported by HTML.
MPEG-4
or MP4
.mp4MP4. Developed by the Moving Pictures Expert Group. Commonly used in video cameras and TV hardware. Supported by all browsers and  recommended by YouTube. 

Note: Only MP4, WebM, and Ogg video are supported by the HTML standard.


 

Common Audio Formats

MP3 is the best 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.

FormatFileDescription
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.wmaWMA (Windows Media Audio). Developed by Microsoft. Plays well on Windows computers, but not in web browsers.
AAC.aacAAC (Advanced Audio Coding). Developed by Apple as the default format for iTunes. Plays well on Apple computers, but not in web browsers.
WAV.wavWAV. Developed by IBM and Microsoft. Plays well on Windows, Macintosh, and Linux operating systems. Supported by HTML.
Ogg.oggOgg. Developed by the Xiph.Org Foundation. Supported by HTML.
MP3.mp3MP3 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.mp4MP4 is a video format, but can also be used for audio. Supported by all browsers.

Note: Only MP3, WAV, and Ogg audio are supported by the HTML standard.

HTML Video


The HTML <video> element is used to show a video on a web page.



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>
Try it Yourself »

How it Works

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>
Try it Yourself »

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

Add muted after autoplay to let your video start playing automatically (but muted):

Example

<video width=”320″ height=”240″ autoplay muted>
  <source src=”movie.mp4″ type=”video/mp4″>
  <source src=”movie.ogg” type=”video/ogg”>
Your browser does not support the video tag.
</video>
Try it Yourself »

Browser Support

The numbers in the table specify the first browser version that fully supports the <video> element.

Element     
<video>4.09.03.54.010.5

ADVERTISEMENT

HTML Video Formats

There are three supported video formats: MP4, WebM, and Ogg. The browser support for the different formats is:

BrowserMP4WebMOgg
EdgeYESYESYES
ChromeYESYESYES
FirefoxYESYESYES
SafariYESYESNO
OperaYESYESYES

HTML Video – Media Types

File FormatMedia Type
MP4video/mp4
WebMvideo/webm
Oggvideo/ogg

HTML Video – Methods, Properties, and Events

The HTML DOM defines methods, properties, and events for the <video> element.

This allows you to load, play, and pause videos, as well as setting duration and volume.

There are also DOM events that can notify you when a video begins to play, is paused, etc.

Example: Using JavaScript


   

Video courtesy of Big Buck Bunny.

Try it Yourself »

For a full DOM reference, go to our HTML Audio/Video DOM Reference.


HTML Video Tags

TagDescription
<video>Defines a video or movie
<source>Defines multiple media resources for media elements, such as <video> and <audio>
<track>Defines text tracks in media players

HTML Audio


The HTML <audio> element is used to play an audio file on a web page.


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>
Try it Yourself »

HTML Audio – How It Works

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> Autoplay

To start an audio file automatically, use the autoplay attribute:

Example

<audio controls autoplay>
  <source src=”horse.ogg” type=”audio/ogg”>
  <source src=”horse.mp3″ type=”audio/mpeg”>
Your browser does not support the audio element.
</audio>
Try it Yourself »

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

Add muted after autoplay to let your audio file start playing automatically (but muted):

Example

<audio controls autoplay muted>
  <source src=”horse.ogg” type=”audio/ogg”>
  <source src=”horse.mp3″ type=”audio/mpeg”>
Your browser does not support the audio element.
</audio>
Try it Yourself »

Browser Support

The numbers in the table specify the first browser version that fully supports the <audio> element.

Element     
<audio>4.09.03.54.010.5

ADVERTISEMENT

HTML Audio Formats

There are three supported audio formats: MP3, WAV, and OGG. The browser support for the different formats is: 

BrowserMP3WAVOGG
Edge/IEYESYES*YES*
ChromeYESYESYES
FirefoxYESYESYES
SafariYESYESNO
OperaYESYESYES

*From Edge 79


HTML Audio – Media Types

File FormatMedia Type
MP3audio/mpeg
OGGaudio/ogg
WAVaudio/wav

HTML Audio – Methods, Properties, and Events

The HTML DOM defines 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.

For a full DOM reference, go to our HTML Audio/Video DOM Reference.


HTML Audio Tags

TagDescription
<audio>Defines sound content
<source>Defines multiple media resources for media elements, such as <video> and <audio>

HTML Plug-ins


Plug-ins are computer programs that extend the standard functionality of the browser.


Plug-ins

Plug-ins were designed to be used for many different purposes:

  • To run Java applets
  • To run Microsoft ActiveX controls
  • To display Flash movies
  • To display maps
  • To scan for viruses
  • To verify a bank id

Warning !

Most browsers no longer support Java Applets and Plug-ins.

ActiveX controls are no longer supported in any browsers.

The support for Shockwave Flash has also been turned off in modern browsers.


The <object> Element

The <object> element is supported by all browsers.

The <object> element defines an embedded object within an HTML document.

It was designed to embed plug-ins (like Java applets, PDF readers, and Flash Players) in web pages, but can also be used to include HTML in HTML:

Example

<object width=”100%” height=”500px” data=”snippet.html”></object>
Try it Yourself »

Or images if you like:

Example

<object data=”audi.jpeg”></object>
Try it Yourself »

ADVERTISEMENT

The <embed> Element

The <embed> element is supported in all major browsers.

The <embed> element also defines an embedded object within an HTML document.

Web browsers have supported the <embed> element for a long time. However, it has not been a part of the HTML specification before HTML5.

Example

<embed src=”audi.jpeg”>
Try it Yourself »

Note that the <embed> element does not have a closing tag. It can not contain alternative text.

The <embed> element can also be used to include HTML in HTML:

Example

<embed width=”100%” height=”500px” src=”snippet.html”>
Try it Yourself »

HTML YouTube Videos


The easiest way to play videos in HTML, is to use YouTube.


Struggling with Video Formats?

Converting videos to different formats can be difficult and time-consuming.

An easier solution is to let YouTube play the videos in your web page.


YouTube Video Id

YouTube will display an id (like tgbNymZ7vqY), when you save (or play) a video.

You can use this id, and refer to your video in the HTML code.


Playing a YouTube Video in HTML

To play your video on a web page, do the following:

  • Upload the video to YouTube
  • Take a note of the video id
  • Define an <iframe> element in your web page
  • Let the src attribute point to the video URL
  • Use the width and height attributes to specify the dimension of the player
  • Add any other parameters to the URL (see below)

Example

<iframe width=”420″ height=”315″
src=”https://www.youtube.com/embed/tgbNymZ7vqY”
>

</iframe>
Try it Yourself »

YouTube Autoplay + Mute

You can let your video start playing automatically when a user visits the page, by adding autoplay=1 to the YouTube URL. However, automatically starting a video is annoying for your visitors!

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

Add mute=1 after autoplay=1 to let your video start playing automatically (but muted).

YouTube – Autoplay + Muted

<iframe width=”420″ height=”315″
src=”https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1&mute=1″
>

</iframe>
Try it Yourself »

ADVERTISEMENT

YouTube Playlist

A comma separated list of videos to play (in addition to the original URL).


YouTube Loop

Add loop=1 to let your video loop forever.

Value 0 (default): The video will play only once.

Value 1: The video will loop (forever).

YouTube – Loop

<iframe width=”420″ height=”315″
src=”https://www.youtube.com/embed/tgbNymZ7vqY?playlist=tgbNymZ7vqY&loop=1″
>

</iframe>
Try it Yourself »

YouTube Controls

Add controls=0 to not display controls in the video player.

Value 0: Player controls does not display.

Value 1 (default): Player controls display.

YouTube – Controls

<iframe width=”420″ height=”315″
src=”https://www.youtube.com/embed/tgbNymZ7vqY?controls=0″
>

</iframe>
Try it Yourself »

HTML APIs

HTML Geolocation API


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 smartphones.


Browser Support

The numbers in the table specify the first browser version that fully supports Geolocation.

API     
Geolocation5.0 – 49.0 (http)
50.0 (https)
9.03.55.016.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 +
  
Longitude: “
 + position.coords.longitude;
}
</script>

Try it Yourself »

Example explained:

  • Check if Geolocation is supported
  • 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;
  }
}

Try it Yourself »


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:

PropertyReturns
coords.latitudeThe latitude as a decimal number (always returned)
coords.longitudeThe longitude as a decimal number (always returned)
coords.accuracyThe accuracy of position (always returned)
coords.altitudeThe altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracyThe altitude accuracy of position (returned if available)
coords.headingThe heading as degrees clockwise from North (returned if available)
coords.speedThe speed in meters per second (returned if available)
timestampThe 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 smartphone):

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 +
  
Longitude: “
 + position.coords.longitude;
}
</script>

Try it Yourself »

HTML Drag and Drop API


In HTML, any element can be dragged and dropped.


Example

W3Schools
 

Drag the W3Schools image into the rectangle.


Drag and Drop

Drag and drop is a very common feature. It is when you “grab” an object and drag it to a different location.


Browser Support

The numbers in the table specify the first browser version that fully supports Drag and Drop.

API     
Drag and Drop4.09.03.56.012.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>

<div id=”div1″ ondrop=”drop(event)” ondragover=”allowDrop(event)”></div>

<img id=”drag1″ src=”img_logo.gif” draggable=”true” ondragstart=”drag(event)” width=”336″ height=”69″>

</body>
</html>

Try it Yourself »

It might seem complicated, but lets go through all the different parts of a drag and drop event.


Make an Element Draggable

First of all: To make an element draggable, set the draggable attribute to true:

“true”>

What to Drag – ondragstart and setData()

Then, specify what should happen when the element is dragged.

In the example above, the ondragstart attribute calls a function, drag(event), that specifies what data to be dragged.

The dataTransfer.setData() method sets the data type and the value of the dragged data:

function drag(ev) {
  ev.dataTransfer.setData(“text”, ev.target.id);
}

In this case, the data type is “text” and the value is the id of the draggable element (“drag1”).


Where to Drop – ondragover

The ondragover event specifies where the dragged data can be dropped.

By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.

This is done by calling the event.preventDefault() method for the ondragover event:

event.preventDefault()

Do the Drop – ondrop

When the dragged data is dropped, a drop event occurs.

In the example above, the ondrop attribute calls a function, drop(event):

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData(“text”);
  ev.target.appendChild(document.getElementById(data));
}

Code explained:

  • Call preventDefault() to prevent the browser default handling of the data (default is open as link on drop)
  • Get the dragged data with the dataTransfer.getData() method. This method will return any data that was set to the same type in the setData() method
  • The dragged data is the id of the dragged element (“drag1”)
  • Append the dragged element into the drop element

More Examples

Example

How to drag (and drop) an image back and forth between two

HTML Web Storage API


HTML web storage; better than cookies.


What is HTML Web Storage?

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 Storage4.08.03.54.011.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”);

Try it Yourself »

Example explained:

  • 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).”;

Try it Yourself »


The sessionStorage Object

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.”;

Try it Yourself »

HTML Web Workers API

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 Workers4.010.03.54.011.5

HTML Web Workers Example

The example below creates a simple web worker that count numbers in the background:

Example

Count numbers:

 

Try it Yourself »


Check Web Worker Support

Before creating a web worker, check whether the user’s browser supports it:

if (typeof(Worker) !== “undefined”) {
  // Yes! Web worker support!
  // Some code…..
} else {
  // Sorry! No Web Worker support..
}

Create a Web Worker File

Now, let’s create our web worker in an external JavaScript.

Here, we create a script that counts. The script is stored in the “demo_workers.js” file:

var i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout(“timedCount()”,500);
}

timedCount();

The important part of the code above is the postMessage() method – which is used to post a message back to the HTML page.

Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.


Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page.

The following lines checks if the worker already exists, if not – it creates a new web worker object and runs the code in “demo_workers.js”:

if (typeof(w) == “undefined”) {
  w = new Worker(“demo_workers.js”);
}

Then we can send and receive messages from the web worker.

Add an “onmessage” event listener to the web worker.

w.onmessage = function(event){
  document.getElementById(“result”).innerHTML = event.data;
};

When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.


Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.

To terminate a web worker, and free browser/computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id=”result”></output></p>
<button onclick=”startWorker()”>Start Worker</button>
<button onclick=”stopWorker()”>Stop Worker</button>

<script>
var w;

function startWorker() {
  if (typeof(Worker) !== “undefined”) {
    if (typeof(w) == “undefined”) {
      w = new Worker(“demo_workers.js”);
    }
    w.onmessage = function(event) {
      document.getElementById(“result”).innerHTML = event.data;
    };
  } else {
    document.getElementById(“result”).innerHTML = “Sorry! No Web Worker support.”;
  }
}

function stopWorker() {
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>

Try it Yourself »


Web Workers and the DOM

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

HTML SSE API

Server-Sent Events (SSE) 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     
SSE6.079.06.05.011.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 + 
;
};

Try it Yourself »

Example explained:

  • Create a new EventSource object, and specify the URL of the page sending the updates (in this example “demo_sse.php”)
  • Each time an update is received, the onmessage event occurs
  • When an onmessage event occurs, put the received data into the element with id=”result”

Check Server-Sent Events Support

In the tryit example above there were some extra lines of code to check browser support for server-sent events:

if(typeof(EventSource) !== “undefined”) {
  // Yes! Server-sent events support!
  // Some code…..
} else {
  // Sorry! No server-sent events support..
}

Server-Side Code Example

For the example above to work, you need a server capable of sending data updates (like PHP or ASP).

The server-side event stream syntax is simple. Set the “Content-Type” header to “text/event-stream”. Now you can start sending event streams.

Code in PHP (demo_sse.php):

header(‘Content-Type: text/event-stream’);
header(‘Cache-Control: no-cache’);

$time = date(‘r’);
echo “data: The server time is: {$time}\n\n”;
flush();
?>

Code in ASP (VB) (demo_sse.asp):

<%
Response.ContentType = “text/event-stream”
Response.Expires = -1
Response.Write(“data: The server time is: ” & now())
Response.Flush()
%>

Code explained:

  • Set the “Content-Type” header to “text/event-stream”
  • Specify that the page should not cache
  • Output the data to send (Always start with “data: “)
  • Flush the output data back to the web page

The EventSource Object

In the examples above we used the onmessage event to get messages. But other events are also available:

EventsDescription
onopenWhen a connection to the server is opened
onmessageWhen a message is received
onerrorWhen an error occurs

HTML Examples

HTML Examples

Examples explained

Examples explained

Examples explained


HTML Text Formatting

Examples explained

Examples explained

Examples explained

Examples explained

Examples explained

Examples explained

Examples explained

Examples explained

HTML Quiz

You can test your HTML skills with W3Schools’ Quiz.


The Test

The test contains 40 questions and there is no time limit. 

The test is not official, it’s just a nice way to see how much you know, or don’t know, about HTML.

Count Your Score

You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 40 points.

Start the Quiz

Good luck!

Start the HTML Quiz ❯

If you don’t know HTML, we suggest that you read our HTML Tutorial from scratch.

HTML Exercises

You can test your HTML skills with W3Schools’ Exercises.


Exercises

We have gathered a variety of HTML exercises (with answers) for each HTML Chapter.

Try to solve an exercise by editing some code. Get a “hint” if you’re stuck, or show the answer to see what you’ve done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start HTML Exercises

Good luck!

Start HTML Exercises ❯

If you don’t know HTML, we suggest that you read our HTML Tutorial from scratch.

You Have Learned HTML, Now What?

HTML Summary

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.

For more information on HTML, please take a look at our HTML examples and our HTML reference.

You can also test your HTML skills with HTML Exercises and HTML Quizzes.


Now You Know HTML, What’s Next?


Learn CSS

CSS lets you style your HTML pages.

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

HTML Accessibility

Always write HTML code with accessibility in mind!

Provide the user a good way to navigate and interact with your site. Make your HTML code as semantic as possible.


Semantic HTML

Semantic HTML means using correct HTML elements for their correct purpose as much as possible. Semantic elements are elements with a meaning; if you need a button, use the  element (and not a 

 element).

Semantic

<button>Report an Error</button>

Try it Yourself »

Non-semantic

<div>Report an Error</div>

Try it Yourself »

Semantic HTML gives context to screen readers, which read the contents of a page out loud.

With the button example in mind:

  • buttons have more suitable styling by default
  • a screen reader identifies it as a button
  • focusable
  • clickable

A button is also accessible for people relying on keyboard-only navigation; it can be clickable with both mouse and keys, and it can be tabbed between (using the tab key on the keyboard).

Examples of non-semantic elements: 

 and  – Tells nothing about its content.

Examples of semantic elements: 

, and  – Clearly defines its content.Headings Are ImportantHeadings are defined with the  to 

 

 tags:

Example

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>

Try it Yourself »

Search engines use the headings to index the structure and content of your web pages.Users skim your pages by its headings. It is important to use headings to show the document structure and the relationships between different sections.Screen readers also use headings as a navigational tool. The different types of heading specify the outline of the page.  headings should be used for main headings, followed by 

 

 headings, then the less important 

 

, and so on.

Note: Use HTML headings for headings only. Don’t use headings to make text BIG or bold.

ADVERTISEMENT

Alternative TextThe 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=”A narrow city street with flowers in Chania”>

Try it Yourself »

If a browser cannot find an image, it will display the value of the alt attribute:

Example

<img src=”wrongname.gif” alt=”A narrow city street with flowers in Chania”>

Try it Yourself »

Declare the LanguageYou should always include the lang attribute inside the  tag, to declare the language of the Web page. This is meant to assist search engines and browsers.The following example specifies English as the language:

<!DOCTYPE html>
<html lang=”en”>
<body>

</body>
</html>

Use Clear LanguageAlways use a clear language, that is easy to understand. Also try to avoid characters that cannot be read clearly by a screen reader. For example:

  • Keep sentences as short as possible
  • Avoid dashes. Instead of writing 1-3, write 1 to 3
  • Avoid abbreviations. Instead of writing Feb, write February
  • Avoid slang words

Create Good Link TextA link text should explain clearly what information the reader will get by clicking on that link.Examples of good and bad links:

Note: This page is an introduction in web accessibility. Visit our Accessibility Tutorial for more details.

HTML References

HTML Element Reference


HTML Tags Ordered Alphabetically

 

element 
TagDescription
Defines a comment
 Defines the document type
 Defines a hyperlink
 Defines an abbreviation or an acronym
 Not supported in HTML5. Use  instead.
Defines an acronym

 

 
Defines contact information for the author/owner of a document
 Not supported in HTML5. Use  or  instead.
Defines an embedded applet

Defines an area inside an image map

Defines an article

Defines content aside from the page content
Defines embedded sound content
Defines bold text
Specifies the base URL/target for all relative URLs in a document
Not supported in HTML5. Use CSS instead.
Specifies a default color, size, and font for all text in a document
Isolates a part of text that might be formatted in a different direction from other text outside it
Overrides the current text direction
Not supported in HTML5. Use CSS instead.
Defines big text

Defines a section that is quoted from another source
Defines the document’s body

Defines a single line break
Defines a clickable button
Used to draw graphics, on the fly, via scripting (usually JavaScript)

Defines a table caption
Not supported in HTML5. Use CSS instead.
Defines centered text
Defines the title of a work
Defines a piece of computer code

Specifies column properties for each column within a

Specifies a group of one or more columns in a table for formatting
Adds a machine-readable translation of a given content
Specifies a list of pre-defined options for input controls

Defines a description/value of a term in a description list
Defines text that has been deleted from a document

Defines additional details that the user can view or hide
Specifies a term that is going to be defined within the content
Defines a dialog box or window

Not supported in HTML5. Use 

     instead.
    Defines a directory list

Defines a section in a document

Defines a description list

Defines a term/name in a description list
Defines emphasized text 
Defines a container for an external application

Groups related elements in a form

Defines a caption for a

element

Specifies self-contained content
Not supported in HTML5. Use CSS instead.
Defines font, color, and size for text

Defines a footer for a document or section

Defines an HTML form for user input
Not supported in HTML5.
Defines a window (a frame) in a frameset
Not supported in HTML5.
Defines a set of frames

to

Defines HTML headings
Contains metadata/information for the document

Defines a header for a document or section


Defines a thematic change in the content
Defines the root of an HTML document
Defines a part of text in an alternate voice or mood

HTML Element Reference – By Category


Basic HTML

TagDescription
 Defines the document type
 Defines an HTML document
 Contains metadata/information for the document

HTML Reference – Browser Support


HTML Reference With Browser Support

The table below lists all HTML elements and their attributes, along with browser support:

      
 YesYesYesYesYes
download14.018.020.010.115.0
hrefYesYesYesYesYes
hreflangYesYesYesYesYes
mediaYesYesYesYesYes
pingYesNoYesNoYes
referrerpolicy51.079.050.011.138.0
relYesYesYesYesYes
targetYesYesYesYesYes
typeYesYesYesYesYes
      
 YesYesYesYesYes
      

 

 
YesYesYesYesYes
      

 

YesYesYesYesYes
altYesYesYesYesYes
coordsYesYesYesYesYes
downloadYesYesYesYesYes
hrefYesYesYesYesYes
hreflangYesYesYesYesYes
mediaYesYesYesYesYes
referrerpolicy51.079.050.011.138.0
relYesYesYesYesYes
shapeYesYesYesYesYes
targetYesYesYesYesYes
typeYesYesYesYesYes
      

 

6.09.04.05.011.1
      

 

6.09.04.05.011.1
      
4.0 9.0 3.5 4.0 11.5
autoplay 4.0 9.0 3.5 4.0 11.5
controls 4.0 9.0 3.5 4.0 11.5
loop 4.0 9.0 3.5 4.0 11.5
muted 4.0 10.0 11.0 7.1 11.5
preload 4.0 9.0 4.0 4.0 11.5
src 4.0 9.0 3.5 4.0 11.5
           
Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
href Yes Yes Yes Yes Yes
target Yes Yes Yes Yes Yes
           
16.0 79.0 10.0 No 15.0
           
Yes Yes Yes Yes Yes
dir Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
cite Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
autofocus 5.0 10.0 4.0 5.0 9.6
disabled Yes Yes Yes Yes Yes
form 10.0 16.0 4.0 5.1 9.5
formaction 9.0 10.0 4.0 5.1 15.0
formenctype 9.0 10.0 4.0 5.1 11.5
formmethod 9.0 10.0 4.0 5.1 15.0
formnovalidate 6.0 11.0 4.0 Yes Yes
formtarget 9.0 10.0 4.0 5.1 10.6
name Yes Yes Yes Yes Yes
type Yes Yes Yes Yes Yes
value Yes Yes Yes Yes Yes
           
4.0 9.0 2.0 3.1 9.0
height 4.0 9.0 2.0 3.1 9.0
width 4.0 9.0 2.0 3.1 9.0
           

Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
span Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
span Yes Yes Yes Yes Yes
           
62.0 13.0 22.0 No 49.0
value 62.0 13.0 22.0 No 49.0
           
20.0 10.0 4.0 12.1 9.5
           

Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
cite Yes Yes Yes Yes Yes
datetime Yes Yes Yes Yes Yes
           

12.0  79.0 49.0 6.0 15.0
open 12.0 79.0 49.0 6.0 15.0
           
Yes Yes Yes Yes Yes
           
37.0 79.0 53.0* No 24.0
open 37.0 79.0 53.0* No 24.0

* Not supported by default, but can be enabled in about:config (set dom.dialog_element.enabled to true).

           

Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
height Yes Yes Yes Yes Yes
src Yes Yes Yes Yes Yes
type Yes Yes Yes Yes Yes
width Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
disabled Yes Yes Yes 6.0 Yes
form Yes Yes Yes Yes Yes
name Yes 11.0 Yes Yes Yes
           

8.0 9.0 4.0 5.1 11.0
           

8.0 9.0 4.0 5.1 11.0
           

5.0 9.0 4.0 5.0 11.1
           

Yes Yes Yes Yes Yes
accept-charset Yes Yes Yes Yes Yes
action Yes Yes Yes Yes Yes
autocomplete Yes Yes 4.0 5.2 15.0
enctype Yes Yes Yes Yes Yes
method Yes Yes Yes Yes Yes
name Yes Yes Yes Yes Yes
novalidate Yes 10.0 4.0 10.1 15.0
rel Yes Yes Yes Yes Yes
target Yes Yes Yes Yes Yes
           

Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
           

5.0  9.0 4.0 5.0 11.1
           


Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
xmlns Yes Yes Yes Yes Yes
           
Yes Yes Yes Yes Yes
           

HTML Attribute Reference


HTML Attribute Reference

The table below lists all HTML attributes and what elements they can be used within:

AttributesBelongs toDescription
acceptSpecifies the types of files that the server accepts (only for type=”file”)
accept-charset

 

Specifies the character encodings that are to be used for the form submission
accesskeyGlobal AttributesSpecifies a shortcut key to activate/focus an element
action

 

Specifies where to send the form-data when a form is submitted
alignNot supported in HTML 5.Specifies the alignment according to surrounding elements. Use CSS instead
alt

 

Specifies an alternate text when the original element fails to display
async

HTML Global Attributes


HTML Global Attributes

The global attributes are attributes that can be used with all HTML elements.

AttributeDescription
accesskeySpecifies a shortcut key to activate/focus an element
classSpecifies one or more classnames for an element (refers to a class in a style sheet)
contenteditableSpecifies whether the content of an element is editable or not
data-*Used to store custom data private to the page or application
dirSpecifies the text direction for the content in an element
draggableSpecifies whether an element is draggable or not
hiddenSpecifies that an element is not yet, or is no longer, relevant
idSpecifies a unique id for an element
langSpecifies the language of the element’s content
spellcheckSpecifies whether the element is to have its spelling and grammar checked or not
styleSpecifies an inline CSS style for an element
tabindexSpecifies the tabbing order of an element
titleSpecifies extra information about an element
translateSpecifies whether the content of an element should be translated or not

HTML Event Attributes


Global Event Attributes

HTML has the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element.

To learn more about programming events, please visit our JavaScript tutorial.

Below are the global event attributes that can be added to HTML elements to define event actions.


Window Event Attributes

Events triggered for the window object (applies to thetag):

AttributeValueDescription
onafterprintscriptScript to be run after the document is printed
onbeforeprintscriptScript to be run before the document is printed
onbeforeunloadscriptScript to be run when the document is about to be unloaded
onerrorscriptScript to be run when an error occurs
onhashchangescriptScript to be run when there has been changes to the anchor part of the a URL
onloadscriptFires after the page is finished loading
onmessagescriptScript to be run when the message is triggered
onofflinescriptScript to be run when the browser starts to work offline
ononlinescriptScript to be run when the browser starts to work online
onpagehidescriptScript to be run when a user navigates away from a page
onpageshowscriptScript to be run when a user navigates to a page
onpopstatescriptScript to be run when the window’s history changes
onresizescriptFires when the browser window is resized
onstoragescriptScript to be run when a Web Storage area is updated
onunloadscriptFires once a page has unloaded (or the browser window has been closed)

 

Form Events

Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most used in form elements):

AttributeValueDescription
onblurscriptFires the moment that the element loses focus
onchangescriptFires the moment when the value of the element is changed
oncontextmenuscriptScript to be run when a context menu is triggered
onfocusscriptFires the moment when the element gets focus
oninputscriptScript to be run when an element gets user input
oninvalidscriptScript to be run when an element is invalid
onresetscriptFires when the Reset button in a form is clicked
onsearchscriptFires when the user writes something in a search field (for <input=”search”>)
onselectscriptFires after some text has been selected in an element
onsubmitscriptFires when a form is submitted

Keyboard Events

AttributeValueDescription
onkeydownscriptFires when a user is pressing a key
onkeypressscriptFires when a user presses a key
onkeyupscriptFires when a user releases a key

Mouse Events

AttributeValueDescription
onclickscriptFires on a mouse click on the element
ondblclickscriptFires on a mouse double-click on the element
onmousedownscriptFires when a mouse button is pressed down on an element
onmousemovescriptFires when the mouse pointer is moving while it is over an element
onmouseoutscriptFires when the mouse pointer moves out of an element
onmouseoverscriptFires when the mouse pointer moves over an element
onmouseupscriptFires when a mouse button is released over an element
onmousewheelscriptDeprecated. Use the onwheel attribute instead
onwheelscriptFires when the mouse wheel rolls up or down over an element

Drag Events

AttributeValueDescription
ondragscriptScript to be run when an element is dragged
ondragendscriptScript to be run at the end of a drag operation
ondragenterscriptScript to be run when an element has been dragged to a valid drop target
ondragleavescriptScript to be run when an element leaves a valid drop target
ondragoverscriptScript to be run when an element is being dragged over a valid drop target
ondragstartscriptScript to be run at the start of a drag operation
ondropscriptScript to be run when dragged element is being dropped
onscrollscriptScript to be run when an element’s scrollbar is being scrolled

Clipboard Events

AttributeValueDescription
oncopyscriptFires when the user copies the content of an element
oncutscriptFires when the user cuts the content of an element
onpastescriptFires 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

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):

For a full overview of HTML colors, visit our colors tutorial.