1 - HTML Notes
1 - HTML Notes
HTML stands for Hypertext Markup Language. HTML is the basic building block of World Wide
Web. Hypertext is text displayed on a computer or other electronic device with references to other
text that the user can instantly access, by a mouse click or key press. Apart from text, hypertext
may have tables, lists, forms, images, and other presentational elements. Markup languages
use sets of markup tags to characterize text elements within a document, which gives instructions
to the web browsers on how the document should appear. HTML was originally developed by Tim
Berners-Lee in 1990. He is also known as the father of the web. In 1996, the World Wide Web
Consortium (W3C) became the authority to maintain the HTML specifications. HTML also became
an international standard (ISO) in 2000. HTML5 is the latest version of HTML. HTML5 provides a
faster and more robust approach to web development.
Note: HTML as described earlier is a markup language not a programming language, like
Java, Ruby, PHP, etc. You need a web browser to view the HTML pages. The web browsers do
not display the HTML tags, but uses the tags to interpret the content of the web pages.
Tip: I suggest you to use an HTML Editor; don't use Word or WordPad!
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting Started with HTML </title>
</head>
<body>
<p>Hello World!<p>
</body>
</html>
Note: It is important that the extension .html is specified — some text editors, such as
Notepad, will automatically save it as .txt otherwise.
To open the file in a browser. Navigate to your file then double click on it. It will open in your
default Web browser. If it does not, open your browser and drag the file to it.
Explanation of code
You might think what that code was all about. Well, let's find out.
• The first line <!DOCTYPE html> is the document type declaration. It instructs the web
browser that this document is an HTML5 document. It is case-insensitive.
• The <head> element is a container for the tags that provides information about the
document, for example, <title> tag defines the title of the document.
• The <body> element contains the document's actual content (paragraphs, links,
images, tables, and so on) that is rendered in the web browser and displayed to the
user.
For now, just focus on the basic structure of the HTML document.
Note: A DOCTYPE declaration appears at the top of a web page before all other elements;
however, the doctype declaration itself is not an HTML tag. Every HTML document requires a
document type declaration to ensure that your pages are displayed correctly.
Tip: The <html>, <head>, and <body> tags make up the basic skeleton of every web page.
Content inside the <head> and </head> are invisible to users with one exception: the text
between <title> and </title> tags which appears as the title on a browser tab.
Example
Try this code »
<p>This is a paragraph.</p> <!-- Paragraph with nested element -->
<p>
This is <b>another</b> paragraph.
</p>
You will learn about the various HTML elements in upcoming chapter.
Note: All elements don't require the end tag or closing tag to be present. These are referred
as empty elements, self-closing elements or void elements.
Example
Try this code »
<p>This is a paragraph.</p>
<P>This is also a valid paragraph.</P>
Tip: We recommend using lowercase for tag and attributing names in HTML, since by doing
this you can make your document more compliant for future upgrades.
Example
Try this code »
<p>Here is some <b>bold</b> text.</p>
<p>Here is some <em>emphasized</em> text.</p>
<p>Here is some <mark>highlighted</mark> text.</p>
Tip: Placing one element inside another is called nesting. A nested element, also called a child
element, can be a parent element too if other elements are nested within it.
HTML tags should be nested in correct order. They must be closed in the inverse order of how
they are defined, that means the last tag opened must be closed first.
Example
Try this code »
<p><strong>These tags are nested properly.</strong></p>
<p><strong>These tags are not nested properly.</p></strong>
Example
Try this code »
<!-- This is an HTML comment -->
<!-- This is a multi-line HTML comment
that spans across more than one line -->
<p>This is a normal piece of text.</p>
You can also comment out part of your HTML code for debugging purpose, as shown here:
Example
Try this code »
<!-- Hiding this image for testing
<img src="images/smiley.png" alt="Smiley">
-->
Note: The block-level elements should not be placed within inline-level elements. For
example, the <p> element should not be placed inside the <b> element.
Example
Try this code »
<img src="images/smiley.png" width="30" height="30" alt="Smiley">
<a href="https://www.google.com/" title="Search Engine">Google</a>
<abbr title="Hyper Text Markup Language">HTML</abbr>
<input type="text" value="John Doe">
In the above example src inside the <img> tag is an attribute and image path provided is its
value. Also, href inside the <a> tag is an attribute and the link provided is its value, etc.
Tip: Both single and double quotes can be used to quote attribute values. However, double
quotes are most common. In situations where the attribute value itself contains double quotes
it is necessary to wrap the value in single quotes, e.g., value='John "Williams" Jr.'
There are several attributes in HTML5 that do not consist of name/value pairs but consists of
just name. Such attributes are called Boolean attributes. Examples of some commonly used
Boolean attributes are checked, disabled, readonly, required, etc.
Example
Try this code »
<input type="email" required>
<input type="submit" value="Submit" disabled>
<input type="checkbox" checked>
<input type="text" value="Read only text" readonly>
You will learn about all these elements in detail in upcoming chapters.
Note: Attribute values are case-insensitive, except, like the id and class attributes. However,
World Wide Web Consortium (W3C) recommends lowercase for attributes values in their
specification.
The id Attribute
The id attribute is used to give a unique name or identifier to an element within a document.
This makes it easier to select the element using CSS or JavaScript.
Example
Try this code »
<input type="text" id="firstName">
<div id="container">Some content</div>
<p id="infoText">This is a paragraph.</p>
Note: The id of an element must be unique within a single document. No two elements in the
same document can be named with the same id, and each element can have only one id.
The class Attribute
Like the id attribute, the class attribute is also used to identify elements. But unlike id,
the class attribute does not have to be unique in a document. This means you can apply the
same class to multiple elements in a document, as shown in the following example:
Example
Try this code »
<input type="text" class="highlight">
<div class="box highlight">Some content</div>
<p class="highlight">This is a paragraph.</p>
Tip: Since a class can be applied to multiple elements, therefore any style rules that are
written to that class will be applied to all the elements having that class.
Example
Try this code »
<abbr title="World Wide Web Consortium">W3C</abbr>
<a href="images/kites.jpg" title="Click to view a larger image">
<img src="images/kites-thumb.jpg" alt="kites">
</a>
Tip: The value of the title attribute (i.e. title text) is displayed as a tooltip by the web browsers
when the user place mouse cursor over the element.
Example
Try this code »
<p style="color: blue;">This is a paragraph.</p>
<img src="images/sky.jpg" style="width: 300px;" alt="Cloudy Sky">
<div style="border: 1px solid red;">Some content</div>
You will learn more about styling HTML elements in HTML styles chapter.
The attributes we've discussed above are also called global attributes. For more global
attributes please check out the HTML5 global attributes reference.
A complete list of attributes for each HTML element is listed inside HTML5 tag reference.
HTML Headings
Organizing Content with Headings
Headings help in defining the hierarchy and the structure of the web page content. HTML
offers six levels of heading tags, <h1> through <h6>; the lower the heading level number,
the greater its importance — thus <h1> tag defines the most important heading, whereas
the <h6> tag defines the least important heading in the document.
By default, browsers display headings in larger and bolder font than normal text.
Also, <h1> headings are displayed in largest font, whereas <h6> headings are displayed in
smallest font.
Example
Try this code »
<h1>Heading level 1</h1>
<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>
— The output of the above example will look something like this:
Note: Each time you place a heading tag on a web page, the web browser built-in style sheets
automatically create some empty space (called margin) before and after each heading. You
can use the CSS margin property to override the browser's default style sheet.
Tip: You can easily customize the appearance of HTML heading tags such as their font size,
boldness, typeface, etc. using the CSS font properties.
Importance of Headings
• HTML headings provide valuable information by highlighting important topics and the
structure of the document, so optimize them carefully to improve user engagement.
• Don't use headings to make your text look BIG or bold. Use them only for highlighting
the heading of your document and to show the document structure.
• Since search engines, such as Google, use headings to index the structure and content
of the web pages so use them very wisely in your webpage.
• Use the <h1> headings as main headings of your web page, followed by
the <h2> headings, then the less important <h3> headings, and so on.
Tip: Use the <h1> tag to mark the most important heading which is usually at the top of the
page. An HTML document generally should have exactly one <h1> heading, followed by the
lower-level headings such as <h2>, <h3>, <h4>, and so on.
Example
Try this code »
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
Note: Browsers built-in style sheets automatically create some space above and below the
content of a paragraph (called margin), but you can override it using CSS.
Note: For the purposes of forwards-compatibility and good coding practice, it's advisable to
use both the opening and closing tags for the paragraphs.
Example
Try this code »
<p>This is a paragraph <br> with line break.</p>
<p>This is <br>another paragraph <br> with line breaks.</p>
Note: Don't use the empty paragraph i.e. <p></p> to add extra space in your web pages. The
browser may ignore the empty paragraphs since it is logical tag. Use the CSS margin property
instead to adjust the space around the elements.
Example
Try this code »
<p>This is a paragraph.</p>
<hr>
<p>This is another paragraph.</p>
Example
Try this code »
<p>This paragraph contains multiple spaces in the source code.</p>
<p>
This paragraph
contains multiple tabs and line breaks
in the source code.
</p>
Insert for creating extra consecutive spaces, while insert <br> tag for creating line
breaks on your web pages, as demonstrated in the following example:
Example
Try this code »
<p>This paragraph has multiple spaces.</p>
<p>This paragraph has multiple<br><br>line<br><br><br>breaks.</p>
The following example will display the text in the browser as it is in the source code:
Example
Try this code »
<pre>
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
</pre>
Tip: Text within the <pre> element is typically rendered by the browsers in a monospace or
fixed-width font, such as Courier, but you can override this using the CSS font property.
However, you can overwrite this using CSS. Learn more about styling links.
Anything between the opening <a> tag and the closing </a> tag becomes the part of the link
that the user sees and clicks in a browser. Here are some examples of the links:
Example
Try this code »
<a href="https://www.google.com/">Google Search</a>
<a href="https://www.tutorialrepublic.com/">Tutorial Republic</a>
<a href="images/kites.jpg">
<img src="kites-thumb.jpg" alt="kites">
</a>
The href attribute specifies the target of the link. Its value can be an absolute or relative URL.
An absolute URL is the URL that includes every part of the URL format, such as protocol, host
name, and path of the document,
e.g., https://www.google.com/, https://www.example.com/form.php, etc. While, relative URLs
are page-relative paths, e.g., contact.html, images/smiley.png, and so on. A relative URL
never includes the http:// or https:// prefix.
Example
Try this code »
<a href="/about-us.php" target="_top">About Us</a>
<a href="https://www.google.com/" target="_blank">Google</a>
<a href="images/sky.jpg" target="_parent">
<img src="sky-thumb.jpg" alt="Cloudy Sky">
</a>
Tip: If your web page is placed inside an iframe, you can use the target="_top" on the links
to break out of the iframe and show the target page in full browser window.
Example
Try this code »
<a href="#sectionA">Jump to Section A</a>
<h2 id="sectionA">Section A</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
Tip: You can even jump to a section of another web page by specifying the URL of that page
along with the anchor (i.e. #elementId) in the href attribute, for
example, <a href="mypage.html#topicA">Go to TopicA</a>.
Example
Try this code »
<p>This is <b>bold text</b>.</p>
<p>This is <strong>strongly important text</strong>.</p>
<p>This is <i>italic text</i>.</p>
<p>This is <em>emphasized text</em>.</p>
<p>This is <mark>highlighted text</mark>.</p>
<p>This is <code>computer code</code>.</p>
<p>This is <small>smaller text</small>.</p>
<p>This is <sub>subscript</sub> and <sup>superscript</sup> text.</p>
<p>This is <del>deleted text</del>.</p>
<p>This is <ins>inserted text</ins>.</p>
By default, the <strong> tag is typically rendered in the browser as <b>, whereas the <em> tag is
rendered as <i>. However, there is a difference in the meaning of these tags.
Example
Try this code »
<p>Cats are <em>cute</em> animals.</p>
<p>The <i>Royal Cruise</i> sailed last night.</p>
Note: Use the <em> and <strong> tags when the content of your page requires that certain
words or phrases should have strong emphasis or importance. Also, in HTML5
the <b> and <i> tags have been redefined, earlier they don't have semantic meaning.
Formatting Quotations
You can easily format the quotation blocks from other sources with the HTML <blockquote> tag.
Blockquotes are generally displayed with indented left and right margins, along with a little
extra space added above and below. Let's try an example to see how it works:
Example
Try this code »
<blockquote>
<p>Learn from yesterday, live for today, hope for tomorrow. The
important thing is not to stop questioning.</p>
<cite>— Albert Einstein</cite>
</blockquote>
Tip: The cite tag is used to describe a reference to a creative work. It must include the title of
that work or the name of the author (people or organization) or an URL reference.
For short inline quotations, you can use the HTML <q> tag. Most browsers display inline quotes
by surrounding the text in quotation marks. Here's an example:
Example
Try this code »
<p>According to the World Health Organization (WHO): <q>Health is a state
of complete physical, mental, and social well-being.</q></p>
Showing Abbreviations
An abbreviation is a shortened form of a word, phrase, or name. You can use the <abbr> tag to
denote an abbreviation. The title attribute is used inside this tag to provide the full expansion
of the abbreviation, which is displayed by the browsers as a tooltip when the mouse cursor is
hovered over the element. Let's try out an example:
Example
Try this code »
<p>The <abbr title="World Wide Web Consortium">W3C</abbr> is the main
international standards organization for the <abbr title="World Wide
Web">WWW or W3</abbr>. It was was founded by Tim Berners-Lee.</p>
This tag should ideally used to display contact information related to the document itself,
such as article's author. Most browsers display an address block in italic. Here's an example:
Example
Try this code »
<address>
Mozilla Foundation<br>
331 E. Evelyn Avenue<br>
Mountain View, CA 94041, USA
</address>
Please check out the HTML reference section for a complete list of HTML formatting tags.
• Inline styles — Using the style attribute in the HTML start tag.
• Embedded style — Using the <style> element in the head section of the document.
• External style sheet — Using the <link> element, pointing to an external CSS files.
In this tutorial we will cover all these different types of style sheet one by one.
Note: The inline styles have the highest priority, and the external style sheets have the lowest.
It means if you specify styles for your paragraphs in both embedded and external style sheets,
the conflicting style rules in the embedded style sheet would override the external style sheet.
Inline Styles: Inline styles are used to apply the unique style rules to an element, by
putting the CSS rules directly into the start tag. It can be attached to an element using
the style attribute. Style attribute has a series of CSS property and value pairs. Each property:
value pair is separated by a semicolon (;), just as you would write into an embedded or external
style sheet. But it needs to be all in one line i.e. no line break after the semicolon.
The following example demonstrates how to set the color and font-size of the text:
Example
Try this code »
<h1 style="color:red; font-size:30px;">This is a heading</h1>
<p style="color:green; font-size:18px;">This is a paragraph.</p>
<div style="color:green; font-size:18px;">This is some text.</div>
Using the inline styles are generally considered as a bad practice. Because style rules are
embedded directly inside the html tag, it causes the presentation to become mixed with the
content of the document, which makes updating or maintaining a website very difficult.
To learn about the various CSS properties in detail, please check out CSS tutorial section.
Note: It's become impossible to style pseudo-elements and pseudo-classes with inline styles.
You should, therefore, avoid the use of style attributes in your markup. Using external style
sheet is the preferred way to add style information to an HTML document.
Embedded style sheets are defined in the <head> section of an HTML document using
the <style> tag. You can define any number of <style> elements inside the <head> section.
The following example demonstrates how style rules are embedded inside a web page.
Example
Try this code »
<head>
<style>
body { background-color: YellowGreen; }
h1 { color: blue; }
p { color: red; }
</style>
</head>
You can attach external style sheets in two ways — linking and importing:
The <link> tag goes inside the <head> section, as shown here:
Example
Try this code »
<head>
<link rel="stylesheet" href="css/style.css">
</head>
Importing External Style Sheets
The @import rule is another way of loading an external style sheet. The @import statement
instructs the browser to load an external style sheet and use its styles. You can use it in two
ways. The simplest way is to use it within the <style> element in your <head> section. Note that,
other CSS rules may still be included in the <style> element.
Example
Try this code »
<style>
@import url("css/style.css");
p {
color: blue;
font-size: 16px;
}
</style>
Similarly, you can use the @import rule to import a style sheet within another style sheet.
Example
Try this code »
@import url("css/layout.css");
@import url("css/color.css");
body {
color: blue;
font-size: 14px;
}
Note: All @import rules must occur at the start of the style sheet. Any style rule defined in the
style sheet itself override conflicting rule in the imported style sheets. The @import rule may
cause performance issues, you should generally avoid importing style sheets.
HTML Images
Images into Web Pages Inserting
Images enhance visual appearance of the web pages by making them more interesting and
colorful. The <img> tag is used to insert images in the HTML documents. It is an empty element
and contains attributes only. The syntax of the <img> tag can be given with:
<img src="url" alt="some_text">
The src attribute tells the browser where to find the image. Its value is the URL of the image
file.
Whereas, the alt attribute provides an alternative text for the image, if it is unavailable or
cannot be displayed for some reason. Its value should be a meaningful substitute for the
image.
Note: Like <br> , the <img> element is also an empty element, and does not have a closing tag.
However, in XHTML it closes itself ending with "/>".
Tip: The required alt attribute provides alternative text description for an image if a user for
some reason cannot able to view it because of slow connection, image is not available at the
specified URL, or if the user uses a screen reader or non-graphical browser.
Example
Try this code »
<img src="kites.jpg" alt="Flying Kites" width="300" height="300">
<img src="sky.jpg" alt="Cloudy Sky" width="250" height="150">
<img src="balloons.jpg" alt="Balloons" width="200" height="200">
You can also use the style attribute to specify width and height for the images. It prevents
style sheets from changing the image size accidently, since inline style has the highest priority.
Example
Try this code »
<img src="kites.jpg" alt="Flying Kites" style="width: 300px; height:
300px;">
<img src="sky.jpg" alt="Cloudy Sky" style="width: 250px; height: 150px;">
<img src="balloons.jpg" alt="Balloons" style="width: 200px; height:
200px;">
Note: It's a good practice to specify both the width and height attributes for an image, so that
browser can allocate that much of space for the image before it is downloaded. Otherwise,
image loading may cause distortion or flicker in your website layout.
The <picture> element contains zero or more <source> elements, each referring to different
image source, and one <img> element at the end. Also each <source> element has
the media attribute which specifies a media condition (similar to the media query) that is used
by the browser to determine when a particular source should be used. Let's try out an
example:
Example
Try this code »
<picture>
<source media="(min-width: 1000px)" srcset="logo-large.png">
<source media="(max-width: 500px)" srcset="logo-small.png">
<img src="logo-default.png" alt="My logo">
</picture>
Note: The browser will evaluate each child <source> element and choose the best match
among them; if no matches are found, the URL of the <img> element's src attribute is used.
Also, the <img> tag must be specified as the last child of the <picture> element.
The basic idea behind creating image map is to provide an easy way of linking various parts of
an image without dividing it into separate image files. For example, a map of the world may
have each country hyperlinked to further information about that country.
Example
Try this code »
<img src="objects.png" usemap="#objects" alt="Objects">
<map name="objects">
<area shape="circle" coords="137,231,71" href="clock.html"
alt="Clock">
<area shape="poly" coords="363,146,273,302,452,300" href="sign.html"
alt="Sign">
<area shape="rect" coords="520,160,641,302" href="book.html"
alt="Book">
</map>
The name attribute of the <map> tag is used to reference the map from the <img> tag using
its usemap attribute. The <area> tag is used inside the <map> element to define the clickable areas
on an image. You can define any number of clickable areas within an image.
Note: The image map should not be used for website navigation. They are not search engine
friendly. A valid use of an image map is with a geographical map.
Tip: There are many online tools available for creating image maps. Some advanced editors
like Adobe Dreamweaver also provides a set of tools for easily creating image maps.
HTML Tables
Creating Tables in HTML
HTML table allows you to arrange data into rows and columns. They are commonly used to
display tabular data like product listings, customer's details, financial reports, and so on.
You can create a table using the <table> element. Inside the <table> element, you can use
the <tr> elements to create rows, and to create columns inside a row you can use
the <td> elements. You can also define a cell as a header for a group of table cells using
the <th> element.
Example
Try this code »
<table>
<tr>
<th>No.</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>Peter Parker</td>
<td>16</td>
</tr>
<tr>
<td>2</td>
<td>Clark Kent</td>
<td>34</td>
</tr>
</table>
Tables do not have any borders by default. You can use the CSS border property to add
borders to the tables. Also, table cells are sized just large enough to fit the contents by
default. To add more space around the content in the table cells you can use the
CSS padding property.
The following style rules add a 1-pixel border to the table and 10-pixels of padding to its cells.
Example
Try this code »
table, th, td {
border: 1px solid black;
}
th, td {
padding: 10px;
}
By default, borders around the table and their cells are separated from each other. But you
can collapse them into one by using the border-collapse property on the <table> element.
Also, text inside the <th> elements are displayed in bold font, aligned horizontally center in the
cell by default. To change the default alignment you can use the CSS text-align property.
The following style rules collapse the table borders and align the table header text to left.
Example
Try this code »
table {
border-collapse: collapse;
}
th {
text-align: left;
}
Please check out the tutorial on CSS tables to learn about styling HTML tables in details.
Let's try out the following example to understand how colspan basically works:
Example
Try this code »
<table>
<tr>
<th>Name</th>
<th colspan="2">Phone</th>
</tr>
<tr>
<td>John Carter</td>
<td>5550192</td>
<td>5550152</td>
</tr>
</table>
Similarly, you can use the rowspan attribute to create a cell that spans more than one row. Let's
try out an example to understand how row spanning basically works:
Example
Try this code »
<table>
<tr>
<th>Name:</th>
<td>John Carter</td>
</tr>
<tr>
<th rowspan="2">Phone:</th>
<td>55577854</td>
</tr>
<tr>
<td>55577855</td>
</tr>
</table>
Example
Try this code »
<table>
<caption>Users Info</caption>
<tr>
<th>No.</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>Peter Parker</td>
<td>16</td>
</tr>
<tr>
<td>2</td>
<td>Clark Kent</td>
<td>34</td>
</tr>
</table>
Example
Try this code »
<table>
<thead>
<tr>
<th>Items</th>
<th>Expenditure</th>
</tr>
</thead>
<tbody>
<tr>
<td>Stationary</td>
<td>2,000</td>
</tr>
<tr>
<td>Furniture</td>
<td>10,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td>12,000</td>
</tr>
</tfoot>
</table>
Note: In HTML5, the <tfoot> element can be placed either before or after
the <tbody> and <tr> elements, but must appear after any <caption>, <colgroup>,
and <thead> elements.
Tip: Do not use tables for creating web page layouts. Table layouts are slower at rendering,
and very difficult to maintain. It should be used only to display tabular data.
Note: Inside a list item you can put text, images, links, line breaks, etc. You can also place an
entire list inside a list item to create the nested list.
In the following sections we will cover all the three types of list one by one:
Example
Try this code »
<ul>
<li>Chocolate Cake</li>
<li>Black Forest Cake</li>
<li>Pineapple Cake</li>
</ul>
You can also change the bullet type in your unordered list using the CSS list-style-
type property. The following style rule changes the type of bullet from the
default disc to square:
Example
Try this code »
ul {
list-style-type: square;
}
Please check out the tutorial on CSS lists to learn about styling HTML lists in details.
The list items in an ordered list are marked with numbers. Here's an example:
Example
Try this code »
<ol>
<li>Fasten your seatbelt</li>
<li>Starts the car's engine</li>
<li>Look around and go</li>
</ol>
— The output of the above example will look something like this:
The numbering of items in an ordered list typically starts with 1. However, if you want to
change that you can use the start attribute, as shown in the following example:
Example
Try this code »
<ol start="10">
<li>Mix ingredients</li>
<li>Bake in oven for an hour</li>
<li>Allow to stand for ten minutes</li>
</ol>
— The output of the above example will look something like this:
10. Mix ingredients
11. Bake in oven for an hour
12. Allow to stand for ten minutes
Like unordered list, you can also use the CSS list-style-type property to change the
numbering type in an ordered list. The following style rule changes the marker type to roman
numbers.
Example
Try this code »
ol {
list-style-type: upper-roman;
}
Tip: You can also use the type attribute to change the numbering type e.g. type="I".
However, you should avoid this attribute, use the CSS list-style-type property instead.
The description list is created using <dl> element. The <dl> element is used in conjunction
with the <dt> element which specify a term, and the <dd> element which specify the term's
definition.
Browsers usually render the definition lists by placing the terms and definitions in separate
lines, where the term's definitions are slightly indented. Here's an example:
Example
Try this code »
<dl>
<dt>Bread</dt>
<dd>A baked food made of flour.</dd>
<dt>Coffee</dt>
<dd>A drink made from roasted coffee beans.</dd>
</dl>
— The output of the above example will look something like this:
Bread
Coffee
Forms contain special elements called controls like inputbox, checkboxes, radio-buttons,
submit buttons, etc. Users generally complete a form by modifying its controls e.g. entering
text, selecting items, etc. and submitting this form to a web server for further processing.
The <form> tag is used to create an HTML form. Here's a simple example of a login form:
Example
Try this code »
<form>
<label>Username: <input type="text"></label>
<label>Password: <input type="password"></label>
<input type="submit" value="Submit">
</form>
The following section describes different types of controls that you can use in your form.
Input Element
This is the most commonly used element within HTML forms. It allows you to specify various
types of user input fields, depending on the type attribute. An input element can be of
type text field, password field, checkbox, radio button, submit button, reset button, file select box,
as well as several new input types introduced in HTML5. The most frequently used input types
are described below.
Text Fields
Text fields are one line areas that allow the user to input text. Single-line text input controls
are created using an <input> element, whose type attribute has a value of text. Here's an
example of a single-line text input used to take username:
Example
Try this code »
<form>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</form>
— The output of the above example will look something like this:
Note: The <label> tag is used to define the labels for <input> elements. If you want your user
to enter several lines you should use a <textarea> instead.
Password Field
Password fields are similar to text fields. The only difference is; characters in a password field
are masked, i.e. they are shown as asterisks or dots. This is to prevent someone else from
reading the password on the screen. This is also a single-line text input controls created using
an <input> element whose type attribute has a value of password. Here's an example of a
single-line password input used to take user password:
Example
Try this code »
<form>
<label for="user-pwd">Password:</label>
<input type="password" name="user-password" id="user-pwd">
</form>
— The output of the above example will look something like this:
Radio Buttons
Radio buttons are used to let the user select exactly one option from a pre-defined set of
options. It is created using an <input> element whose type attribute has a value of radio.
Here's an example of radio buttons that can be used to collect user's gender information:
Example
Try this code »
<form>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
</form>
— The output of the above example will look something like this:
Checkboxes
Checkboxes allows the user to select one or more option from a pre-defined set of options. It
is created using an <input> element whose type attribute has a value of checkbox. Here's an
example of checkboxes that can be used to collect information about user's hobbies:
Example
Try this code »
<form>
<input type="checkbox" name="sports" id="soccer">
<label for="soccer">Soccer</label>
<input type="checkbox" name="sports" id="cricket">
<label for="cricket">Cricket</label>
<input type="checkbox" name="sports" id="baseball">
<label for="baseball">Baseball</label>
</form>
— The output of the above example will look something like this:
Note: If you want to make a radio button or checkbox selected by default, you can add the
attribute checked to the input element, like <input type="checkbox" checked>.
This is also created using an <input> element, whose type attribute value is set to file.
Example
Try this code »
<form>
<label for="file-select">Upload:</label>
<input type="file" name="upload" id="file-select">
</form>
— The output of the above example will look something like this:
Tip: There are several other input types. Please check out the chapter on HTML5 new input
types to learn more about the newly introduced input types.
Textarea
Textarea is a multiple-line text input control that allows a user to enter more than one line of
text. Multi-line text input controls are created using an <textarea> element.
Example
Try this code »
<form>
<label for="address">Address:</label>
<textarea rows="3" cols="30" name="address" id="address"></textarea>
</form>
— The output of the above example will look something like this:
Select Boxes
A select box is a dropdown list of options that allows user to select one or more option from a
pull-down list of options. Select box is created using the <select> element
and <option> element.
The <option> elements within the <select> element define each list item.
Example
Try this code »
<form>
<label for="city">City:</label>
<select name="city" id="city">
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
</select>
</form>
— The output of the above example will look something like this:
Submit and Reset Buttons
A submit button is used to send the form data to a web server. When submit button is clicked
the form data is sent to the file specified in the form's action attribute to process the
submitted data. A reset button resets all the forms control to default values. Try out the
following example by typing your name in the text field, and click on submit button to see it
in action.
Example
Try this code »
<form action="action.php" method="post">
<label for="first-name">First Name:</label>
<input type="text" name="first-name" id="first-name">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
Type your name in the text field above, and click on submit button to see it in action.
Note: You can also create buttons using the <button> element. Buttons created with
the <button> element function just like buttons created with the input element, but they offer
richer rendering possibilities by allowing the embedding of other HTML elements.
Example
Try this code »
<form>
<fieldset>
<legend>Contact Details</legend>
<label>Email Address: <input type="email" name="email"></label>
<label>Phone Number: <input type="text" name="phone"></label>
</fieldset>
</form>
Frequently Used Form Attributes
The following table lists the most frequently used form element's attributes:
Attribute Description
action Specifies the URL of the program or script on the web server that will be used for processing the
information submitted via form.
method Specifies the HTTP method used for sending the data to the web server by the browser. The value
can be either get (the default) and post.
target Specifies where to display the response that is received after submitting the form. Possible values
are _blank, _self, _parent and _top.
enctype Specifies how the form data should be encoded when submitting the form to the server. Applicable
only when the value of the method attribute is post.
There are several other attributes, to know about them please see the <form> tag reference.
Note: The name attribute represents the form's name within the forms collection. Its value
must be unique among the forms in a document, and must not be an empty string.
Tip: All the data sent via get method is visible in the browser's address bar. But, the data sent
via post is not visible to the user. Please check out the tutorial on GET vs. POST to learn about
the difference between these two HTTP methods in detail.
HTML Doctypes
Understanding the HTML5 Doctype
A Document Type Declaration, or DOCTYPE for short, is an instruction to the web browser
about the version of markup language in which a web page is written.
A DOCTYPE declaration appears at the top of a web page before all other elements.
According to the HTML specification or standards, every HTML document requires a valid
document type declaration to insure that your web pages are displayed the way they are
intended to be displayed.
The doctype declaration is usually the very first thing defined in an HTML document (even
before the opening <html> tag); however the doctype declaration itself is not an HTML tag.
The DOCTYPE for HTML5 is very short, concise, and case-insensitive.
<!DOCTYPE html>
Doctypes for earlier versions of HTML were longer because the HTML language was SGML-
based and therefore required a reference to a DTD, but they are obsolete now.
With HTML5 this is no longer the case and the doctype declaration is only needed to enable
the standard mode for documents written using the HTML syntax.
You can use the following markup as a template to create a new HTML5 document.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><!-- Insert your title here --></title>
</head>
<body>
<!-- Insert your content here -->
</body>
</html>
Note: The doctype declaration refers to a Document Type Definition (DTD). It is an instruction
to the web browser about what version of the markup language the page is written in. The
World Wide Web Consortium (W3C) provides DTDs for all HTML versions.
Tip: Must add a doctype declaration when creating an HTML document. Also, use the W3C's
Validator to check your HTML for markup or syntax error before publishing online.
HTML Layout
Creating Website Layouts
Creating a website layout is the activity of positioning the various elements that make a web
page in a well-structured manner and give appealing look to the website.
You have seen most websites on the internet usually display their content in multiple rows
and columns, formatted like a magazine or newspaper to provide the users a better reading
and writing environment. This can be easily achieved by using the HTML tags, such
as <table>, <div>, <header>, <footer>, <section>, etc. and adding some CSS styles to them.
HTML Table Based Layout
Table provides the simplest way for creating layouts in HTML. Generally, this involves the
process of putting the contents such as text, images, and so on into rows and columns.
The following layout is created using an HTML table with 3 rows and 2 columns — the first
and last row spans both columns using the table's colspan attribute:
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML Table Layout</title>
</head>
<body style="margin:0px;">
<table style="width:100%; border-collapse:collapse; font:14px
Arial,sans-serif;">
<tr>
<td colspan="2" style="padding:10px 20px; background-
color:#acb3b9;">
<h1 style="font-size:24px;">Tutorial Republic</h1>
</td>
</tr>
<tr style="height:170px;">
<td style="width:20%; padding:20px; background-color:#d4d7dc;
vertical-align: top;">
<ul style="list-style:none; padding:0px; line-
height:24px;">
<li><a href="#" style="color:#333;">Home</a></li>
<li><a href="#" style="color:#333;">About</a></li>
<li><a href="#" style="color:#333;">Contact</a></li>
</ul>
</td>
<td style="padding:20px; background-color:#f2f2f2; vertical-
align:top;">
<h2>Welcome to our site</h2>
<p>Here you will learn how to create websites...</p>
</td>
</tr>
<tr>
<td colspan="2" style="padding:5px; background-color:#acb3b9;
text-align:center;">
<p>copyright © tutorialrepublic.com</p>
</td>
</tr>
</table>
</body>
</html>
— The HTML code above will produce the following output:
Warning: The method used for creating layout in the above example is not wrong, but it's not
recommended. Avoid tables and inline styles for creating layouts. Layouts created using tables
often rendered very slowly. Tables should only be used to display tabular data.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML Div Layout</title>
<style>
body {
font: 14px Arial,sans-serif;
margin: 0px;
}
.header {
padding: 10px 20px;
background: #acb3b9;
}
.header h1 {
font-size: 24px;
}
.container {
width: 100%;
background: #f2f2f2;
}
.nav, .section {
float: left;
padding: 20px;
min-height: 170px;
box-sizing: border-box;
}
.nav {
width: 20%;
background: #d4d7dc;
}
.section {
width: 80%;
}
.nav ul {
list-style: none;
line-height: 24px;
padding: 0px;
}
.nav ul li a {
color: #333;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.footer {
background: #acb3b9;
text-align: center;
padding: 5px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Tutorial Republic</h1>
</div>
<div class="wrapper clearfix">
<div class="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
<div class="section">
<h2>Welcome to our site</h2>
<p>Here you will learn how to create websites...</p>
</div>
</div>
<div class="footer">
<p>copyright © tutorialrepublic.com</p>
</div>
</div>
</body>
</html>
— The HTML code above will produce the same output as the previous example:
We've created this layout using the CSS float techniques, since most web browsers support it.
Alternatively, you can also use the CSS3 flexbox to create modern and more flexible layouts.
See the tutorial on CSS3 flexible box layouts to learn about flexbox in detail.
Tip: Better web page layouts can be created by using the DIV elements and CSS. You can
change the layout of all the pages of your website by editing just one CSS file. To learn about
CSS in detail, please check out our CSS tutorial section.
You can consider these elements as a replacement for commonly used classes such
as .header, .footer, .nav, .section, etc. The following example uses the new HTML5
structural elements to create the same layout that we have created in the previous examples.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 Web Page Layout</title>
<style>
body {
font: 14px Arial,sans-serif;
margin: 0px;
}
header {
padding: 10px 20px;
background: #acb3b9;
}
header h1 {
font-size: 24px;
}
.container {
width: 100%;
background: #f2f2f2;
}
nav, section {
float: left;
padding: 20px;
min-height: 170px;
box-sizing: border-box;
}
section {
width: 80%;
}
nav {
width: 20%;
background: #d4d7dc;
}
nav ul {
list-style: none;
line-height: 24px;
padding: 0px;
}
nav ul li a {
color: #333;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
footer {
background: #acb3b9;
text-align: center;
padding: 5px;
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>Tutorial Republic</h1>
</header>
<div class="wrapper clearfix">
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<section>
<h2>Welcome to our site</h2>
<p>Here you will learn how to create websites...</p>
</section>
</div>
<footer>
<p>copyright © tutorialrepublic.com</p>
</footer>
</div>
</body>
</html>
— The HTML code above will also produce the same output as the previous example:
The following table provides a brief overview of new HTML5 structural elements.
Tag Description
Please check out the reference on HTML5 tags to know about the newly introduced tags.
HTML5 Tags/Elements
HTML5 Tags
The following section contains a complete list of standard tags belonging to the latest HTML5
and XHTML 1.1 specifications. All the tags are listed alphabetically.
Tag Description
<applet> Obsolete Embeds a Java applet (mini Java applications) on the page. Use <object> instead.
<base> Defines the base URL for all relative URLs in a document.
<basefont> Obsolete Specifies the base font for a page. Use CSS instead.
<bdi> Represents text that is isolated from its surrounding for the purposes of bidirectional text
formatting.
<canvas> Defines a region in the document, which can be used to draw graphics on the fly via scripting
(usually JavaScript).
<dd> Specifies a description, or value for the term (<dt>) in a description list (<dl>).
<del> Represents text that has been deleted from the document.
<details> Represents a widget from which the user can obtain additional information or controls on-
demand.
<embed> Embeds external application, typically multimedia content like audio or video into an HTML
document.
<font> Obsolete Defines font, color, and size for text. Use CSS instead.
<head> Defines the head portion of the document that contains information about the document such
as title.
<ins> Defines a block of text that has been inserted into a document.
<link> Defines the relationship between the current document and an external resource.
<menuitem> Defines a list (or menuitem) of commands that a user can perform.
<noframes> Obsolete Defines an alternate content that displays in browsers that do not support frames.
<noscript> Defines alternative content to display when the browser doesn't support scripting.
<rp> Provides fall-back parenthesis for browsers that that don't support ruby annotations.
<source> Defines alternative media resources for the media elements like <audio> or <video>.
<style> Inserts style information (commonly CSS) into the head of a document.
<tbody> Groups a set of rows defining the main body of the table data.
<template> Defines the fragments of HTML that should be hidden when the page is loaded, but can be
cloned and inserted in the document by JavaScript.
<thead> Groups a set of rows that describes the column labels of a table.
<track> Defines text tracks for the media elements like <audio> or <video>.
HTML Head
The HTML head Element
The <head> element primarily is the container for all the head elements, which provide extra
information about the document (metadata), or reference to other resources that are required
for the document to display or behave correctly in a web browser. The head elements
collectively describes the properties of the document such as title, provide meta information
like character set, instruct the browser where to find the style sheets or scripts that allows you
to extend the HTML document in a highly active and interactive ways.
The HTML elements that can be used inside the <head> element
are: <title>, <base>, <link>, <style>, <meta>, <script> and the <noscript> element.
The title element is required in all HTML/XHTML documents to produce a valid document.
Only one title element is permitted in a document and it must be placed within
the <head> element. The title element contains plain text and entities; it may not contain other
markup tags.
The title of the document may be used for different purposes. For example:
• To display a title in the browser title bar and in the task bar.
• To provide a title for the page when it is added to favorites or bookmarked.
• To displays a title for the page in search-engine results.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>A simple HTML document</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Tip: A good title should be short and specific to the document's content, because search
engine's web crawlers pay particular attention to the words used in the title. The title should
ideally be less than 65 characters in length. See the guidelines for titles.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>Defining a base URL</title>
<base href="https://www.tutorialrepublic.com/">
</head>
<body>
<p><a href="html-tutorial/html-head.php">HTML Head</a>.</p>
</body>
</html>
The hyperlink in the example above will actually resolve
to https://www.tutorialrepublic.com/html-tutorial/html-head.php regardless of the URL of the
current page. This is because the relative URL specified in the link: html-tutorial/html-head.php is
added to the end of the base URL: https://www.tutorialrepublic.com/.
Warning: The HTML <base> element must appear before any element that refers to an external
resource. HTML permits only one base element for each document.
The HTML link Element
The <link> element defines the relationship between the current document and an external
documents or resources. A common use of link element is to link to external style sheets.
Example
Try this code »
<head>
<title>Linking Style Sheets</title>
<link rel="stylesheet" href="style.css">
</head>
Please check out the CSS tutorial section to learn about style sheets in detail.
Note: An HTML document's <head> element may contain any number of <link> elements.
The <link> element has attributes, but no contents.
Example
Try this code »
<head>
<title>Embedding Style Sheets</title>
<style>
body { background-color: YellowGreen; }
h1 { color: red; }
p { color: green; }
</style>
</head>
Note: An embedded style sheet should be used when a single document has a unique style. If
the same style sheet is used in multiple documents, then an external style sheet would be
more appropriate. See the tutorial on HTML styles to learn more about it.
Example
Try this code »
<head>
<title>Specifying Metadata</title>
<meta charset="utf-8">
<meta name="author" content="John Smith">
</head>
The meta element will be explained in more detail in the next chapter.
Example
Try this code »
<head>
<title>Adding JavaScript</title>
<script>
document.write("<h1>Hello World!</h1>")
</script>
</head>
HTML Meta
Defining Metadata
The <meta> tags are typically used to provide structured metadata such as a
document's keywords, description, author name, character encoding, and other metadata. Any
number of meta tags can be placed inside the head section of an HTML or XHTML document.
Metadata will not be displayed on the web page, but will be machine parsable, and can be
used by the browsers, search engines like Google or other web services.
The following section describes the use of meta tags for various purposes.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>Declaring Character Encoding</title>
<meta charset="utf-8">
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
To set the character encoding inside a CSS document, the @charset at-rule is used.
Note: UTF-8 is a very versatile and recommended character encoding to choose. However, if
this is not specified, then the default encoding of the platform is used.
Example
Try this code »
<head>
<title>Defining Document's Author</title>
<meta name="author" content="Alexander Howick">
</head>
Note: The name attribute of the meta tag defines the name of a piece of document-level
metadata, while the content attribute gives the corresponding value. The content attribute value
may contain text and entities, but it may not contain HTML tags.
Example
Try this code »
<head>
<title>Defining Keywords and Description</title>
<meta name="keywords" content="HTML, CSS, javaScript">
<meta name="description" content="Easy to understand tutorials and
references on HTML, CSS, javaScript and more...">
</head>
Tip: Search engines will often use the meta description of a page to create short synopsis for
the page when it appear in search results. See the guidelines for meta description.
Without a viewport meta tag, mobile browsers render the web pages at typical desktop screen
widths, and then scale it down to fit the mobile screen. As a result, it requires pinch-and-zoom
to view the web page properly in mobile devices, which is very inconvenient.The following
demonstration shows two web pages — one with viewport meta tag and other without
viewport meta tag set. Open these links on mobile devices to see how it works.
The viewport meta tag allows you to set the best viewport size and scaling limits for viewing
the web pages on mobile devices. A typical viewport meta tag definition will look as follows:
Example
Try this code »
<head>
<title>Configuring the Viewport</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
The width=device-width key-value pair inside the content attribute sets the width of the viewport
to same as the screen width of the device, whereas the initial-scale=1 sets the initial scale or
zoom level to 100% when the page is first loaded by the browser.
Tip: Always use the <meta> viewport tag in your web pages. It will make your website user-
friendly and more accessible on mobile devices like cell phones and tablets.
HTML Script
Working with Client-side Script
Client-side scripting refers to the type of computer programs that are executed by the user's
web browser. JavaScript (JS) is the most popular client-side scripting language on the web.
The <script> element is used to embed or reference JavaScript within an HTML document to
add interactivity to web pages and provide a significantly better user experience.
Some of the most common uses of JavaScript are form validation, generating alert messages,
creating image gallery, show hide content, DOM manipulation, and many more.
Embedding JavaScript
To embed JavaScript in an HTML file, just add the code as the content of a <script> element.
The JavaScript in the following example write a string of text to a web page.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Embedding JavaScript</title>
</head>
<body>
<div id="greet"></div>
<script>
document.getElementById("greet").innerHTML = "Hello World!";
</script>
</body>
</html>
Tip: Ideally, script elements should be placed at the bottom of the page, before the closing
body tag i.e. </body>, because when browser encounters a script it pauses rendering the rest of
the page until it parses the script that may significantly impact your site performance.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Linking External JavaScript</title>
</head>
<body>
<div id="greet"></div>
<script src="hello.js"></script>
</body>
</html>
Note: When the src attribute is specified, the <script> element must be empty. This simply
means that you cannot use the same <script> element to both embed the JavaScript and to
link to an external JavaScript file in an HTML document.
Tip: JavaScript files are normal text files with .js extension, such as "hello.js". Also, the external
JavaScript file contains only JavaScript statements; it does not contain
the <script>...</script> element like embedded JavaScript.
This element can contain any HTML elements, aside from <script>, that can be included in
the <body> element of a normal HTML page. Let's check out an example:
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Noscript Demo</title>
</head>
<body>
<div id="greet"></div>
<script>
document.getElementById("greet").innerHTML = "Hello World!";
</script>
<noscript>
<p>Oops! This website requires a JavaScript-enabled browser.</p>
</noscript>
</body>
</html>
Note: The content inside the noscript element will only be displayed if the user's browser
doesn't support scripting, or scripting is disabled in the browser.
To display these special characters, they must be replaced with the character entities.
Character entity references, or entities for short, enable you to use the characters that cannot
be expressed in the document's character encoding or that cannot be entered by a keyboard.
You can use numeric character references, instead of entity names. A key benefit of using
numeric character references is that, they have stronger browser support, and can be used to
specify any Unicode character, whereas entities are limited to a subset of this.
Note: HTML entities names are case-sensitive! Please check out the HTML character
entities reference for a complete list of character entities of special characters and symbols.
Tip: Nonbreaking space ( ) is used to create a blank space between two items that
cannot be separated by a line break. They are also used to display multiple spaces since web
browsers display only one space if multiple spaces are created using the spacebar key.
For instance, if you look at the address bar of your browser you will see:
https://www.tutorialrepublic.com/html-tutorial/html-url.php
— This is the URL of the web page you are viewing right now.
A URL has a linear structure and normally consists of some of the following:
Scheme name — The scheme identifies the protocol to be used to access the resource on the
Internet. The scheme names followed by the three characters :// (a colon and two slashes).
The most commonly used protocols are http://, https://, ftp://, and mailto://.
Host name — The host name identifies the host where resource is located. A hostname is a
domain name assigned to a host computer. This is usually a combination of the host's local
name with its parent domain's name. For example, www.tutorialrepublic.com consists of
host's machine name www and the domain name tutorialrepublic.com.
Port Number — Servers often deliver more than one type of service, so you must also tell the
server what service is being requested. These requests are made by port number. Well-known
port numbers for a service are normally omitted from the URL. For example, web service HTTP
runs by default over port 80, HTTPS runs by default over port 443.
Path — The path identifies the specific resource within the host that the user wants to access.
For example, /html/html-url.php, /news/technology/, etc.
Query String — The query string contains data to be passed to server-side scripts, running
on the web server. For example, parameters for a search. The query string preceded by a
question mark (?), is usually a string of name and value pairs separated by ampersand (&), for
example, ?first_name=John&last_name=Corner, q=mobile+phone, and so on.
Fragment identifier — The fragment identifier, if present, specifies a location within the
page. Browser may scroll to display that part of the page. The fragment identifier introduced
by a hash character (#) is the optional last part of a URL for a document.
Note: Scheme and host components of a URL are not case-sensitive, but path and query
string are case-sensitive. Usually the whole URL is specified in lower case.
Reserved Characters
Certain characters are reserved or restricted from use in a URL because they may (or may not)
be defined as delimiters by the generic syntax in a particular URL scheme. For example,
forward slash / characters are used to separate different parts of a URL.
If data for a URL component contains character that would conflict with a reserved set of
characters, which is defined as a delimiter in the URL scheme then the conflicting character
must be percent-encoded before the URL is formed. Reserved characters in a URL are:
! # $ & ' ( ) * + , / : ; = ? @ [ ]
%21 %23 %24 %26 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %5B %5D
Unreserved Characters
Characters that are allowed in a URL but do not have a reserved purpose are called
unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period,
underscore, and tilde. The following table lists all the unreserved characters in a URL:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - _ . ~
HTML Validation
Why Validate Your HTML Code
As a beginner it is very common that you will make mistake in writing your HTML code.
Incorrect or non-standard code may cause unexpected results in how your page displayed or
function in browsers. To prevent this you can test or validate your HTML code against the
formal guidelines and standards set by the Wide Web Consortium (W3C) for HTML/XHTML
web pages. The World Wide Web Consortium provide a simple online tool
(https://validator.w3.org/) that automatically check your HTML code and point out any
problems/errors your code might have, such as missing closing tags or missing quotes around
attributes.
Validating a Web Page
Validating a web page is a process of ensuring that it conforms to the norms or standards
defined by the World Wide Web Consortium (W3C) which is the authority to maintain HTML
standards.
There are several specific reasons for validating a web page, some of them are:
• It helps to create web pages that are cross-browser, cross-platform compatible. It also
likely to be compatible with the future version of web browsers and web standards.
• Standards compliant web pages increase the search engine spiders and crawlers
visibility, as a result your web pages will more likely be appear in search results.
• It will reduce unexpected errors and make your web pages more accessible to the
visitor.
Note: Validation is important. It will ensure that your web pages are interpreted in the same
way (the way you want it) by the various web browsers, search engines etc.
Follow the link given below to validate your HTML/XHTML document. It will automatically
detect whether you're using HTML or XHTML, and which doctype you're using.
W3C Markup Validation Service
In this section we're going to take a brief look at each of the following new input types:
• color
• date
• datetime-local
• email
• month
• number
• range
• search
• tel
• time
• url
• week
There was also a datetime input type for entering a date and time, but it is now obsolete.
Let's try out the following example to understand how it basically works:
Example
Try this code »
<form>
<label for="mycolor">Select Color:</label>
<input type="color" value="#00ff00" id="mycolor">
</form>
Note: The color input (i.e. type="color") is supported in all major modern web browsers such
as Firefox, Chrome, Opera, Safari (12.1+), Edge (14+). Not supported by the Microsoft
Internet Explorer and older version of Apple Safari browsers.
The date value includes the year, month, and day, but not the time.
Example
Try this code »
<form>
<label for="mydate">Select Date:</label>
<input type="date" value="2019-04-15" id="mydate">
</form>
Note: The date input (i.e. type="date") is supported by the Chrome, Firefox, Opera and Edge
browsers. Not supported by the Internet Explorer and Safari browsers.
Input Type Datetime-local
The datetime-local input type allows the user to select both local date and time, including
the year, month, and day as well as the time in hours and minutes.
Let's try out the following example to understand how it basically works:
Example
Try this code »
<form>
<label for="mydatetime">Choose Date and Time:</label>
<input type="datetime-local" id="mydatetime">
</form>
Warning: The input type="datetime-local" is not supported by Firefox, Safari, and Internet
Explorer browsers. Currently supported by Chrome, Edge, and Opera browsers.
Let's try out this example by entering any e-mail address to see how it actually works:
Example
Try this code »
<form>
<label for="myemail">Enter Email Address:</label>
<input type="email" id="myemail" required>
</form>
Tip: You can style the email input field for different validation states, when an value is entered
using the :valid, :invalid or :required pseudo-classes.
Note: The validation for the email input (i.e. type="email") is supported by all major browsers
like Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.
The value is a string in the format "YYYY-MM", where YYYY is the four-digit year and MM is
the month number. Let's try out an example to see how this basically works:
Example
Try this code »
<form>
<label for="mymonth">Select Month:</label>
<input type="month" id="mymonth">
</form>
Warning: The input type="month" is not supported by Firefox, Safari and Internet Explorer
browsers. Currently supported in Chrome, Edge, and Opera browsers.
The following example will allow you to enter a numeric value between 1 to 10.
Example
Try this code »
<form>
<label for="mynumber">Enter a Number:</label>
<input type="number" min="1" max="10" step="0.5" id="mynumber">
</form>
Note: The number input (i.e. type="number") is supported by all major web browsers such as
Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above. Internet Explorer however
recognized the number but do not provide increment and decrement spin buttons.
Let's try out the following example to understand how it basically works:
Example
Try this code »
<form>
<label for="mynumber">Select a Number:</label>
<input type="range" min="1" max="10" step="0.5" id="mynumber">
</form>
Note: The range input (i.e. type="range") is supported by all major web browsers such as
Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.
Input Type Search
The search input type can be used for creating search input fields.
A search field typically behaves like a regular text field, but in some browsers like Chrome and
Safari as soon as you start typing in the search box a small cross appears on the right side of
the field that lets you quickly clear the search field. Let's try out an example to see how it
works:
Example
Try this code »
<form>
<label for="mysearch">Search Website:</label>
<input type="search" id="mysearch">
</form>
Note: The search input (i.e. type="search") is supported by all major web browsers such as
Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.
Browsers don't support tel input validation natively. However, you can use
the placeholder attribute to help users in entering the correct format for a phone number, or
specify a regular expression to validate the user input using the pattern attribute. Let's check
out an example:
Example
Try this code »
<form>
<label for="myphone">Telephone Number:</label>
<input type="tel" id="myphone" placeholder="xx-xxxx-xxxx" required>
</form>
Note: The validation for tel input (i.e. type="tel") is currently not supported by any browser
because format for phone numbers vary so much across countries, but it is still useful. Mobile
browsers display a numeric keyboard for tel input field for entering phone numbers.
Example
Try this code »
<form>
<label for="mytime">Select Time:</label>
<input type="time" id="mytime">
</form>
Warning: The input type="time" is not supported by Internet Explorer and Safari browsers.
Currently supported by Chrome, Firefox, Edge, and Opera browsers.
You can use the multiple attribute to enter more than one URL. Also, if required attribute is
specified browser will automatically carry out validation to ensure that only text that matches
the standard format for URLs is entered into the input box. Let's see how this works:
Example
Try this code »
<form>
<label for="myurl">Enter Website URL:</label>
<input type="url" id="myurl" required>
</form>
Note: The validation for the url input (i.e. type="url") is supported by all major browsers like
Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.
Let's try out the following example to understand how this works:
Example
Try this code »
<form>
<label for="myweek">Select Week:</label>
<input type="week" id="myweek">
</form>
Warning: The input type="week" is not supported by Firefox, Safari and Internet Explorer
browsers. Currently supported by Chrome, Edge, and Opera browsers.
The following table summarizes some of the basic differences between these two elements,
which will help you to understand how to use these elements effectively and appropriately.
SVG Canvas
Multiple graphical elements, which become the part of Single element similar to <img> in behavior. Canvas
the page's DOM tree diagram can be saved to PNG or JPG format
Give better performance with smaller number of Give better performance with larger number of objects
objects or larger surface, or both or smaller surface, or both
Better scalability. Can be printed with high quality at Poor scalability. Not suitable for printing on higher
any resolution. Pixelation does not occur resolution. Pixelation may occur
HTML5 Audio
Embedding Audio in HTML Document
Inserting audio onto a web page was not easy before, because web browsers did not have a
uniform standard for defining embedded media files like audio.
In this chapter we'll demonstrates some of the many ways to embed sound in your webpage,
from the use of a simple link to the use of the latest HTML5 <audio> element.
The following example simply inserts an audio into the HTML5 document, using the browser
default set of controls, with one source defined by the src attribute.
Example
Try this code »
<audio controls="controls" src="media/birds.mp3">
Your browser does not support the HTML5 Audio element.
</audio>
An audio, using the browser default set of controls, with alternative sources.
Example
Try this code »
<audio controls="controls">
<source src="media/birds.mp3" type="audio/mpeg">
<source src="media/birds.ogg" type="audio/ogg">
Your browser does not support the HTML5 Audio element.
</audio>
The 'ogg' track in the above example works in Firefox, Opera and Chrome, while the same
track in the 'mp3' format is added to make the audio work in Internet Explorer and Safari.
Let's try out the following example to understand how this basically works:
Example
Try this code »
<a href="media/sea.mp3">Track 1</a>
<a href="media/wind.mp3">Track 2</a>
The following example code embeds a simple audio file into a web page.
Example
Try this code »
<object data="media/sea.mp3"></object>
<object data="media/sea.ogg"></object>
Warning: The <object> element is not supported widely and very much depends on the type
of the object that's being embedded. Other methods like HTML5 <audio> element or third-
party HTML5 audio players could be a better choice in many cases.
The following code fragment embeds audio files into a web page.
Example
Try this code »
<embed src="media/wind.mp3">
<embed src="media/wind.ogg">
Warning: However the <embed> element is very well supported in current browsers and defined
as standard in HTML5, but your audio might not played due to lack of browser support for
that file format or unavailability of plugins.
HTML5 Video
Embedding Video in HTML Document
Inserting video onto a web page was not relatively easy, because web browsers did not have a
uniform standard for defining embedded media files like video.
In this chapter we'll demonstrates some of the many ways of adding videos on web pages,
from the latest HTML5 <video> element to the popular YouTube videos.
The following example simply inserts a video into the HTML document, using the browser
default set of controls, with one source defined by the src attribute.
Example
Try this code »
<video controls="controls" src="media/shuttle.mp4">
Your browser does not support the HTML5 Video element.
</video>
A video, using the browser default set of controls, with alternative sources.
Example
Try this code »
<video controls="controls">
<source src="media/shuttle.mp4" type="video/mp4">
<source src="media/shuttle.ogv" type="video/ogg">
Your browser does not support the HTML5 Video element.
</video>
The following code fragment embeds a Flash video into a web page.
Example
Try this code »
<object data="media/blur.swf" width="400px" height="200px"></object>
Only browsers or applications that support Flash will play this video.
Warning: The <object> element is not supported widely and very much depends on the type
of the object that's being embedded. Other methods could be a better choice in many cases.
iPad and iPhone device cannot display Flash videos.
The following code fragment embeds a Flash video into a web page.
Example
Try this code »
<embed src="media/blur.swf" width="400px" height="200px">
Warning: However, the <embed> element is very well supported in current web browsers and it
is also defined as standard in HTML5, but your video might not played due to lack of browser
support for Flash or unavailability of plugins.
You can further customize this embed code such as changing the video size by selecting the
customization option given just below the embed-code input box.
The following example simply embeds a video from the YouTube. Let's try it out:
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>YouTube Video</title>
</head>
<body>
<iframe width="560" height="315"
src="//www.youtube.com/embed/YE7VzlLtp-4" frameborder="0"
allowfullscreen></iframe>
</body>
</html>
HTML5 Web Storage. What is Web Storage?
The HTML5's web storage feature lets you store some information locally on the user's
computer, similar to cookies, but it is faster and much better than cookies. However, web
storage is no more secure than cookies. Please check out the tutorial on PHP cookies to learn
more about cookies.
The information stored in the web storage isn't sent to the web server as opposed to the
cookies where data sent to the server with every request. Also, where cookies let you store a
small amount of data (nearly 4KB), the web storage allows you to store up to 5MB of data.
There are two types of web storage, which differ in scope and lifetime:
• Local storage — The local storage uses the localStorage object to store data for your entire
website on a permanent basis. That means the stored local data will be available on the
next day, the next week, or the next year unless you remove it.
• Session storage — The session storage uses the sessionStorage object to store data on
a temporary basis, for a single browser window or tab. The data disappears when session
ends i.e. when the user closes that browser window or tab.
Tip: The HTML5's web storage feature is supported in all major modern web browsers like
Firefox, Chrome, Opera, Safari and Internet Explorer 8 and above.
Here are some advantages of using the HTML5 application cache feature:
• Offline browsing — Users can use the application even when they're offline or there are
unexpected disruptions in the network connection.
• Improve performance — Cached resources load directly from the user's machine rather
than the remote server hence web pages load faster and performing better.
• Reduce HTTP request and server load — The browser will only have to download the
updated/changed resources from the remote server that minimize the HTTP requests and
saves precious bandwidth as well as reduce the load on the web server.
Tip: The HTML5's application cache feature is supported in all major modern web browsers
like Firefox, Chrome, Opera, Safari and Internet Explorer 10 and above.
HTML5 introduces a new technology called web worker that is specifically designed to do
background work independently of other user-interface scripts, without affecting the
performance of the page. Unlike normal JavaScript operations, web worker doesn't interrupt
the user and the web page remains responsive because they are running the tasks in the
background.
Tip: The HTML5's web worker feature is supported in all major modern web browsers like
Firefox, Chrome, Opera, Safari and Internet Explorer 10 and above.
Let's create an external JavaScript file named "worker.js" and type the following code.
Example
Download
var i = 0;
function countNumbers() {
if(i < 100000) {
i = i + 1;
postMessage(i);
}
Tip: The worker object's postMessage() method is used to send a message (like the numbers in
the example above) back to the web page from the web worker file.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using Web Worker</title>
<script>
if(window.Worker) {
// Create a new web worker
var worker = new Worker("worker.js");
Example explained:
The JavaScript code in the above example has the following meaning:
• The statement var worker = new Worker("worker.js"); creates a new web worker
object, which is used to communicate with the web worker.
• When the worker posts a message, it fires the onmessage event handler (line no-14)
that allows the code to receive messages from the web worker.
• The event.data element contains the message sent from the web worker.
Note: The code that a worker runs is always stored in a separate JavaScript file. This is to
prevent web developer from writing the web worker code that attempts to use global
variables or directly access the elements on the web page.
The following example will show you how to start and stop worker from a web page through
clicking the HTML buttons. It utilizes the same JavaScript file 'worker.js' what we have used in
the previous example to count the numbers from zero to 100000. Let's try it out:
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Start/Stop Web Worker</title>
<script>
// Set up global variable
var worker;
function startWorker() {
// Initialize web worker
worker = new Worker("worker.js");
function update(event) {
// Update the page with current message from worker
document.getElementById("result").innerHTML = event.data;
}
function stopWorker() {
// Stop the worker
worker.terminate();
}
</script>
</head>
<body>
<h1>Web Worker Demo</h1>
<button onclick="startWorker();" type="button">Start web
worker</button>
<button type="button" onclick="stopWorker();">Stop web worker</button>
<div id="result">
<!--Received messages will be inserted here-->
</div>
</body>
</html>
Tip: Use the web workers for performing only heavy-weight JavaScript tasks that do not
interrupt the user-interface scripts (i.e. scripts that respond to clicks or other user interactions).
It's not recommended to use web workers for short tasks.
However, there are some situations where web pages require a longer-term connection to the
web server. A typical example is stock quotes on finance websites where price updated
automatically. Another example is a news ticker running on various media websites.
You can create such things with the HTML5 server-sent events. It allows a web page to hold
an open connection to a web server so that the web server can send a new response
automatically at any time, there's no need to reconnect, and run the same server script from
scratch over and over again.
Note: Server-Sent Events (SSE) are unidirectional that means data are delivered in one
direction from the server to client. A client typically is a web browser.
Tip: The HTML5's server-sent events feature is supported in all major modern web browsers
like Firefox, Chrome, Safari and Opera except Internet Explorer.
Sending Messages with a Server Script
Let's create a PHP file named "server_time.php" and type the following script into it. It will
simply report the current time of the web server's built-in clock in regular intervals. We will
retrieve this time and update the web page accordingly later in this tutorial.
Example
Download
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
// Send it in a message
echo "data: " . $currentTime . "\n\n";
flush();
?>
The first two line of the PHP script sets two important headers. First, it sets the MIME type
to text/event-stream, which is required by the server-side event standard. The second line tells
the web server to turn off caching otherwise the output of your script may be cached.
Every message send through HTML5 server-sent events must start with the text data: followed
by the actual message text and the new line character sequence (\n\n).
And finally, we have used the PHP flush() function to make sure that the data is sent right
away, rather than buffered until the PHP code is complete.
Now let's create an HTML document named "demo_sse.html" and place it in the same project
directory where the "server_time.php" file is located. This HTML document simply receives the
current time reported by the web server and display it to the user.
Download
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
window.onload = function() {
var source = new EventSource("server_time.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += "New time
received from web server: " + event.data + "<br>";
};
};
</script>
</head>
<body>
<div id="result">
<!--Server response will be inserted here-->
</div>
</body>
</html>
HTML5 Geolocation
What is Geolocation?
The HTML5 geolocation feature lets you find out the geographic coordinates (latitude and
longitude numbers) of the current location of your website's visitor.
This feature is helpful for providing better browsing experience to the site visitor. For example,
you can return the search results that are physically close to the user's location.
The following is a simple example of geolocation that displays your current position. But, first
you need to agree to let the browser tell the web server about your position.
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Current Position</title>
<script>
function showPosition() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var positionInfo = "Your current position is (" +
"Latitude: " + position.coords.latitude + ", " + "Longitude: " +
position.coords.longitude + ")";
document.getElementById("result").innerHTML =
positionInfo;
});
} else {
alert("Sorry, your browser does not support HTML5
geolocation.");
}
}
</script>
</head>
<body>
<div id="result">
<!--Position information will be inserted here-->
</div>
<button type="button" onclick="showPosition();">Show Position</button>
</body>
</html>
Note: The web browsers won't share the visitor location with a web page unless the visitor
gives it explicit permission. The geolocation standard makes it an official rule to get user
permission for every website that wants location data.
The first function is called if your geolocation attempt is successful, while the second is called
if your geolocation attempt ends in failure. Let's check out an example:
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Handling Geolocation Errors</title>
<script>
// Set up global variable
var result;
function showPosition() {
// Store the element where the page displays the result
result = document.getElementById("result");
// If geolocation is available, try to get the visitor's position
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback,
errorCallback);
result.innerHTML = "Getting the position information...";
} else {
alert("Sorry, your browser does not support HTML5
geolocation.");
}
};
function showMap(position) {
// Get location data
var latlong = position.coords.latitude + "," +
position.coords.longitude;
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using the Google Maps</title>
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function showPosition() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showMap, showError);
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
}
var myOptions = {
center: latlong,
zoom: 16,
mapTypeControl: true,
navigationControlOptions: {
style:google.maps.NavigationControlStyle.SMALL
}
}
Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Watching Position</title>
<script>
// Set global variable
var watchID;
function showPosition() {
if(navigator.geolocation) {
watchID =
navigator.geolocation.watchPosition(successCallback);
} else {
alert("Sorry, your browser does not support HTML5
geolocation.");
}
}
function successCallback(position) {
toggleWatchBtn.innerHTML = "Stop Watching";
function startWatch() {
var result = document.getElementById("result");
toggleWatchBtn.onclick = function() {
if(watchID) {
toggleWatchBtn.innerHTML = "Start Watching";
navigator.geolocation.clearWatch(watchID);
watchID = false;
} else {
toggleWatchBtn.innerHTML = "Aquiring Geo Location...";
showPosition();
}
}
}