Learn HTML: Beginner's Guide
Learn HTML: Beginner's Guide
Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Try it Yourself »
HTML Examples
In this HTML tutorial, you will find more than 200 examples. With our online
"Try it Yourself" editor, you can edit and test each example yourself!
Go to HTML Examples!
HTML Exercises
Many chapters in this tutorial end with an exercise where you can check your
level of knowledge.
Exercise?
What is a correct syntax for an HTML hyperlink?
Submit Answer »
See all HTML Exercises
What is HTML?
HTML stands for Hyper Text Markup Language
HTML is the standard markup language for creating Web pages
HTML describes the structure of a Web page
HTML consists of a series of elements
HTML elements tell the browser how to display the content
HTML elements label pieces of content such as "this is a heading", "this
is a paragraph", "this is a link", etc.
</body>
</html>
Try it Yourself »
Example Explained
The <!DOCTYPE html> declaration defines that this document is an
HTML5 document
The <html> element is the root element of an HTML page
The <head> element contains meta information about the HTML page
The <title> element specifies a title for the HTML page (which is
shown in the browser's title bar or in the page's tab)
The <body> element defines the document's body, and is a container
for all the visible contents, such as headings, paragraphs, images,
hyperlinks, tables, lists, etc.
The <h1> element defines a large heading
The <p> element defines a paragraph
The HTML element is everything from the start tag to the end tag:
Note: Some HTML elements have no content (like the <br> element). These
elements are called empty elements. Empty elements do not have an end
tag!
Web Browsers
The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML
documents and display them correctly.
A browser does not display the HTML tags, but uses them to determine how
to display the document:
HTML Page Structure
Below is a visualization of an HTML page structure:
<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Note: The content inside the <body> section will be displayed in a browser.
The content inside the <title> element will be shown in the browser's title
bar or in the page's tab.
HTML History
Since the early days of the World Wide Web, there have been many versions
of HTML:
Year Version
However, for learning HTML we recommend a simple text editor like Notepad
(PC) or TextEdit (Mac).
We believe that using a simple text editor is a good way to learn HTML.
Follow the steps below to create your first web page with Notepad or
TextEdit.
Open the Start Screen (the window symbol at the bottom left on your
screen). Type Notepad.
Windows 7 or earlier:
Open Start > Programs > Accessories > Notepad
Then under "Open and Save", check the box that says "Display HTML files as
HTML code instead of formatted text".
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Step 3: Save the HTML Page
Save the file on your computer. Select File > Save as in the Notepad menu.
Name the file "[Link]" and set the encoding to UTF-8 (which is the
preferred encoding for HTML files).
Tip: You can use either .htm or .html as file extension. There is no difference;
it is up to you.
Don't worry if we use tags you have not learned about yet.
HTML Documents
All HTML documents must start with a document type declaration: <!DOCTYPE
html>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
It must only appear once, at the top of the page (before any HTML tags).
<!DOCTYPE html>
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important
heading:
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
Try it Yourself »
HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
Try it Yourself »
HTML Links
HTML links are defined with the <a> tag:
Example
<a href="[Link] is a link</a>
Try it Yourself »
HTML Images
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are provided as
attributes:
Example
<img src="[Link]" alt="[Link]" width="104" height="
142">
Try it Yourself »
Exercise?
What is a correct HTML markup for the document type declaration?
<!DOCTYPE html>
DOCTYPE html;
--DOCTYPE html;
Submit Answer »
An HTML element is defined by a start tag, some content, and an end tag.
HTML Elements
The HTML element is everything from the start tag to the end tag:
Note: Some HTML elements have no content (like the <br> element). These
elements are called empty elements. Empty elements do not have an end
tag!
Nested HTML Elements
HTML elements can be nested (this means that elements can contain other
elements).
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
Example Explained
The <html> element is the root element and it defines the whole HTML
document.
<body>
</body>
Then, inside the <body> element there are two other elements: <h1> and <p>:
<h1>My First Heading</h1>
<p>My first paragraph.</p>
Example
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph
</body>
</html>
Try it Yourself »
The <br> tag defines a line break, and is an empty element without a closing
tag:
Example
<p>This is a <br> paragraph with a line break.</p>
Try it Yourself »
Exercise?
True or False. Empty elements must have a close tag.
True
False
Submit Answer »
HTML Attributes
All HTML elements can have attributes
Attributes provide additional information about elements
Attributes are always specified in the start tag
Attributes usually come in name/value pairs like: name="value"
Example
<a href="[Link] W3Schools</a>
Try it Yourself »
You will learn more about links in our HTML Links chapter.
Example
<img src="img_girl.jpg">
Try it Yourself »
There are two ways to specify the URL in the src attribute:
2. Relative URL - Links to an image that is hosted within the website. Here,
the URL does not include the domain name. If the URL begins without a slash,
it will be relative to the current page. Example: src="img_girl.jpg". If the URL
begins with a slash, it will be relative to the domain. Example:
src="/images/img_girl.jpg".
Tip: It is almost always best to use relative URLs. They will not break if you
change domain.
Example
<img src="img_girl.jpg" width="500" height="600">
Try it Yourself »
Example
<img src="img_girl.jpg" alt="Girl with a jacket">
Try it Yourself »
Example
See what happens if we try to display an image that does not exist:
You will learn more about images in our HTML Images chapter.
You will learn more about styles in our HTML Styles chapter.
<!DOCTYPE html>
<html lang="en">
<body>
...
</body>
</html>
Country codes can also be added to the language code in the lang attribute.
So, the first two characters define the language of the HTML page, and the
last two characters define the country.
The following example specifies English as the language and United States as
the country:
<!DOCTYPE html>
<html lang="en-US">
<body>
...
</body>
</html>
You can see all the language codes in our HTML Language Code Reference.
The value of the title attribute will be displayed as a tooltip when you mouse
over the element:
Example
<p title="I'm a tooltip">This is a paragraph.</p>
Try it Yourself »
The title attribute (and all other attributes) can be written with uppercase or
lowercase like title or TITLE.
Good:
<a href="[Link] our HTML
tutorial</a>
Bad:
<a href=[Link] our HTML
tutorial</a>
Sometimes you have to use quotes. This example will not display the title
attribute correctly, because it contains a space:
Example
<p title=Description of W3Schools>
Try it Yourself »
At W3Schools we always use quotes around attribute values.
In some situations, when the attribute value itself contains double quotes, it
is necessary to use single quotes:
Or vice versa:
Chapter Summary
All HTML elements can have attributes
The href attribute of <a> specifies the URL of the page the link goes to
The src attribute of <img> specifies the path to the image to be
displayed
The width and height attributes of <img> provide size information for
images
The alt attribute of <img> provides an alternate text for an image
The style attribute is used to add styles to an element, such as color,
font, size, and more
The lang attribute of the <html> tag declares the language of the Web
page
The title attribute defines some extra information about an element
Exercise?
Which of the following is a correct syntax for using an HTML attribute?
<img src='img_girl.jpg'>
<img src('img_girl.jpg')>
<img src:'img_girl.jpg'>
Submit Answer »
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Try it Yourself »
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important
heading.
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 »
Note: Browsers automatically add some white space (a margin) before and
after a heading.
<h1> headings should be used for main headings, followed by <h2> headings,
then the less important <h3>, and so on.
Note: Use HTML headings for headings only. Don't use headings to make
text BIG or bold.
Bigger Headings
Each HTML heading has a default size. However, you can specify the size for
any heading with the style attribute, using the CSS font-size property:
Example
<h1 style="font-size:60px;">Heading 1</h1>
Try it Yourself »
Exercise?
Which of the following headers is the largest and most important header?
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
Submit Answer »
Tag Description
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
Try it Yourself »
HTML Display
You cannot be sure how HTML will be displayed.
Large or small screens, and resized windows will create different results.
With HTML, you cannot change the display by adding extra spaces or extra
lines in your HTML code.
The browser will automatically remove any extra spaces and lines when the
page is displayed:
Example
<p>
This paragraph
contains a lot of lines
in the source code,
but the browser
ignores it.
</p>
<p>
This paragraph
contains a lot of spaces
in the source code,
but the browser
ignores it.
</p>
Try it Yourself »
The <hr> element is used to separate content (or define a change) in an HTML
page:
Example
<h1>This is heading 1</h1>
<p>This is some text.</p>
<hr>
<h2>This is heading 2</h2>
<p>This is some other text.</p>
<hr>
Try it Yourself »
The <hr> tag is an empty tag, which means that it has no end tag.
Use <br> if you want a line break (a new line) without starting a new
paragraph:
Example
<p>This is<br>a paragraph<br>with line breaks.</p>
Try it Yourself »
The <br> tag is an empty tag, which means that it has no end tag.
Example
<p>
My Bonnie lies over the ocean.
Try it Yourself »
Example
<pre>
My Bonnie lies over the ocean.
Try it Yourself »
Exercise?
True or False. HTML paragraphs always starts on a new line.
True
False
Example
I am Red
I am Blue
I am Big
Try it Yourself »
<tagname style="property:value;">
Background Color
The CSS background-color property defines the background color for an
HTML element.
Example
Set the background color for a page to powderblue:
<body style="background-color:powderblue;">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
Try it Yourself »
Example
Set background color for two different elements:
<body>
</body>
Try it Yourself »
Text Color
The CSS color property defines the text color for an HTML element:
Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
Try it Yourself »
Fonts
The CSS font-family property defines the font to be used for an HTML
element:
Example
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>
Try it Yourself »
Text Size
The CSS font-size property defines the text size for an HTML element:
Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>
Try it Yourself »
Text Alignment
The CSS text-align property defines the horizontal text alignment for an
HTML element:
Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>
Try it Yourself »
Chapter Summary
Use the style attribute for styling HTML elements
Use background-color for background color
Use color for text colors
Use font-family for text fonts
Use font-size for text sizes
Use text-align for text alignment
Exercise?
What is a correct way to add a background color to an HTML document?
<body style='background-color:pink;'>
<body background-color='pink;'>
<body style='bgcolor:pink;'>
HTML contains several elements for defining text with a special meaning.
Example
This text is bold
Try it Yourself »
Example
<b>This text is bold</b>
Try it Yourself »
The HTML <strong> element defines text with strong importance. The content
inside is typically displayed in bold.
Example
<strong>This text is important!</strong>
Try it Yourself »
Tip: The <i> tag is often used to indicate a technical term, a phrase from
another language, a thought, a ship name, etc.
Example
<i>This text is italic</i>
Try it Yourself »
The HTML <em> element defines emphasized text. The content inside is
typically displayed in italic.
Tip: A screen reader will pronounce the words in <em> with an emphasis,
using verbal stress.
Example
<em>This text is emphasized</em>
Try it Yourself »
Example
<small>This is some smaller text.</small>
Try it Yourself »
Example
<p>Do not forget to buy <mark>milk</mark> today.</p>
Try it Yourself »
Example
<p>My favorite color is <del>blue</del> red.</p>
Try it Yourself »
HTML <ins> Element
The HTML <ins> element defines a text that has been inserted into a
document. Browsers will usually underline inserted text:
Example
<p>My favorite color is <del>blue</del> <ins>red</ins>.</p>
Try it Yourself »
Example
<p>This is <sub>subscripted</sub> text.</p>
Try it Yourself »
Example
<p>This is <sup>superscripted</sup> text.</p>
Try it Yourself »
Exercise?
Two of the following HTML elements makes the text bold, which two?
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Example
Here is a quote from WWF's website:
For 60 years, WWF has worked to help people and nature thrive. As the
world's leading conservation organization, WWF works in nearly 100
countries. At every level, we collaborate with people around the world to
develop and deliver innovative solutions that protect communities, wildlife,
and the places in which they live.
Try it Yourself »
Example
<p>Here is a quote from WWF's website:</p>
<blockquote cite="[Link]
For 60 years, WWF has worked to help people and nature thrive. As
the world's leading conservation organization, WWF works in
nearly 100 countries. At every level, we collaborate with people
around the world to develop and deliver innovative solutions that
protect communities, wildlife, and the places in which they live.
</blockquote>
Try it Yourself »
Example
<p>WWF's goal is to: <q>Build a future where people live in
harmony with nature.</q></p>
Try it Yourself »
HTML <abbr> for Abbreviations
The HTML <abbr> tag defines an abbreviation or an acronym, like "HTML",
"CSS", "Mr.", "Dr.", "ASAP", "ATM".
Tip: Use the global title attribute to show the description for the
abbreviation/acronym when you mouse over the element.
Example
<p>The <abbr title="World Health Organization">WHO</abbr> was
founded in 1948.</p>
Try it Yourself »
The text in the <address> element usually renders in italic, and browsers will
always add a line break before and after the <address> element.
Example
<address>
Written by John Doe.<br>
Visit us at:<br>
[Link]<br>
Box 564, Disneyland<br>
USA
</address>
Try it Yourself »
Example
<p><cite>The Scream</cite> by Edvard Munch. Painted in 1893.</p>
Try it Yourself »
The HTML <bdo> tag is used to override the current text direction:
Example
<bdo dir="rtl">This text will be written from right to left</bdo>
Try it Yourself »
Exercise?
Which of the following is NOT a quotation element (in fact, not an HTML element at all)?
<q>
<quote>
<blockquote>
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
HTML comments are not displayed in the browser, but they can help
document your HTML source code.
Notice that there is an exclamation point (!) in the start tag, but not in the
end tag.
Note: Comments are not displayed by the browser, but they can help
document your HTML source code.
Add Comments
With comments you can place notifications and reminders in your HTML code:
Example
<!-- This is a comment -->
<p>This is a paragraph.</p>
Try it Yourself »
Hide Content
Comments can be used to hide content.
Example
<p>This is a paragraph.</p>
Try it Yourself »
You can also hide more than one line. Everything between the <!-- and
the --> will be hidden from the display.
Example
Hide a section of HTML code:
<p>This is a paragraph.</p>
<!--
<p>Look at this cool image:</p>
<img border="0" src="pic_trulli.jpg" alt="Trulli">
-->
<p>This is a paragraph too.</p>
Try it Yourself »
Comments are also great for debugging HTML, because you can comment
out HTML lines of code, one at a time, to search for errors.
Example
Hide a part of a paragraph:
Try it Yourself »
Exercise?
What is the correct syntax for adding a comment in HTML?
HTML Colors
❮ PreviousNext ❯
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 »
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 <div> elements have their background color set with
RGB, HEX, and HSL values:
#ff6347
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>
Try it Yourself »
Exercise?
Do you remember any legal HTML color names? Which one of the following is a legal
HTML color?
Apple
Banana
Tomato
An RGB color value represents RED, GREEN, and BLUE light sources.
This means that there are 256 x 256 x 256 = 16777216 possible colors!
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).
Example
rgb(255, 0, 0)
rgb(0, 0, 255)
rgb(255, 165, 0)
rgb(106, 90, 205)
Try it Yourself »
Shades of Gray
Shades of gray are often defined using equal values for all three parameters:
Example
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.
Example
Try it Yourself »
Experiment by mixing the RGBA values below:
RED
255
GREEN
99
BLUE
71
ALPHA
0.5
Exercise?
What is the color of the following text:
Hello
color:rgb(0, 255, 0)
color:rgb(255, 0, 0)
Submit Answer »
HTML HEX Colors
❮ PreviousNext ❯
#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.
To display black, set all color parameters to 00, like this: #000000.
To display white, set all color parameters to ff, like this: #ffffff.
#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 »
Exercise?
What is the highest HEX number of the following:
#44
#AA
#BB
Submit Answer »
SATURATION
100%
LIGHTNESS
50%
Example
Try it Yourself »
Saturation
Saturation can be described as the intensity of a color.
50% is 50% gray, but you can still see the color.
Example
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), and 100% means full lightness (white).
Example
Try it Yourself »
Shades of Gray
Shades of gray are often defined by setting the hue and saturation to 0, and
adjusting the lightness from 0% to 100% to get darker/lighter shades:
Example
hsl(0, 0%, 20%)
Try it Yourself »
HUE
SATURATION
100%
LIGHTNESS
50%
ALPHA
0.5
Example
Try it Yourself »
Exercise?
Which one of the following color values will result in a black color?
hsl(0, 0, 100%)
Submit Answer »
CSS saves a lot of work. It can control the layout of multiple web pages all
at once.
CSS = Styles and Colors
M a n i p u l a t e T e x t
C o l o r s , B o x e s
What is CSS?
Cascading Style Sheets (CSS) is used to format the layout of a webpage.
With CSS, you can control the color, font, the size of text, the spacing
between elements, how elements are positioned and laid out, what
background images or background colors are to be used, different displays
for different devices and screen sizes, and much more!
Tip: The word cascading means that a style applied to a parent element will
also apply to all children elements within the parent. So, if you set the color
of the body text to "blue", all headings, paragraphs, and other text elements
within the body will also get the same color (unless you specify something
else)!
Using CSS
CSS can be added to HTML documents in 3 ways:
The most common way to add CSS, is to keep the styles in external CSS files.
However, in this tutorial we will use inline and internal styles, because this is
easier to demonstrate, and easier for you to try it yourself.
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
The following example sets the text color of the <h1> element to blue, and the
text color of the <p> element to red:
Example
<h1 style="color:blue;">A Blue Heading</h1>
Try it Yourself »
Internal CSS
An internal CSS is used to define a style for a single HTML page.
The following example sets the text color of ALL the <h1> elements (on that
page) to blue, and the text color of ALL the <p> elements to red. In addition,
the page will be displayed with a "powderblue" background color:
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Try it Yourself »
External CSS
An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each
HTML page:
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Try it Yourself »
The external style sheet can be written in any text editor. The file must not
contain any HTML code, and must be saved with a .css extension.
"[Link]":
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
Tip: With an external style sheet, you can change the look of an entire web
site, by changing one file!
CSS Colors, Fonts and Sizes
Here, we will demonstrate some commonly used CSS properties. You will
learn more about them later.
Example
Use of CSS color, font-family and font-size properties:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Try it Yourself »
CSS Border
The CSS border property defines a border around an HTML element.
Tip: You can define a border for nearly all HTML elements.
Example
Use of CSS border property:
p {
border: 2px solid powderblue;
}
Try it Yourself »
CSS Padding
The CSS padding property defines a padding (space) between the text and the
border.
Example
Use of CSS border and padding properties:
p {
border: 2px solid powderblue;
padding: 30px;
}
Try it Yourself »
CSS Margin
The CSS margin property defines a margin (space) outside the border.
Example
Use of CSS border and margin properties:
p {
border: 2px solid powderblue;
margin: 50px;
}
Try it Yourself »
Example
This example uses a full URL to link to a style sheet:
Try it Yourself »
Example
This example links to a style sheet located in the html folder on the current
web site:
Try it Yourself »
Example
This example links to a style sheet located in the same folder as the current
page:
Try it Yourself »
You can read more about file paths in the chapter HTML File Paths.
Chapter Summary
Use the HTML style attribute for inline styling
Use the HTML <style> element to define internal CSS
Use the HTML <link> element to refer to an external CSS file
Use the HTML <head> element to store <style> and <link> elements
Use the CSS color property for text colors
Use the CSS font-family property for text fonts
Use the CSS font-size property for text sizes
Use the CSS border property for borders
Use the CSS padding property for space inside the border
Use the CSS margin property for space outside the border
Tip: You can learn much more about CSS in our CSS Tutorial.
Exercise?
What is a correct syntax for linking to an external stylesheet?
HTML Links
❮ PreviousNext ❯
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.
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!
The most important attribute of the <a> 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 [Link]:
Try it Yourself »
Tip: Links can of course be styled with CSS, to get another look!
Example
Use target="_blank" to open the linked document in a new browser window
or tab:
Try it Yourself »
A local link (a link to a page within the same website) is specified with
a relative URL (without the "[Link] part):
Example
<h2>Absolute URLs</h2>
<p><a href="[Link]
<p><a href="[Link]
<h2>Relative URLs</h2>
<p><a href="html_images.asp">HTML Images</a></p>
<p><a href="/css/[Link]">CSS Tutorial</a></p>
Try it Yourself »
HTML Links - Use an Image as a Link
To use an image as a link, just put the <img> tag inside the <a> tag:
Example
<a href="[Link]">
<img src="[Link]" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>
Try it Yourself »
Example
<a href="[Link] email</a>
Try it Yourself »
Button as a Link
To use an HTML button as a link, you have to add some JavaScript code.
Example
<button onclick="[Link]='[Link]'">HTML
Tutorial</button>
Try it Yourself »
Example
<a href="[Link] title="Go to W3Schools
HTML section">Visit our HTML Tutorial</a>
Try it Yourself »
<a href="[Link]
tutorial</a>
Try it Yourself »
Example
Link to a page located in the html folder on the current web site:
Try it Yourself »
Example
Link to a page located in the same folder as the current page:
Try it Yourself »
You can read more about file paths in the chapter HTML File Paths.
Chapter Summary
Use the <a> 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 <img> element (inside <a>) 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
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Exercise?
What is a correct syntax for an HTML hyperlink?
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:
<style>
a:link {
color: green;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: pink;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: red;
background-color: transparent;
text-decoration: underline;
}
a:active {
color: yellow;
background-color: transparent;
text-decoration: underline;
}
</style>
Try it Yourself »
Link Buttons
A link can also be styled as a button, by using CSS:
This is a link
Example
<style>
a:link, a:visited {
background-color: #f44336;
color: white;
padding: 15px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
a:hover, a:active {
background-color: red;
}
</style>
Try it Yourself »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Exercise?
True or False. By default all hyperlinks are underlined.
HTML links can be used to create bookmarks, so that readers can jump to
specific parts of a web page.
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:
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 »
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
Exercise?
What HTML attribute is used to create a bookmark?
The id attribute
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
HTML Images
❮ PreviousNext ❯
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 »
Images are not technically inserted into a web page; images are linked to
web pages. The <img> tag creates a holding space for the referenced image.
The <img> tag is empty, it contains attributes only, and does not have a
closing tag.
Syntax
<img src="url" alt="alternatetext">
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).
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="[Link]" 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.
Example
<img src="img_girl.jpg" alt="Girl in a
jacket" style="width:500px;height:600px;">
Try it Yourself »
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.
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>
</body>
</html>
Try it Yourself »
Try it Yourself »
Example
<img src="[Link] a
lt="[Link]">
Try it Yourself »
Animated Images
HTML allows animated GIFs:
Example
<img src="[Link]" alt="Computer
Man" style="width:48px;height:48px;">
Try it Yourself »
Image as a Link
To use an image as a link, put the <img> tag inside the <a> tag:
Example
<a href="[Link]">
<img src="[Link]" 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="[Link]" alt="Smiley
face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>
Try it Yourself »
Tip: To learn more about CSS Float, read our CSS Float Tutorial.
Chapter Summary
Use the HTML <img> element to define an image
Use the HTML src attribute to define the URL of the image
Use the HTML alt attribute to define an alternate text for an image, if
it cannot be displayed
Use the HTML width and height attributes 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.
Exercise?
What is a correct HTML element for adding an image?
The <image> element
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
HTML Image Maps
❮ PreviousNext ❯
With HTML image maps, you can create clickable areas on an image.
Image Maps
The HTML <map> tag defines an image map. An image map is an image with
clickable areas. The areas are defined with one or more <area> tags.
Try to click on the computer, phone, or the cup of coffee in the image below:
Example
Here is the HTML source code for the image map above:
Try it Yourself »
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 <img> tag. The only difference from other
images is that you must add a usemap attribute:
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.
<map name="workmap">
The name attribute must have the same value as the <img>'s usemap attribute .
The Areas
Then, add the clickable areas.
Shape
You must define the shape of the clickable area, and you can choose one of
these values:
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:
The coordinates 270,350 is located 270 pixels from the left margin and 350
pixels from the top:
Example
<area shape="rect" coords="34, 44, 270, 350" href="[Link]">
Try it Yourself »
This is the area that becomes clickable and will send the user to the page
"[Link]":
Shape="circle"
To add a circle area, first locate the coordinates of the center of the circle:
337,300
Then specify the radius of the circle:
44 pixels
Try it Yourself »
This is the area that becomes clickable and will send the user to the page
"[Link]":
Shape="poly"
The shape="poly" contains several coordinate points, which creates a shape
formed with straight lines (a polygon).
How can we make the croissant in the image below become a clickable link?
We have to find the x and y coordinates for all edges of the croissant:
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,27
0,140,329,85,355,58,352,37,322,40,259,103,161,128,147" href="croi
[Link]">
Try it Yourself »
This is the area that becomes clickable and will send the user to the page
"[Link]":
Image Map and JavaScript
A clickable area can also trigger 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="[Link]" oncl
ick="myFunction()">
</map>
<script>
function myFunction() {
alert("You clicked the coffee cup!");
}
</script>
Try it Yourself »
Chapter Summary
Use the HTML <map> element to define an image map
Use the HTML <area> element to define the clickable areas in the
image map
Use the HTML usemap attribute of the <img> element to point to an
image map
Exercise?
What is a correct HTML element for defining an image map?
Submit Answer »
HTML Image Tags
Tag Description
For a complete list of all available HTML tags, visit our HTML Tag Reference.
❮ PreviousNext ❯
Example
Add a background image on a <p> element:
Try it Yourself »
You can also specify the background image in the <style> element, in
the <head> section:
Example
Specify the background image in the <style> element:
<style>
p {
background-image: url('img_girl.jpg');
}
</style>
Try it Yourself »
Example
Add a background image for the entire page:
<style>
body {
background-image: url('img_girl.jpg');
}
</style>
Try it Yourself »
Background Repeat
If the background image is smaller than the element, the image will repeat
itself, horizontally and vertically, until it reaches the end of the element:
Example
<style>
body {
background-image: url('example_img_girl.jpg');
}
</style>
Try it Yourself »
To avoid the background image from repeating itself, set the background-
repeat property to no-repeat.
Example
<style>
body {
background-image: url('example_img_girl.jpg');
background-repeat: no-repeat;
}
</style>
Try it Yourself »
Background Cover
If you want the background image to cover the entire element, you can set
the background-size property to cover.
Also, to make sure the entire element is always covered, set the background-
attachment property to fixed:
This way, the background image will cover the entire element, with no
stretching (the image will keep its original proportions):
Example
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
Try it Yourself »
Background Stretch
If you want the background image to stretch to fit the entire element, you
can set the background-size property to 100% 100%:
Try resizing the browser window, and you will see that the image will stretch,
but always cover the entire element.
Example
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
</style>
Try it Yourself »
Exercise?
What is a correct CSS property for defining background images?
The bg property
Submit Answer »
To learn more about CSS background properties, study our CSS Background
Tutorial.
The HTML <picture> element allows you to display different pictures for
different devices or screen sizes.
The HTML <picture> Element
The HTML <picture> element gives web developers more flexibility in
specifying image resources.
Each <source> 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 »
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 <source> 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 <picture> 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 <source> element with matching attribute
values, and ignore any following <source> elements.
Exercise?
One of these elements is NOT a legal HTML element, which one?
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
HTML Favicon
❮ PreviousNext ❯
A favicon is a small image displayed next to the page title in the browser
tab.
A favicon image is displayed to the left of the page title in the browser tab,
like this:
To add a favicon to your website, either save your favicon image to the root
directory of your webserver, or create a folder in the root directory called
images, and save your favicon image in this folder. A common name for a
favicon image is "[Link]".
Example
<!DOCTYPE html>
<html>
<head>
<title>My Page Title</title>
<link rel="icon" type="image/x-icon" href="/images/[Link]"
>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Now, save the "[Link]" file and reload it in your browser. Your browser
tab should now display your favicon image to the left of the page title.
Chapter Summary
Use the HTML <link> element to insert a favicon
Exercise?
In which HTML element is the Favicon defined?
The <img> element
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Every web page should have a page title to describe the meaning of the
page.
The Title Element
The <title> element adds a title to your page:
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Tutorial</title>
</head>
<body>
</body>
</html>
The page title is very important for search engine optimization (SEO). The
text is used by search engine algorithms to decide the order when listing
pages in search results.
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Exercise?
In which HTML element is the page title defined?
Submit Answer »
HTML Tables
❮ PreviousNext ❯
HTML tables allow web developers to arrange data into rows and columns.
Example
Company Contact Co
Try it Yourself »
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 »
Table Cells
Each table cell is defined by a <td> and a </td> tag.
Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>
Try it Yourself »
Note: A table cell can contain all sorts of HTML elements: text, images, lists,
links, other tables, etc.
Table Rows
Each table row starts with a <tr> and ends with a </tr> tag.
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 when 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 table header cells. In those cases use
the <th> tag instead of the <td> tag:
Example
Let the first row be table header cells:
<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 <th> elements are bold and centered, but you can
change that with CSS.
Exercise?
What is the correct tag name for a table-cell in HTML?
<tc>
<td>
<tr>
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
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.
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
Try it Yourself »
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
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 »
Exercise?
What is the correct CSS property for styling the border of a table?
table-border
table-style
border
Submit Answer »
HTML Table Sizes
❮ PreviousNext ❯
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.
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 <body> 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 »
Exercise?
What is the correct CSS property for styling the width of a table?
size
table-size
width
Submit Answer »
HTML tables can have headers for each column or row, or for many
columns/rows.
8:00
9:00
10:00
11:00
12:00
13:00
8:00
9:00
10:00
11:00
12:00
DECEMBER
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 »
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 »
Jill Smith 50
Eve Jackson 94
Example
th {
text-align: left;
}
Try it Yourself »
Name Age
Jill Smith 50
Eve Jackson 94
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
Month Savings
January $100
February $50
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 »
Exercise?
What is the correct tag name for a table-header in HTML?
<table-header>
<td>
<th>
Submit Answer »
HTML tables can adjust the padding inside the cells, and also the space
between the cells.
With Padding
With Spacing
Example
th, td {
padding: 15px;
}
Try it Yourself »
To add padding only above the content, use the padding-top property.
Example
th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}
Try it Yourself »
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 »
Exercise?
What is the correct CSS property for styling the padding inside table cells?
padding
table-padding
cell-padding
Submit Answer »
❮ PreviousNext ❯
NAME
APRIL
2022
FIESTA
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.
Exercise?
What is the correct HTML attribute for specifying how many rows a cell should span?
span
rowspan
spanning
Submit Answer »
HTML Table Styling
❮ PreviousNext ❯
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
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.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
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.
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 Name Last Name Savings
If you specify borders only at the bottom of each table row, you will have a
table with 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:
Example
tr:hover {background-color: #D6EEEE;}
Try it Yourself »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
The span attribute specifies how many columns get the style.
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 <colgroup> tag must be a child of a <table> element and should be
placed before any other table elements, like <thead>, <tr>, <td> etc., but after
the <caption> element, if present.
Legal CSS Properties
There is 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
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 an
"empty" <col> 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
❮ PreviousNext ❯
HTML lists allow web developers to group a set of related items in lists.
Example
An unordered HTML list:
Item
Item
Item
Item
1. First item
2. Second item
3. Third item
4. Fourth item
Try it Yourself »
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 »
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Try it Yourself »
The <dl> tag defines the description list, the <dt> tag defines the term
(name), and the <dd> tag describes each term:
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Try it Yourself »
Value Description
Disc
Example - Disc
<ul style="list-style-type:disc;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Try it Yourself »
Circle
Example - Circle
<ul style="list-style-type:circle;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Try it Yourself »
Square
Example - Square
<ul style="list-style-type:square;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Try it Yourself »
No List Marker
Example - None
<ul style="list-style-type:none;">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Try it Yourself »
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 (<li>) can contain a new list, and other HTML elements, like
images and links, etc.
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 <ul> element to define an unordered list
Use the CSS list-style-type property to define the list item marker
Use the HTML <li> 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
Exercise?
What is the correct CSS property to use when defining the style of a list marker of
unordered lists?
list-style-type
style-type-list
type-list-style
Submit Answer »
The HTML <ol> tag defines an ordered list. An ordered list can be
numerical or alphabetical.
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 <ol> tag, defines the type of the list item marker:
Type Description
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
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Try it Yourself »
Uppercase Letters
Uppercase Letters:
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Try it Yourself »
Lowercase Letters
Lowercase Letters:
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Try it Yourself »
Try it Yourself »
Try it Yourself »
Example
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Try it Yourself »
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 (<li>) can contain a new list, and other HTML elements, like
images and links, etc.
Chapter Summary
Use the HTML <ol> element to define an ordered list
Use the HTML type attribute to define the numbering type
Use the HTML <li> element to define a list item
Lists can be nested
List items can contain other HTML elements
Exercise?
What is the correct HTML attribute to use when defining the type of the list item marker
of ordered lists?
list-style
list-type
marker-type
type
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Try it Yourself »
Chapter Summary
Use the HTML <dl> element to define a description list
Use the HTML <dt> element to define the description term
Use the HTML <dd> element to describe the term in a description list
Exercise?
What is the correct tag name for a description list?
<dl>
<list>
<definition>
Submit Answer »
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Every HTML element has a default display value, depending on what type
of element it is.
The two most common display values are block and inline.
Block-level Elements
A block-level element always starts on a new line, and the browsers
automatically add some space (a margin) before and after the element.
A block-level element always takes up the full width available (stretches out
to the left and right as far as it can).
Example
<p>Hello World</p>
<div>Hello World</div>
Try it Yourself »
<address>
<article>
<aside>
<blockquote>
<canvas>
<dd>
<div>
<dl>
<dt>
<fieldset>
<figcaption>
<figure>
<footer>
<form>
<h1>-<h6>
<header>
<hr>
<li>
<main>
<nav>
<noscript>
<ol>
<p>
<pre>
<section>
<table>
<tfoot>
<ul>
<video>
Inline Elements
An inline element does not start on a new line.
An inline element only takes up as much width as necessary.
Example
<span>Hello World</span>
Try it Yourself »
<a>
<abbr>
<acronym>
<b>
<bdo>
<big>
<br>
<button>
<cite>
<code>
<dfn>
<em>
<i>
<img>
<input>
<kbd>
<label>
<map>
<object>
<output>
<q>
<samp>
<script>
<select>
<small>
<span>
<strong>
<sub>
<sup>
<textarea>
<time>
<tt>
<var>
The <div> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <div> element can be used to style blocks
of content:
Example
<div style="background-color:black;color:white;padding:20px;">
<h2>London</h2>
<p>London is the capital city of England. It is the most
populous city in the United Kingdom, with a metropolitan area of
over 13 million inhabitants.</p>
</div>
Try it Yourself »
You will learn more about the <div> element in the next chapter.
The <span> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <span> element can be used to style parts
of the text:
Example
<p>My mother has <span style="color:blue;font-
weight:bold;">blue</span> eyes and my father
has <span style="color:darkolivegreen;font-weight:bold;">dark
green</span> eyes.</p>
Try it Yourself »
Chapter Summary
A block-level element always starts on a new line and takes up the full
width available
An inline element does not start on a new line and it only takes up as
much width as necessary
The <div> element is a block-level element and is often used as a
container for other HTML elements
The <span> element is an inline container used to mark up a part of a
text, or a part of a document
Exercise?
Which type of elements takes up the full width available?
Block elements
Inline elements
Submit Answer »
HTML Tags
Tag Description
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Example
A <div> element takes up all available width:
Result
Lorem Ipsum
I am a div
Try it Yourself »
The <div> element has no required attributes, but style, class and id are
common.
<div> as a container
The <div> element is often used to group sections of a web page together.
Example
A <div> element with HTML elements:
<div>
<h2>London</h2>
<p>London is the capital city of England.</p>
<p>London has over 9 million inhabitants.</p>
</div>
Result
London
London is the capital city of England.
Try it Yourself »
Example
<style>
div {
width:300px;
margin:auto;
}
</style>
Result
London
London is the capital city of England.
Try it Yourself »
<div>
<h2>Oslo</h2>
<p>Oslo is the capital city of Norway.</p>
<p>Oslo has over 700,000 inhabitants.</p>
</div>
<div>
<h2>Rome</h2>
<p>Rome is the capital city of Italy.</p>
<p>Rome has over 4 million inhabitants.</p>
</div>
Result
London
London is the capital city of England.
Oslo
Oslo is the capital city of Norway.
Rome
Rome is the capital city of Italy.
Try it Yourself »
Aligning <div> elements side by side
When building web pages, you often want to have two or
more <div> elements side by side, like this:
London
London is the capital city of England.
Oslo
Oslo is the capital city of Norway.
Rome
Rome is the capital city of Italy.
There are different methods for aligning elements side by side, all include
some CSS styling. We will look at the most common methods:
Float
The CSS float property was not originally meant to align <div> elements side-
by-side, but has been used for this purpose for many years.
The CSS float property is used for positioning and formatting content and
allows elements to be positioned horizontally, rather than vertically.
Example
How to use float to align div elements side by side:
<style>
.mycontainer {
width:100%;
overflow:auto;
}
.mycontainer div {
width:33%;
float:left;
}
</style>
Result
London
London is the capital city of England.
Oslo
Oslo is the capital city of Norway.
Rome
Rome is the capital city of Italy.
Try it Yourself »
Inline-block
If you change the <div> element's display property from block to inline-
block, the <div> elements will no longer add a line break before and after, and
will be displayed side by side instead of on top of each other.
Example
How to use display: inline-block to align div elements side by side:
<style>
div {
width: 30%;
display: inline-block;
}
</style>
Result
London
London is the capital city of England.
Oslo
Oslo is the capital city of Norway.
Rome
Rome is the capital city of Italy.
Try it Yourself »
Flex
The CSS Flexbox Layout Module was introduced to make it easier to design
flexible responsive layout structure without using float or positioning.
To make the CSS flex method work, surround the <div> elements with
another <div> element and give it the status as a flex container.
Example
How to use flex to align div elements side by side:
<style>
.mycontainer {
display: flex;
}
.mycontainer > div {
width:33%;
}
</style>
Result
London
London is the capital city of England.
Oslo
Oslo is the capital city of Norway.
Rome
Rome is the capital city of Italy.
Try it Yourself »
In the following example we have three <div> elements with a class attribute
with the value of "city". All of the three <div> elements will be styled equally
according to the .city style definition in the head section:
Example
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
border: 2px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div class="city">
<h2>London</h2>
<p>London is the capital of England.</p>
</div>
<div class="city">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div class="city">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>
</body>
</html>
Try it Yourself »
In the following example we have two <span> elements with a class attribute
with the value of "note". Both <span> elements will be styled equally
according to the .note style definition in the head section:
Example
<!DOCTYPE html>
<html>
<head>
<style>
.note {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
</body>
</html>
Try it Yourself »
Tip: You can learn much more about CSS in our CSS Tutorial.
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
</head>
<body>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</body>
</html>
Try it Yourself »
Multiple Classes
HTML elements can belong to more than one class.
To define multiple classes, separate the class names with a space, e.g. <div
class="city main">. The element will be styled according to all the classes
specified.
In the following example, the first <h2> element belongs to both the city class
and also to the main class, and will get the CSS styles from both of the
classes:
Example
<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>
Try it Yourself »
In the following example, both <h2> and <p> point to the "city" class and will
share the same style:
Example
<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>
Try it Yourself »
Example
Click on a button to hide all elements with the class name "city":
<script>
function myFunction() {
var x = [Link]("city");
for (var i = 0; i < [Link]; i++) {
x[i].[Link] = "none";
}
}
</script>
Try it Yourself »
Don't worry if you don't understand the code in the example above.
You will learn more about JavaScript in our HTML JavaScript chapter, or you
can study our JavaScript Tutorial.
Chapter Summary
The HTML class attribute specifies one or more class names for an
element
Classes are used by CSS and JavaScript to select and access specific
elements
The class attribute can be used on any HTML element
The class name is case sensitive
Different HTML elements can point to the same class name
JavaScript can access elements with a specific class name with
the getElementsByClassName() method
Exercise?
True or False. The class name is case sensitive
True
False
Submit Answer »
HTML id Attribute
❮ PreviousNext ❯
You cannot have more than one element with the same id in an HTML
document.
The id Attribute
The id attribute specifies a unique id for an HTML element. The value of
the id attribute must be unique within the HTML document.
The syntax for id is: write a hash character (#), followed by an id name. Then,
define the CSS properties within curly braces {}.
In the following example we have an <h1> element that points to the id name
"myHeader". This <h1> element will be styled according to the #myHeader style
definition in the head section:
Example
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">My Header</h1>
</body>
</html>
Try it Yourself »
Note: The id name must contain at least one character, cannot start with a
number, and must not contain whitespaces (spaces, tabs, etc.).
Example
<style>
/* Style the element with the id "myHeader" */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Try it Yourself »
Tip: You can learn much more about CSS in our CSS Tutorial.
To use a bookmark, you must first create it, and then add a link to it.
Then, when the link is clicked, the page will scroll to the location with the
bookmark.
Example
First, create a bookmark with the id attribute:
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 »
Or, add a link to the bookmark ("Jump to Chapter 4"), from another page:
Example
Use the id attribute to manipulate text with JavaScript:
<script>
function displayResult() {
[Link]("myHeader").innerHTML = "Have a nice
day!";
}
</script>
Try it Yourself »
Chapter Summary
The id attribute is used to specify a unique id for an HTML element
The value of the id attribute must be unique within the HTML
document
The id attribute is used by CSS and JavaScript to style/select a specific
element
The value of the id attribute is case sensitive
The id attribute is also used to create HTML bookmarks
JavaScript can access an element with a specific id with
the getElementById() method
Exercise?
True or False. The id name is case sensitive
True
False
HTML Iframes
❮ PreviousNext ❯
An inline frame is used to embed another document within the current HTML
document.
Syntax
<iframe src="url" title="description"></iframe>
Tip: It is a good practice to always include a title attribute for the <iframe>.
This is used by screen readers to read out what the content of the iframe is.
Example
<iframe src="demo_iframe.htm" height="200" width="300" title="Ifr
ame Example"></iframe>
Try it Yourself »
Example
<iframe src="demo_iframe.htm" style="height:200px;width:300px;" t
itle="Iframe Example"></iframe>
Try it Yourself »
To remove the border, add the style attribute and use the
CSS border property:
Example
<iframe src="demo_iframe.htm" style="border:none;" title="Iframe
Example"></iframe>
Try it Yourself »
With CSS, you can also change the size, style and color of the iframe's
border:
Example
<iframe src="demo_iframe.htm" style="border:2px solid
red;" title="Iframe Example"></iframe>
Try it Yourself »
Iframe - Target for a Link
An iframe can be used as the target frame for a link.
The target attribute of the link must refer to the name attribute of the iframe:
Example
<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe
Example"></iframe>
Try it Yourself »
Chapter Summary
The HTML <iframe> tag specifies an inline frame
The src attribute defines the URL of the page to embed
Always include a title attribute (for screen readers)
The height and width attributes specify the size of the iframe
Use border:none; to remove the border around the iframe
Exercise?
In which IFRAME attribute can we specify an URL?
href
src
url
Submit Answer »
HTML JavaScript
❮ PreviousNext ❯
Example
My First JavaScript
Click me to display Date and Time
Try it Yourself »
Common uses for JavaScript are image manipulation, form validation, and
dynamic changes of content.
This JavaScript example writes "Hello JavaScript!" into an HTML element with
id="demo":
Example
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
Try it Yourself »
Tip: You can learn much more about JavaScript in our JavaScript Tutorial.
A Taste of JavaScript
Here are some examples of what JavaScript can do:
Example
JavaScript can change content:
Try it Yourself »
Example
JavaScript can change styles:
[Link]("demo").[Link] = "25px";
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "yellow";
Try it Yourself »
Example
JavaScript can change attributes:
[Link]("image").src = "[Link]";
Try it Yourself »
The HTML <noscript> Tag
The HTML <noscript> tag defines an alternate content to be displayed to
users that have disabled scripts in their browser or have a browser that
doesn't support scripts:
Example
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>Sorry, your browser does not support JavaScript!
</noscript>
Try it Yourself »
Exercise?
In which HTML element do we put JavaScripts?
<java>
<javascript>
<script>
Submit Answer »
<noscript> Defines an alternate content for users that do not support client-side scri
For a complete list of all available HTML tags, visit our HTML Tag Reference.
A file path describes the location of a file in a web site's folder structure.
<img src="../[Link]"> The "[Link]" file is located in the folder one level
current folder
Web pages
Images
Style sheets
JavaScripts
Example
<img src="[Link] al
t="Mountain">
Try it Yourself »
The <img> tag is explained in the chapter: HTML Images.
Example
<img src="/images/[Link]" alt="Mountain">
Try it Yourself »
In the following example, the file path points to a file in the images folder
located in the current folder:
Example
<img src="images/[Link]" alt="Mountain">
Try it Yourself »
In the following example, the file path points to a file in the images folder
located in the folder one level up from the current folder:
Example
<img src="../images/[Link]" alt="Mountain">
Try it Yourself »
Best Practice
It is best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your
current base URL. All links will work on your own computer (localhost) as well
as on your current public domain and your future public domains.
HTML metadata is data about the HTML document. Metadata is not displayed
on the page.
Metadata typically define the document title, character set, styles, scripts,
and other meta information.
The content of a page title is very important for search engine optimization
(SEO)! The page title is used by search engine algorithms to decide the order
when listing pages in search results.
Example
<!DOCTYPE html>
<html>
<head>
<title>A Meaningful Page Title</title>
</head>
<body>
Try it Yourself »
Example
<style>
body {background-color: powderblue;}
h1 {color: red;}
p {color: blue;}
</style>
Try it Yourself »
The <link> tag is most often used to link to external style sheets:
Example
<link rel="stylesheet" href="[Link]">
Try it Yourself »
The metadata will not be displayed on the page, but is used by browsers
(how to display content or reload page), by search engines (keywords), and
other web services.
Examples
Define the character set used:
<meta charset="UTF-8">
Setting the viewport to make your website look good on all devices:
Example
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="John Doe">
Try it Yourself »
Setting The Viewport
The viewport is the user's visible area of a web page. It varies with the device
- it will be smaller on a mobile phone than on a computer screen.
You should include the following <meta> element in all your web pages:
This gives the browser instructions on how to control the page's dimensions
and scaling.
The width=device-width part sets the width of the page to follow the screen-
width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first
loaded by the browser.
Here is an example of a web page without the viewport meta tag, and the
same web page with the viewport meta tag:
Tip: If you are browsing this page with a phone or a tablet, you can click on
the two links below to see the difference.
Without the viewport meta tag
The following JavaScript writes "Hello JavaScript!" into an HTML element with
id="demo":
Example
<script>
function myFunction() {
[Link]("demo").innerHTML = "Hello
JavaScript!";
}
</script>
Try it Yourself »
The <base> tag must have either an href or a target attribute present, or both.
Example
Specify a default URL and a default target for all links on a page:
<head>
<base href="[Link] target="_blank">
</head>
<body>
<img src="images/[Link]" width="24" height="39" alt="Stickm
an">
<a href="tags/tag_base.asp">HTML base Tag</a>
</body>
Try it Yourself »
Chapter Summary
The <head> element is a container for metadata (data about data)
The <head> element is placed between the <html> tag and
the <body> tag
The <title> element is required and it defines the title of the
document
The <style> element is used to define style information for a single
document
The <link> tag is most often used to link to external style sheets
The <meta> element is typically used to specify the character set, page
description, keywords, author of the document, and viewport settings
The <script> element is used to define client-side JavaScripts
The <base> element specifies the base URL and/or target for all
relative URLs in a page
Exercise?
Which one of the following elements should NOT be placed in the head section?
<title>
<link>
<body>
Submit Answer »
<base> Defines a default address or a default target for all links on a page
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Example
Cities
London
Paris
Tokyo
London
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
Footer
Try it Yourself »
You can read more about semantic elements in our HTML Sem
CSS framework
CSS float property
CSS flexbox
CSS grid
CSS Frameworks
If you want to create your layout fast, you can use a CSS framework,
like [Link] or Bootstrap.
Ever heard about W3Schools Spaces? Here you can create your website
from scratch or use a template, and host it for free.
Example
Cities
London
Paris
Tokyo
London
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
Footer
Try it Yourself »
CSS Flexbox Layout
Use of flexbox ensures that elements behave predictably when the page
layout must accommodate different screen sizes and different display
devices.
Example
Cities
London
Paris
Tokyo
London
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
Footer
Try it Yourself »
Learn more about CSS grids in our CSS Grid Intro chapter.
HTML Responsive Web
Design
❮ PreviousNext ❯
Responsive web design is about creating web pages that look good on all
devices!
Example
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
Try it Yourself »
This will set the viewport of your page, which will give the browser
instructions on how to control the page's dimensions and scaling.
Here is an example of a web page without the viewport meta tag, and the
same web page with the viewport meta tag:
Tip: If you are browsing this page on a phone or a tablet, you can click on the
two links above to see the difference.
Responsive Images
Responsive images are images that scale nicely to fit any browser size.
Try it Yourself »
Notice that in the example above, the image can be scaled up to be larger
than its original size. A better solution, in many cases, will be to use the max-
width property instead.
Example
<img src="img_girl.jpg" style="max-width:100%;height:auto;">
Try it Yourself »
Resize the browser window to see how the image below changes depending
on the width:
Example
<picture>
<source srcset="img_smallflower.jpg" media="(max-width:
600px)">
<source srcset="img_flowers.jpg" media="(max-width: 1500px)">
<source srcset="[Link]">
<img src="img_smallflower.jpg" alt="Flowers">
</picture>
Try it Yourself »
That way the text size will follow the size of the browser window:
Hello World
Resize the browser window to see how the text size scales.
Example
<h1 style="font-size:10vw">Hello World</h1>
Try it Yourself »
Viewport is the browser window size. 1vw = 1% of viewport width. If the
viewport is 50cm wide, 1vw is 0.5cm.
Media Queries
In addition to resize text and images, it is also common to use media queries
in responsive web pages.
With media queries you can define completely different styles for different
browser sizes.
Example: resize the browser window to see that the three div elements below
will display horizontally on large screens and stack vertically on small
screens:
Left Menu
Main Content
Right Content
Example
<style>
.left, .right {
float: left;
width: 20%; /* The width is 20%, by default */
}
.main {
float: left;
width: 60%; /* The width is 60%, by default */
}
Try it Yourself »
Tip: To learn more about Media Queries and Responsive Web Design, read
our RWD Tutorial.
Try it Yourself »
Ever heard about W3Schools Spaces? Here you can create your website
from scratch or use a template, and host it for free.
[Link]
[Link] is a modern CSS framework with support for desktop, tablet, and
mobile design by default.
London
London is the capital city of England.
It is the most populous city in the United Kingdom, with a metropolitan area
of over 13 million inhabitants.
Paris
Paris is the capital of France.
The Paris area is one of the largest population centers in Europe, with more
than 12 million inhabitants.
Tokyo
Tokyo is the capital of Japan.
It is the center of the Greater Tokyo Area, and the most populous
metropolitan area in the world.
Example
<!DOCTYPE html>
<html>
<head>
<title>[Link]</title>
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet" href="[Link]
.css">
</head>
<body>
<div class="w3-third">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
<p>The Paris area is one of the largest population centers in
Europe,
with more than 12 million inhabitants.</p>
</div>
<div class="w3-third">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
<p>It is the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</div>
</div>
</body>
</html>
Try it Yourself »
Bootstrap
Another popular CSS framework is Bootstrap:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link href="[Link]
/[Link]" rel="stylesheet">
<script src="[Link]
/[Link]"></script>
</head>
<body>
Try it Yourself »
Exercise?
There is a CSS font size unit that sizes text in percent of the viewport, what unit is that?
px
em
vw
vp
HTML contains several elements for defining user input and computer
code.
Example
<code>
x = 5;
y = 6;
z = x + y;
</code>
Try it Yourself »
Result:
Try it Yourself »
Example
Define some text as sample output from a computer program in a document:
Result:
Try it Yourself »
Example
Define some text as computer code in a document:
<code>
x = 5;
y = 6;
z = x + y;
</code>
Result:
x = 5; y = 6; z = x + y;
Try it Yourself »
Preserve Line-Breaks
Notice that the <code> element does NOT preserve extra whitespace and
line-breaks.
Example
<pre>
<code>
x = 5;
y = 6;
z = x + y;
</code>
</pre>
Result:
x = 5;
y = 6;
z = x + y;
Try it Yourself »
Result:
The area of a triangle is: 1/2 x b x h, where b is the base, and h is the vertical
height.
Try it Yourself »
Chapter Summary
The <kbd> element defines keyboard input
The <samp> element defines sample output from a computer program
The <code> element defines a piece of computer code
The <var> element defines a variable in programming or in a
mathematical expression
The <pre> element defines preformatted text
Exercise?
Which one of the following is NOT an HTML element?
<code>
<pre>
<kbd>
<xamp>
Submit Answer »
HTML Computer Code Elements
Tag Description
For a complete list of all available HTML tags, visit our HTML Tag Reference.
In HTML there are several semantic elements that can be used to define
different parts of a web page:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
HTML <section> Element
The <section> element defines a section in a document.
Chapters
Introduction
News items
Contact information
A web page could normally be split into sections for introduction, content,
and contact information.
Example
Two sections in a document:
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is an international
organization working on issues regarding the conservation,
research and restoration of the environment, formerly named the
World Wildlife Fund. WWF was founded in 1961.</p>
</section>
<section>
<h1>WWF's Panda symbol</h1>
<p>The Panda has become the symbol of WWF. The well-known panda
logo of WWF originated from a panda named Chi Chi that was
transferred from the Beijing Zoo to the London Zoo in the same
year of the establishment of WWF.</p>
</section>
Try it Yourself »
Forum posts
Blog posts
User comments
Product cards
Newspaper articles
Example
Three articles with independent, self-contained content:
<article>
<h2>Google Chrome</h2>
<p>Google Chrome is a web browser developed by Google, released
in 2008. Chrome is the world's most popular web browser today!
</p>
</article>
<article>
<h2>Mozilla Firefox</h2>
<p>Mozilla Firefox is an open-source web browser developed by
Mozilla. Firefox has been the second most popular web browser
since January, 2018.</p>
</article>
<article>
<h2>Microsoft Edge</h2>
<p>Microsoft Edge is a web browser developed by Microsoft,
released in 2015. Microsoft Edge replaced Internet Explorer.</p>
</article>
Try it Yourself »
Example 2
Use CSS to style the <article> element:
<html>
<head>
<style>
.all-browsers {
margin: 0;
padding: 5px;
background-color: lightgray;
}
.browser {
background: white;
}
<article class="all-browsers">
<h1>Most Popular Browsers</h1>
<article class="browser">
<h2>Google Chrome</h2>
<p>Google Chrome is a web browser developed by Google,
released in 2008. Chrome is the world's most popular web browser
today!</p>
</article>
<article class="browser">
<h2>Mozilla Firefox</h2>
<p>Mozilla Firefox is an open-source web browser developed by
Mozilla. Firefox has been the second most popular web browser
since January, 2018.</p>
</article>
<article class="browser">
<h2>Microsoft Edge</h2>
<p>Microsoft Edge is a web browser developed by Microsoft,
released in 2015. Microsoft Edge replaced Internet Explorer.</p>
</article>
</article>
</body>
</html>
Try it Yourself »
Can we use the definitions to decide how to nest those elements? No, we
cannot!
Note: You can have several <header> elements in one HTML document.
However, <header> cannot be placed within a <footer>, <address> or
another <header> element.
Example
A header for an <article>:
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's
natural environment,
and build a future in which humans live in harmony with
nature.</p>
</article>
Try it Yourself »
authorship information
copyright information
contact information
sitemap
back to top links
related documents
Example
A footer section in a document:
<footer>
<p>Author: Hege Refsnes</p>
<p><a href="[Link]
</footer>
Try it Yourself »
Notice that NOT all links of a document should be inside a <nav> element.
The <nav> element is intended only for major blocks of navigation links.
Browsers, such as screen readers for disabled users, can use this element to
determine whether to omit the initial rendering of this content.
Example
A set of navigation links:
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
Try it Yourself »
Example
Display some content aside from the content it is placed in:
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<aside>
<h4>Epcot Center</h4>
<p>Epcot is a theme park at Walt Disney World Resort featuring
exciting attractions, international pavilions, award-winning
fireworks and seasonal special events.</p>
</aside>
Try it Yourself »
Example 2
Use CSS to style the <aside> element:
<html>
<head>
<style>
aside {
width: 30%;
padding-left: 15px;
margin-left: 15px;
float: right;
font-style: italic;
background-color: lightgray;
}
</style>
</head>
<body>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<aside>
<p>The Epcot center is a theme park at Walt Disney World Resort
featuring exciting attractions, international pavilions, award-
winning fireworks and seasonal special events.</p>
</aside>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
<p>My family and I visited The Epcot center this summer. The
weather was nice, and Epcot was amazing! I had a great summer
together with my family!</p>
</body>
</html>
Try it Yourself »
Example
<figure>
<img src="pic_trulli.jpg" alt="Trulli">
<figcaption>Fig1. - Trulli, Puglia, Italy.</figcaption>
</figure>
Try it Yourself »
Tag Description
<article> Defines independent, self-contained content
<details> Defines additional details that the user can view or hide
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Exercise?
Which one of the following is NOT an HTML element?
<header>
<footer>
<content>
<main>
Submit Answer »
❮ PreviousNext ❯
HTML Style Guide
❮ PreviousNext ❯
Consistent, clean, and tidy HTML code makes it easier for others to read
and understand your code.
Here are some guidelines and tips for creating good HTML code.
<!DOCTYPE html>
Good:
<body>
<p>This is a paragraph.</p>
</body>
Bad:
<BODY>
<P>This is a paragraph.</P>
</BODY>
Good:
<section>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</section>
Bad:
<section>
<p>This is a paragraph.
<p>This is a paragraph.
</section>
Good:
<a href="[Link] our HTML
tutorial</a>
Bad:
<a HREF="[Link] our HTML
tutorial</a>
Good:
<table class="striped">
Bad:
<table class=striped>
Very bad:
This will not work, because the value contains spaces:
Also, always define the width and height of images. This reduces flickering,
because the browser can reserve space for the image before loading.
Good:
<img src="[Link]" alt="HTML5" style="width:128px;height:128px"
>
Bad:
<img src="[Link]">
Good:
<link rel="stylesheet" href="[Link]">
Bad:
<link rel = "stylesheet" href = "[Link]">
For readability, add blank lines to separate large or logical code blocks.
For readability, add two spaces of indentation. Do not use the tab key.
Good:
<body>
<h1>Famous Cities</h1>
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo
Area, and the most populous metropolitan area in the world.</p>
<h2>London</h2>
<p>London is the capital city of England. It is the most populous
city in the United Kingdom.</p>
<h2>Paris</h2>
<p>Paris is the capital of France. The Paris area is one of the
largest population centers in Europe.</p>
</body>
Bad:
<body>
<h1>Famous Cities</h1>
<h2>Tokyo</h2><p>Tokyo is the capital of Japan, the center of the
Greater Tokyo Area, and the most populous metropolitan area in
the world.</p>
<h2>London</h2><p>London is the capital city of England. It is
the most populous city in the United Kingdom.</p>
<h2>Paris</h2><p>Paris is the capital of France. The Paris area
is one of the largest population centers in Europe.</p>
</body>
The contents of a page title is very important for search engine optimization
(SEO)! The page title is used by search engine algorithms to decide the order
when listing pages in search results.
Example
<!DOCTYPE html>
<head>
<title>Page Title</title>
</head>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
Try it Yourself »
However, we strongly recommend to always add
the <html> and <body> tags!
Omitting <html> and <body> can also crash DOM and XML software.
Omitting <head>?
The HTML <head> tag can also be omitted.
Browsers will add all elements before <body>, to a default <head> element.
Example
<!DOCTYPE html>
<html>
<title>Page Title</title>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Try it Yourself »
Allowed:
<meta charset="utf-8">
Also Allowed:
<meta charset="utf-8" />
If you expect XML/XHTML software to access your page, keep the closing
slash (/), because it is required in XML and XHTML.
Example
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Try it Yourself »
Meta Data
To ensure proper interpretation and correct search engine indexing, both the
language and the character encoding <meta charset="charset"> should
be defined as early as possible in an HTML document:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
Setting The Viewport
The viewport is the user's visible area of a web page. It varies with the device
- it will be smaller on a mobile phone than on a computer screen.
You should include the following <meta> element in all your web pages:
This gives the browser instructions on how to control the page's dimensions
and scaling.
The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is
first loaded by the browser.
Here is an example of a web page without the viewport meta tag, and the
same web page with the viewport meta tag:
Tip: If you are browsing this page with a phone or a tablet, you can click on
the two links below to see the difference.
Without the viewport meta tag
HTML Comments
Short comments should be written on one line, like this:
Comments that spans more than one line, should be written like this:
<!--
This is a long comment example. This is a long comment example.
This is a long comment example. This is a long comment example.
-->
Long comments are easier to observe if they are indented with two spaces.
[Link] {font-family:Verdana;font-size:16em;}
body {
background-color: lightgrey;
font-family: "Arial Black", Helvetica, sans-serif;
font-size: 16em;
color: black;
}
<script src="[Link]">
Example
getElementById("Demo").innerHTML = "Hello";
getElementById("demo").innerHTML = "Hello";
Try it Yourself »
Other web servers (Microsoft, IIS) are not case sensitive: "[Link]" can be
accessed as "[Link]".
If you use a mix of uppercase and lowercase, you have to be aware of this.
File Extensions
HTML files should have a .html extension (.htm is allowed).
Both will be treated as HTML by any web browser and web server.
Default Filenames
When a URL does not specify a filename at the end (like
"[Link] the server just adds a default filename, such
as "[Link]", "[Link]", "[Link]", or "[Link]".
However, servers can be configured with more than one default filename;
usually you can set up as many default filenames as you want.
❮ PreviousNext ❯
HTML Entities
❮ PreviousNext ❯
If you use the less than (<) or greater than (>) signs in your HTML text, the
browser might mix them with tags.
&entity_name;
&#entity_number;
Non-breaking Space
A commonly used HTML entity is the non-breaking space:
A non-breaking space is a space that will not break into a new line.
Two words separated by a non-breaking space will stick together (not break
into a new line). This is handy when breaking the words might be disruptive.
Examples:
§ 10
10 km/h
10 PM
If you write 10 spaces in your text, the browser will remove 9 of them. To add
real spaces to your text, you can use the character entity.
Note
Entity names are case sensitive.
Some diacritical marks, like grave ( ̀) and acute ( ́) are called accents.
̀ a à à
́ a á á
̂ a â â
̃ a ã ã
̀ O Ò Ò
́ O Ó Ó
̂ O Ô Ô
̃ O Õ Õ
Exercise?
What is the entity name that represents a less than < sign?
<
&less;
Submit Answer »
HTML Symbols
❮ PreviousNext ❯
Symbols or letters that are not present on your keyboard can be added to
HTML using entities.
To add such symbols to an HTML page, you can use the entity name or the
entity number (a decimal or a hexadecimal reference) for the symbol:
Example
Display the euro sign:
Try it Yourself »
Emoji Value
🗻 Try it »
🗻
🗼 Try it »
🗼
🗽 Try it »
🗽
🗾 Try it »
🗾
🗿 Try it »
🗿
😀 😀 Try it »
😁 😁 Try it »
😂 😂 Try it »
😃 😃 Try it »
😄 😄 Try it »
😅 😅 Try it »
💺💻💼💽💾
👮👯👰👱👲
🐂🐃🐄🐅🐆
They are letters (characters) from the UTF-8 (Unicode) character set.
UTF-8 covers almost all of the characters and symbols in the world.
<meta charset="UTF-8">
UTF-8 Characters
Many UTF-8 characters cannot be typed on a keyboard, but they can always
be displayed using numbers (called entity numbers):
A is 65
B is 66
C is 67
Example
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
</body>
</html>
Try it Yourself »
Example Explained
The <meta charset="UTF-8"> element defines the character set.
The characters A, B, and C, are displayed by the numbers 65, 66, and 67.
To let the browser understand that you are displaying a character, you must
start the entity number with &# and end it with ; (semicolon).
Emoji Characters
Emojis are also characters from the UTF-8 alphabet:
😄 is 128516
😍 is 128525
💗 is 128151
Example
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<p>😀</p>
<p>😀</p><p>😀</p><p>😀</p>
</body>
</html>
Try it Yourself »
Since Emojis are characters, they can be copied, displayed, and sized just like
any other character in HTML.
Example
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<h1>Sized Emojis</h1>
<p style="font-size:48px">
😀 😄 😍 💗
</p>
</body>
</html>
Try it Yourself »
Example
<meta charset="UTF-8">
UTF-8 covers almost all of the characters and symbols in the world!
<meta charset="Windows-1252">
HTML 4 Example
<meta http-equiv="Content-Type" content="text/html;charset=ISO-
8859-1">
HTML 5 Example
<meta charset="ISO-8859-1">
<meta charset="UTF-8">
32 space
33 ! ! ! ! exclamation mark
35 # # # # number sign
36 $ $ $ $ dollar sign
37 % % % % percent sign
40 ( ( ( ( left parenthesis
41 ) ) ) ) right parenthesis
42 * * * * asterisk
43 + + + + plus sign
44 , , , , comma
45 - - - - hyphen-minus
46 . . . . full stop
47 / / / / solidus
48 0 0 0 0 digit zero
49 1 1 1 1 digit one
50 2 2 2 2 digit two
51 3 3 3 3 digit three
52 4 4 4 4 digit four
53 5 5 5 5 digit five
54 6 6 6 6 digit six
55 7 7 7 7 digit seven
56 8 8 8 8 digit eight
57 9 9 9 9 digit nine
58 : : : : colon
59 ; ; ; ; semicolon
61 = = = = equals sign
63 ? ? ? ? question mark
64 @ @ @ @ commercial at
65 A A A A Latin A
66 B B B B Latin B
67 C C C C Latin C
68 D D D D Latin D
69 E E E E Latin E
70 F F F F Latin F
71 G G G G Latin G
72 H H H H Latin H
73 I I I I Latin I
74 J J J J Latin J
75 K K K K Latin K
76 L L L L Latin L
77 M M M M Latin M
78 N N N N Latin N
79 O O O O Latin O
80 P P P P Latin P
81 Q Q Q Q Latin Q
82 R R R R Latin R
83 S S S S Latin S
84 T T T T Latin T
85 U U U U Latin U
86 V V V V Latin V
87 W W W W Latin W
88 X X X X Latin X
89 Y Y Y Y Latin Y
90 Z Z Z Z Latin Z
91 [ [ [ [ left square bracket
92 \ \ \ \ reverse solidus
94 ^ ^ ^ ^ circumflex accent
95 _ _ _ _ low line
96 ` ` ` ` grave accent
97 a a a a Latin small a
98 b b b b Latin small b
99 c c c c Latin small c
126 ~ ~ ~ ~ tilde
127 DEL
134 † dagger
149 • bullet
150 – en dash
151 — em dash
168 ¨ ¨ ¨ diaeresis
184 ¸ ¸ ¸ cedilla
198 Æ Æ Æ Latin AE
199 Ç Ç Ç Latin C with cedilla
Most people enter the name when surfing, because names are easier to
remember than numbers.
scheme://[Link]:port/path/filename
Explanation:
URL Encoding
URLs can only be sent over the Internet using the ASCII character-set. If a
URL contains characters outside the ASCII set, the URL has to be converted.
URLs cannot contain spaces. URL encoding normally replaces a space with a
plus (+) sign, or %20.
Try It Yourself
Hello Günter Submit
If you click "Submit", the browser will URL encode the input before it is sent
to the server.
€ %80 %E2%82%AC
£ %A3 %C2%A3
© %A9 %C2%A9
® %AE %C2%AE
À %C0 %C3%80
Á %C1 %C3%81
 %C2 %C3%82
à %C3 %C3%83
Ä %C4 %C3%84
Å %C5 %C3%85
For a complete reference of all URL encodings, visit our URL Encoding
Reference.
What is XHTML?
XHTML stands for EXtensible HyperText Markup Language
XHTML is a stricter, more XML-based version of HTML
XHTML is HTML defined as an XML application
XHTML is supported by all major browsers
Why XHTML?
XML is a markup language where all documents must be marked up correctly
(be "well-formed").
XHTML was developed to make HTML more extensible and flexible to work
with other data formats (such as XML). In addition, browsers ignore errors in
HTML pages, and try to display the website even if it has some errors in the
markup. So XHTML comes with a much stricter error handling.
Example
Here is an XHTML document with a minimum of required tags:
</body>
</html>
Correct:
<b><i>Some text</i></b>
Wrong:
<b><i>Some text</b></i>
Wrong:
<p>This is a paragraph
<p>This is another paragraph
Correct:
A break: <br />
A horizontal rule: <hr />
An image: <img src="[Link]" alt="Happy face" />
Wrong:
A break: <br>
A horizontal rule: <hr>
An image: <img src="[Link]" alt="Happy face">
Correct:
<body>
<p>This is a paragraph</p>
</body>
Wrong:
<BODY>
<P>This is a paragraph</P>
</BODY>
Correct:
<a href="[Link] our HTML
tutorial</a>
Wrong:
<a HREF="[Link] our HTML
tutorial</a>
Correct:
<a href="[Link] our HTML
tutorial</a>
Wrong:
<a href=[Link] our HTML
tutorial</a>
Correct:
<input type="checkbox" name="vehicle" value="car" checked="checke
d" />
<input type="text" name="lastname" disabled="disabled" />
Wrong:
<input type="checkbox" name="vehicle" value="car" checked />
<input type="text" name="lastname" disabled />
[Link] w w .w [Link]/html/html_validate.html
An HTML form is used to collect user input. The user input is most often
sent to a server for processing.
Example
First name:
John
Last name:
Doe
Submit
Try it Yourself »
The <form> 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.
Type Description
<input type="radio"> Displays a radio button (for selecting one of many choice
Text Fields
The <input type="text"> 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 »
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 <label> element is useful for screen-reader users, because the screen-
reader will read out loud the label when the user focuses on the input
element.
The <label> element also helps users who have difficulty clicking on very
small regions (such as radio buttons or checkboxes) - because when the user
clicks the text within the <label> element, it toggles the radio
button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.
Radio Buttons
The <input type="radio"> defines a radio button.
Example
A form with radio buttons:
<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 »
HTML
CSS
JavaScript
Checkboxes
The <input type="checkbox"> defines a checkbox.
Example
A form with checkboxes:
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bik
e">
<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="Boa
t">
<label for="vehicle3"> I have a boat</label>
</form>
Try it Yourself »
I have a bike
I have a car
I have a boat
The form-handler is typically a file on the server with a script for processing
input data.
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 »
First name:
John
Last name:
Doe
Submit
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 »
Exercise?
What is the correct HTML element for defining a form?
<schema>
<ff>
<form>
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.
Value Description
Example
Here, the submitted result will open in a new browser tab:
Try it Yourself »
Example
This example uses the GET method when submitting the form data:
Try it Yourself »
Example
This example uses the POST method when submitting the form data:
Try it Yourself »
Notes on GET:
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!
Example
A form with autocomplete on:
Try it Yourself »
When present, it specifies that the form-data (input) should not be validated
when submitted.
Example
A form with a novalidate attribute:
Try it Yourself »
Exercise?
What is the correct syntax for opening the form's result in a new browser tab?
Submit Answer »
enctype Specifies how the form-data should be encoded when submitting it to the server (only for meth
novalidate Specifies that the form should not be validated when submitted
rel Specifies the relationship between a linked resource and the current document
target Specifies where to display the response that is received after submitting the form
Example
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname">
Try it Yourself »
All the different values of the type attribute are covered in the next
chapter: HTML Input Types.
The <label> 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 <label> 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 <label> element, it toggles the radio button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.
The <select> Element
The <select> element defines a drop-down list:
Example
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Try it Yourself »
Example
<option value="fiat" selected>Fiat</option>
Try it Yourself »
Visible Values:
Use the size attribute to specify the number of visible values:
Example
<label for="cars">Choose a car:</label>
<select id="cars" name="cars" size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Try it Yourself »
Allow Multiple Selections:
Use the multiple attribute to allow the user to select more than one value:
Example
<label for="cars">Choose a car:</label>
<select id="cars" name="cars" size="4" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Try it Yourself »
Example
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
Try it Yourself »
The rows attribute specifies the visible number of lines in a text area.
You can also define the size of the text area by using CSS:
Example
<textarea name="message" style="width:200px; height:600px;">
The cat was playing in the garden.
</textarea>
Try it Yourself »
Example
<button type="button" onclick="alert('Hello World!')">Click Me!
</button>
Try it Yourself »
Click Me!
Note: Always specify the type attribute for the button element. Different
browsers may use different default types for the button element.
Example
<form action="/action_page.php">
<fieldset>
<legend>Personalia:</legend>
<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><b
r>
<input type="submit" value="Submit">
</fieldset>
</form>
Try it Yourself »
Personalia:First name:
John
Last name:
Doe
Submit
Users will see a drop-down list of the pre-defined options as they input data.
The list attribute of the <input> element, must refer to the id attribute of
the <datalist> element.
Example
<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
Try it Yourself »
The <output> Element
The <output> element represents the result of a calculation (like one
performed by a script).
Example
Perform a calculation and show the result in an <output> element:
<form action="/action_page.php"
oninput="[Link]=parseInt([Link])+parseInt([Link])">
0
<input type="range" id="a" name="a" value="50">
100 +
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
<br><br>
<input type="submit">
</form>
Try it Yourself »
Exercise?
What is the correct HTML element to group related data in a form and also, by default,
draw a border around it?
<group>
<fieldset>
<fence>
Submit Answer »
HTML Form Elements
Tag Description
For a complete list of all available HTML tags, visit our HTML Tag Reference.
This chapter describes the different types for the HTML <input> element.
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="submit">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">
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 »
First name:
Last name:
Try it Yourself »
Username:
Password:
The form-handler is typically a server page with a script for processing input
data.
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 »
Last name:
Doe
Submit
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 »
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" value="Reset">
</form>
Try it Yourself »
Last name:
Doe
Submit Reset
If you change the input values and then click the "Reset" button, the form-
data will be reset to the default values.
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 »
HTML
CSS
JavaScript
Input Type Checkbox
<input type="checkbox"> defines a checkbox.
Example
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bik
e">
<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="Boa
t">
<label for="vehicle3"> I have a boat</label>
</form>
Try it Yourself »
I have a bike
I have a car
I have a boat
Example
<input type="button" onclick="alert('Hello World!')" value="Click
Me!">
Try it Yourself »
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 »
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 »
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" nam
e="birthdaytime">
</form>
Try it Yourself »
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 Image
The <input type="image"> defines an image as a submit button.
Example
<form>
<input type="image" src="img_submit.gif" alt="Submit" width="48"
height="48">
</form>
Try it Yourself »
Example
<form>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
</form>
Try it Yourself »
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 »
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 »
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:
Attribute Description
checked Specifies that an input field should be pre-selected when the page lo
type="checkbox" or type="radio")
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 »
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 »
Example
<form>
<label for="gsearch">Search Google:</label>
<input type="search" id="gsearch" name="gsearch">
</form>
Try it Yourself »
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 »
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 »
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 »
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 »
Exercise?
What is the default value of the INPUT element's type attribute?
button
submit
text
Submit Answer »
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 »
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" readonl
y><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
Try it Yourself »
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" disable
d><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>
Try it Yourself »
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 »
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 »
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>
Try it Yourself »
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.
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 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, number, 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 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 »
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)!
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 »
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 »
Example
An <input> element with pre-defined values in a <datalist>:
<form>
<input list="browsers">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
Try it Yourself »
The autocomplete attribute works with <form> and the following <input> types:
text, search, url, tel, email, password, datepickers, range, and color.
Example
An HTML form with autocomplete on, and off for one input field:
Try it Yourself »
Exercise?
What is the default value of the INPUT element's size attribute?
10
15
20
Submit Answer »
HTML Form and Input Elements
Tag Description
For a complete list of all available HTML tags, visit our HTML Tag Reference.
Example
An input field located outside of the HTML form (but still a part of the form):
Try it Yourself »
Note: This attribute overrides the action attribute of the <form> 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="Subm
it 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 <form> 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":
Try it Yourself »
Note: This attribute overrides the method attribute of the <form> element.
The formmethod attribute works with the following input types: submit and
image.
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":
Try it Yourself »
Note: This attribute overrides the target attribute of the <form> 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 »
Note: This attribute overrides the novalidate attribute of the <form> 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 »
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:
Try it Yourself »
Exercise?
What is not a legal form attribute for the INPUT element?
formaction
formtype
formtarget
Submit Answer »
The graphic to the left is created with <canvas>. It shows four elements: a
red rectangle, a gradient rectangle, a multicolor rectangle, and a
multicolor text.
What is HTML Canvas?
The HTML <canvas> element is used to draw graphics, on the fly, via
JavaScript.
The <canvas> element is only a container for graphics. You must use
JavaScript to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and
adding images.
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no
border and no content.
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.
Draw a Line
Example
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link](0, 0);
[Link](200, 100);
[Link]();
</script>
Try it Yourself »
Draw a Circle
Example
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link]();
[Link](95, 50, 40, 0, 2 * [Link]);
[Link]();
</script>
Try it Yourself »
Draw a Text
Example
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World", 10, 50);
</script>
Try it Yourself »
Stroke Text
Example
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World", 10, 50);
</script>
Try it Yourself »
// Create gradient
var grd = [Link](0, 0, 200, 0);
[Link](0, "red");
[Link](1, "white");
Try it Yourself »
Draw Circular Gradient
Example
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
// Create gradient
var grd = [Link](75, 50, 5, 90, 60, 100);
[Link](0, "red");
[Link](1, "white");
Try it Yourself »
Draw Image
Example
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
var img = [Link]("scream");
[Link](img, 10, 10);
</script>
Try it Yourself »
SVG graphics are scalable, and do not lose any quality if they are zoomed or
resized:
SVG
What is SVG?
SVG stands for Scalable Vector Graphics
SVG is used to define vector-based graphics for the Web
SVG defines graphics in XML format
Each element and attribute in SVG files can be animated
SVG is a W3C recommendation
SVG integrates with other standards, such as CSS, DOM, XSL and
JavaScript
SVG Circle
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
SVG Rectangle
Example
<svg width="400" height="120">
<rect x="10" y="10" width="200" height="100" stroke="red" strok
e-width="6" fill="blue" />
</svg>
Try it Yourself »
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 »
Example
<svg height="130" width="500">
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="yellow" />
<stop offset="100%" stop-color="red" />
</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, while Canvas draws 2D
graphics, on the fly (with JavaScript).
SVG is XML based, which means that every element is available within the
SVG DOM. You can attach JavaScript event handlers to SVG graphics.
SVG Canvas
SVG Tutorial
To learn more about SVG, please read our SVG Tutorial.
HTML Multimedia
❮ PreviousNext ❯
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.
MPEG .mpg MPEG. Developed by the Moving Pictures Expert Group. The first po
.mpeg on the web. Not supported anymore in HTML.
RealVideo .rm RealVideo. Developed by Real Media to allow video streaming with
.ram Does not play in web browsers.
Flash .swf Flash. Developed by Macromedia. Often requires an extra compone
.flv in web browsers.
WebM .webm WebM. Developed by Mozilla, Opera, Adobe, and Google. Supported
MPEG-4 .mp4 MP4. Developed by the Moving Pictures Expert Group. Commonly us
or MP4 cameras and TV hardware. Supported by all browsers and recomm
YouTube.
Note: Only MP4, WebM, and Ogg video are supported by the HTML standard.
MIDI .mid MIDI (Musical Instrument Digital Interface). Main format for all electro
.midi like synthesizers and PC sound cards. MIDI files do not contain sound,
that can be played by electronics. Plays well on all computers and mu
not in web browsers.
RealAudi .rm RealAudio. Developed by Real Media to allow streaming of audio with
o .ram Does not play in web browsers.
WMA .wma WMA (Windows Media Audio). Developed by Microsoft. Plays well on W
computers, but not in web browsers.
AAC .aac AAC (Advanced Audio Coding). Developed by Apple as the default for
Plays well on Apple computers, but not in web browsers.
WAV .wav WAV. Developed by IBM and Microsoft. Plays well on Windows, Macint
operating systems. Supported by HTML.
MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the most p
music players. Combines good compression (small files) with high qua
by all browsers.
MP4 .mp4 MP4 is a video format, but can also be used for audio. Supported by a
Note: Only MP3, WAV, and Ogg audio are supported by the HTML standard.
HTML Video
❮ PreviousNext ❯
Video
Example
Courtesy of Big Buck Bunny:
Try it Yourself »
Example
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" 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.
Example
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" type="video/ogg">
Your browser does not support the video tag.
</video>
Try it Yourself »
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="[Link]" 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
WebM video/webm
Ogg video/ogg
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.
Try it Yourself »
<source> Defines multiple media resources for media elements, such as <vid
HTML Audio
❮ PreviousNext ❯
The HTML <audio> element is used to play an audio file on a web page.
Example
<audio controls>
<source src="[Link]" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Try it Yourself »
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.
Example
<audio controls autoplay>
<source src="[Link]" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Try it Yourself »
Add muted after autoplay to let your audio file start playing automatically (but
muted):
Example
<audio controls autoplay muted>
<source src="[Link]" 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
*From Edge 79
MP3 audio/mpeg
OGG audio/ogg
WAV audio/wav
There are also DOM events that can notify you when an audio begins to play,
is paused, etc.
<source> Defines multiple media resources for media elements, such as <video>
HTML Plug-ins
❮ PreviousNext ❯
Plug-ins
Plug-ins were designed to be used for many different purposes:
Warning !
The support for Shockwave Flash has also been turned off in modern
browsers.
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="[Link]"></object>
Try it Yourself »
Example
<object data="[Link]"></object>
Try it Yourself »
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="[Link]">
Try it Yourself »
Note that the <embed> element does not have a closing tag. It can not
contain alternative text.
Example
<embed width="100%" height="500px" src="[Link]">
Try it Yourself »
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.
Example
<iframe width="420" height="315"
src="[Link]
</iframe>
Try it Yourself »
Try it Yourself »
YouTube Playlist
A comma separated list of videos to play (in addition to the original URL).
YouTube Loop
Add playlist=videoID and loop=1 to let your video loop forever.
Try it Yourself »
YouTube Controls
Add controls=0 to NOT display controls in the video player.
YouTube - Controls
<iframe width="420" height="315"
src="[Link]
</iframe>
Try it Yourself »
1. Geolocation API - This API is used to access the current location of a user
(with latitude and longitude).
2. Drag and Drop API - This API enables you to use drag-and-drop features
in browsers.
3. Web Storage API - This API has mechanisms to let browsers store
key/value pairs (in a more intuitive way than cookies).
4. Web Workers API - This API allows a JavaScript to run in the background,
without affecting the performance of the page. Users can continue to do
whatever they want: clicking, selecting things, etc., while the web worker
runs in the background.
6. Canvas API - This API lets you draw graphics, on the fly, via JavaScript.
Check Browser Capability - Always check that the target browsers support
the API. Always add script or message to be run if a browser does not support
it.
Add Robust Error Handling - Add robust error handling to take care of
scenarios where an API may not function as expected, to ensure a seamless
user experience.
To use these APIs, you will have to download the code from the Web.
Examples:
Since this can compromise privacy, the location is not available unless the
user approves it.
Try It
Tip: The Geolocation API is most accurate for devices with GPS, like
smartphones or smartwatches.
Browser Support
The numbers in the table specify the first browser version that fully supports
Geolocation.
API
The example below returns the latitude and longitude of the user's current
location:
Example
<script>
const x = [Link]("demo");
function getLocation() {
if ([Link]) {
[Link](success, error);
} else {
[Link] = "Geolocation is not supported by this
browser.";
}
}
function success(position) {
[Link] = "Latitude: " + [Link] +
"<br>Longitude: " + [Link];
}
function error() {
alert("Sorry, no position available.");
}
</script>
Try it Yourself »
Example explained:
Example
function error(error) {
switch([Link]) {
case error.PERMISSION_DENIED:
[Link] = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
[Link] = "Location information is unavailable."
break;
case [Link]:
[Link] = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
[Link] = "An unknown error occurred."
break;
}
}
Try it Yourself »
Location-specific Information
Geolocation is also very useful for location-specific information, like:
Property Returns
[Link] The altitude in meters above the mean sea level (returned if av
[Link] The altitude accuracy of position (returned if available)
y
The example below shows the watchPosition() method. You need an accurate
GPS device to test this (like a smartphone):
Example
<script>
const x = [Link]("demo");
function getLocation() {
if ([Link]) {
[Link](success, error);
} else {
[Link] = "Geolocation is not supported by this
browser.";
}
}
function success(position) {
[Link] = "Latitude: " + [Link] +
"<br>Longitude: " + [Link];
}
function error(error) {
switch([Link]) {
case error.PERMISSION_DENIED:
[Link] = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
[Link] = "Location information is unavailable."
break;
case [Link]:
[Link] = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
[Link] = "An unknown error occurred."
break;
}
}
</script>
Try it Yourself »
The HTML Drag and Drop API enables an element to be dragged and
dropped.
Example
Drag the W3Schools image into the second rectangle.
Browser Support
The numbers in the table specify the first browser version that fully supports
Drag and Drop.
API
Example
<!DOCTYPE HTML>
<html>
<head>
<script>
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
function dragoverHandler(ev) {
[Link]();
}
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>
</body>
</html>
Try it Yourself »
It might seem complicated, but lets go through all the different parts of a
drag and drop event.
or:
In the example above, the ondragstart attribute of the <img> element calls a
function (dragstartHandler(ev)), that specifies what data to be dragged.
The [Link]() method sets the data type and the value of the
dragged data:
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
In this case, the data type is "text" and the value is the id of the draggable
element ("img1").
This is done by calling the preventDefault() method for the ondragover event:
function dragoverHandler(ev) {
[Link]();
}
In the example above, the ondrop attribute of the <div> element calls a
function, dropHandler(event):
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
Code explained:
More Examples
Example
How to drag and drop an <h1> element to a <div> element:
<script>
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
function dragoverHandler(ev) {
[Link]();
}
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>
Try it Yourself »
Example
How to drag and drop an <a> element to a <div> element:
<script>
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
function dragoverHandler(ev) {
[Link]();
}
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>
Try it Yourself »
Example
How to drag and drop an image back and forth between two <div> elements:
Try it Yourself »
HTML Web Storage API
❮ PreviousNext ❯
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
Example
Test browser support:
<script>
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
[Link] = "Your browser supports Web storage!";
} else {
[Link] = "Sorry, no Web storage support!";
}
</script>
Try it Yourself »
Example
Use localStorage to set and retrieve name and value pairs:
<script>
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
// Store
[Link]("lastname", "Smith");
[Link]("bgcolor", "yellow");
// Retrieve
[Link] = [Link]("lastname");
[Link] = [Link]("bgcolor");
} else {
[Link] = "Sorry, no Web storage support!";
}
</script>
Try it Yourself »
Example explained:
[Link]("lastname");
Example
<script>
function clickCounter() {
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
if ([Link]) {
[Link] = Number([Link])
+1;
} else {
[Link] = 1;
}
[Link] = "You have clicked the button
" + [Link] + " time(s)!";
} else {
[Link] = "Sorry, no Web storage support!";
}
}
</script>
Try it Yourself »
Example
<script>
function clickCounter() {
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
if ([Link]) {
[Link] =
Number([Link])+1;
} else {
[Link] = 1;
}
[Link] = "You have clicked the button
" + [Link] + " time(s) in this session!";
} else {
[Link] = "Sorry, no Web storage support!";
}
}
</script>
Try it Yourself »
Web workers are useful for heavy code that can't be run on the main thread,
without causing long tasks that make the page unresponsive.
Browser Support
The numbers in the table specify the first browser version that fully support
the Web Workers API.
API
Example
Count numbers:
Try it Yourself »
Note: Normally web workers are not used for such simple scripts, but for
more CPU intensive tasks!
Example
Test browser support:
<script>
const x = [Link]("result");
if(typeof(Worker) !== "undefined") {
[Link] = "Your browser support Web Workers!";
} else {
[Link] = "Sorry, your browser does not support Web
Workers.";
}
</script>
Try it Yourself »
Create a .js Web Worker File
Now, let's create a web worker in an external JavaScript file.
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
Note: The important part of the code above is the postMessage() method -
which is used to post messages back to the HTML page.
The following lines checks if a worker (w) already exists, if not - it creates a
new web worker object and points to the .js file: "demo_workers.js":
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
Then we can SEND and RETRIEVE messages from the web worker.
Data is sent between web workers and the main thread via a system of
messages - both sides send their messages using the postMessage() method,
and respond to messages via the onmessage event handler.
When the web worker in the .js posts a message, the code within the event
listener is executed. The data from the web worker is stored in [Link].
[Link]();
w = undefined;
Example
<!DOCTYPE html>
<html>
<body>
<script>
let w;
function startWorker() {
const x = [Link]("result");
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
[Link] = function(event) {
[Link] = [Link];
};
} else {
[Link] = "Sorry! No Web Worker support.";
}
}
function stopWorker() {
[Link]();
w = undefined;
}
</script>
</body>
</html>
Try it Yourself »
Normally, a web page has to request data from the server, but with server-
sent events, the updates are pushed automatically.
Browser Support
The numbers in the table specify the first browser version that fully support
the Server-Sent Events API.
API
Example
<script>
const x = [Link]("result");
// Check browser support for SSE
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
[Link] = function(event) {
[Link] += [Link] + "<br>";
};
} else {
[Link] = "Sorry, no support for server-sent events.";
}
</script>
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"
<?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();
?>
<%
[Link] = "text/event-stream"
[Link] = -1
[Link]("data: The server time is: " & now())
[Link]()
%>
Code explained: