Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Beginner's Guide to HTML5/CSS3 - Part 2 of 12

1 Apr 2014CPOL17 min read 94.8K   330  
Building on the Basics

Image 1

Introduction 

This article is the 2nd part of "Beginner's Guide to HTML5/CSS3" series. This article will explain you basic HTML elements, their structure and implementation with interactive examples right away. We will also explore some basic HTML5 Tags.

What's in the Box?

Images and different kinds of hyperlinks

Images

Tag syntax Tag restrictions What it does? Demo
<img> Start tag: required, End tag: Not required Just creates a space to show the image from the source specified. Image 2

The BOB shown above has the code as...

HTML
<img src="http://s.codeproject.com/App_Themes/CodeProject/Img/logo250x135.gif" />

Here src is BOB's location URL.

Image Attributes - (Taken from here)

New : New in HTML5. 

Attribute Value Description
align top
bottom
middle
left
right
Not supported in HTML5.
Specifies the alignment of an image according to surrounding elements
alt text Specifies an alternate text for an image
border pixels Not supported in HTML5.
Specifies the width of the border around an image
crossoriginNew anonymous
use-credentials
Allow images from third-party sites that allow cross-origin access to be used with canvas
height pixels Specifies the height of an image
hspace pixels Not supported in HTML5.
Specifies the whitespace on left and right side of an image
ismap ismap Specifies an image as a server-side image-map
longdesc URL Not supported in HTML5.
Specifies the URL to a document that contains a long description of an image
src  URL  Specifies the URL of an image
usemap  #mapname Specifies an image as a client-side image-map
vspace  pixels Not supported in HTML5.
Specifies the whitespace on top and bottom of an image
width pixels Specifies the width of an image

In case you want to know more about these attributes, you can click on them and learn more. There is one new attribute include in HTML5 that is crossorigin Let me discuss more on that.

crossorigin 

Its values are anonymous and use-credentials. This attribute indicates if the image is fetched using CORS (Cross-origin resource sharing) or not. CORS-enabled images can be reused in the <canvas> element without being tainted.

  • anonymous 
    A cross-origin request is performed, but no credential is sent. If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin: HTTP header), the image will be tainted and its usage restricted.
  • use-credentials
    A cross-origin request is performed and credential is sent. If the server does not give credentials to the origin site, the image will be tainted and its usage restricted.

If the image is not present, the resource is fetched without a CORS request. If the image is invalid, it is handled as anonymous. To know more, see CORS enabled image

Hyperlinks

A Hyperlink is a reference for data, which is clickable. There are three kinds of Hyperlinks as described below.

Tag syntax Tag restrictions What it does? Demo
<a> Start tag: required, End tag: required  A Hyperlink points to a whole document or to a specific element within a document. This is a Hyperlink, click me to open me on a new Window

The code for this is... 

HTML
<a href="http://www.codeproject.com/Members/taditdash" target="_blank" title="Tadit Dash - Professional Profile">This is a Hyperlink, click me to open me on a new Window</a>

Let's discuss more on the important Attributes.

HTML Link Syntax 

The HTML code for a link is...

HTML
<a href="url">Link text</a>

The href attribute specifies the destination of a link.

Example 
HTML
<a href="http://www.codeproject.com/">Let's go to CodeProject</a>

which will display like this: Let's go to CodeProject

One important thing is "Link text" can be an image or any other HTML element.

Example 
HTML
<a href="http://www.codeproject.com/"><img src="http://s.codeproject.com/App_Themes/CodeProject/Img/logo250x135.gif" /></a>

Image 3

Now the image turns to a Link, click on the image to move to Code Project Home Page.

The target Attribute

Values are:

  • _blank - Opens the linked document in a new window or tab.
  • _parent - Opens the linked document in the parent frame.
  • _self - Opens the linked document in the same frame as it was clicked (this is default).
  • _top - Opens the linked document in the full body of the window.
  • framename - Opens the linked document in a named frame.

The target attribute specifies where to open the linked document. The example below will open the linked document in a new browser window or a new tab:

Example 
HTML
<a href="http://www.codeproject.com/" target="_blank">Let's go to CodeProject on a new Tab or Window</a>

which will display like this: Let's go to CodeProject on a new Tab or Window

The id and name Attributes

The id or name attribute can be used to create a bookmark inside an HTML document. These Bookmarks are not displayed, they are invisible to the reader.

Example 

All the headings in this articles are one one anchor with an name attribute set:

HTML
<a name="Images and different kinds of hyperlinks">Images and different kinds of hyperlinks</a> 

As you can see the in this article, the heading is simply interpreted without any special effect. To create a link to the "Images and different kinds of hyperlinks" heading (as I have done at the start under heading "What's in the Box?") in the same document, we need to do like:

HTML
<a href="#Images and different kinds of hyperlinks">Take me to "Images and different kinds of hyperlinks"</a>

which will render like: Take me to "Images and different kinds of hyperlinks".

To create a link for the "Images and different kinds of hyperlinks" from another page/website:

HTML
<a href="http://www.codeproject.com/Articles/750601/Beginners-Guide-to-HTML-CSS-Part-of#Images and different kinds of hyperlinks">Images and different kinds of hyperlinks</a>

The anchor can be created by id attribute also, like:

HTML
<a id="ImagesAndDifferentKindsOfHyperlinks">Images and different kinds of hyperlinks</a>

to create a link to this, we can do like:

HTML
<a href="#ImagesAndDifferentKindsOfHyperlinks">Take me to "Images and different kinds of hyperlinks"</a> 

Other Tags relating documents with HTML Page

The <link> tag

  • Appears at the head section of HTML Document.
  • The tag defines the relationship between a document and an external resource.
  • The tag is most used to link to Style Sheets. (it is a file, which includes all the Style Properties defined for the HTML Elements.)
Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Link Tag Example</title>
    <link rel="stylesheet" type="text/css" href="StyleSheet1.css">
    <link rel="stylesheet" type="text/css" href="StyleSheet2.css">
    <link rel="stylesheet" type="text/css" href="StyleSheet3.css">
</head>
...the rest of the document... 

Here relationship is defined by rel attribute and type says the MIME(Multipurpose Internet Mail Extensions) type of Document. You can see that three Style Sheets are linked to the HTML Page. The Styles or CSS Properties defined inside these Style Sheets will be applied to respective elements in the HTML Page.

The <Base> tag

  • Appears at the head section of HTML Document.
  • The tag specifies the base URL/target for all relative URLs (refer following Example) in a document.
  • There can be at maximum one element in a document.
Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Link Tag Example</title>
    <base href="http://www.somewebsite.com/somecategory/default.html" />
<body>
    <p>Have you seen this <a href="../someothercategory/someimage.gif"> Image</a>
</body>
</html>

the relative URI "../someothercategory/someimage.gif" would resolve to:

http://www.somewebsite.com/someothercategory/someimage.gif

Lists and Tables

Lists

To represent lists of information in our HTML Page, we can take help of certain tags defined for them. All lists must contain one or more list elements. That simply means Lists can be nested. Let's look at different types of Lists and their Syntax.

Tag syntax Tag restrictions What it does? Demo
Unordered List - <ul> Start tag: required, End tag: required A List represents list of information in either Ordered or Unordered or Descriptive way.
  • Item 1
  • Item 2
  • Item 3
Ordered List - <ol> Start tag: required, End tag: required
  1. Item 1
  2. Item 2
  3. Item 3
Description List - <dl> Start tag: required, End tag: required
Description 1
Item1
Description 2
Item 2

Let's explore one by one.

Unordered List

An Unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

Example 
HTML
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul> 

Refer Demo Column of table above to see how it renders on browser.

Ordered List 

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked with numbers. 

Example 
HTML
<ol>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ol>

Refer Demo Column of table above to see how it renders on browser.

Definitions

A description list is a list of terms/names, with a description of each term/name. The <dl> tag defines a description list. The <dt> - defines terms/names and <dd> - describes each term/name.

Example
HTML
<dl>
    <dt>Description 1</dt>
    <dd>Item1</dd>
    <dt>Description 2</dt>
    <dd>Item 2</dd>
</dl>

Refer Demo Column of table above to see how it renders on browser.

Tables

Tag syntax Tag restrictions What it does? Demo
<table> Start tag: required, End tag: required HTML Table is used to arrange data (text, preformatted text, images, links, forms, form fields, other tables, etc.) into rows and columns of cells.

Simple HTML Table.

Tadit Dash India
Code Project Canada

With Headers, Footers.

This is the Header Section.
Tadit Dash India
Code Project Canada
This is the Footer Section.

With Headings.

First Name Last Name Country
Tadit Dash India
Code Project Canada

Let's discuss more on HTML Tables.

  • Tables are defined with the <table> tag.
  • A table is divided into rows with the <tr> tag. (tr stands for table row)
  • Each small box inside a row is called a cell defined with the <td> tag. (td stands for table data)
  • A row can also be divided into headings with the <th> tag. (th stands for table heading)
  • The <td> elements are the data containers in the table.
  • The <td> elements can contain all sorts of HTML elements like text, images, lists, other tables, etc.

Simple HTML Table

Can be defined with <table>, <tr> and <td> tags.

Example 
HTML
<table>
    <tr>
        <td>Tadit</td>
        <td>Dash</td>
        <td>India</td>
    </tr>
    <tr>
        <td>Code</td>
        <td>Project</td>
        <td>Canada</td>
    </tr>
</table>

Refer the Demo column of table above to see how it renders on browser.

HTML Table with Headers and Footers

Can be defined with <table>, <tr>, <td> and <th> tags alongwith <thead>, <tfoot> and <tbody> tags.

Example
HTML
<table>
    <thead>
        <tr>
            <th colspan="3">This is the Header Section.</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tadit</td>
            <td>Dash</td>
            <td>India</td>
        </tr>
        <tr>
            <td>Code</td>
            <td>Project</td>
            <td>Canada</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="3">This is the Footer Section.</td>
        </tr>            
    </tfoot>
</table>

Here colspan="3" attribute defines that the cell would spread over all three columns of the Table.

Refer the Demo column of table above to see how it renders on browser.

HTML Table with Headings

Can be defined with <table>, <tr> and <td> and <th> tags.

Example
HTML
<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>Tadit</td>
        <td>Dash</td>
        <td>India</td>
    </tr>
    <tr>
        <td>Code</td>
        <td>Project</td>
        <td>Canada</td>
    </tr>
</table>

Refer the Demo column of table above to see how it renders on browser.

Emphasis tags (bold, strikethrough, italics, etc.)

These tags are used emphasize the text.

Tag syntax Tag restrictions What it does? Demo

Strike - <s>

Start tag: required, End tag: required Specifies Stroked text. Previously <strike> was used for this purpose, which is not supported in HTML5 anymore. Don't strike me.
Strong - <strong> Start tag: required, End tag: required It defines important text (usually bold), but allow for the actual styling to be controlled via CSS. Hence preferred in modern web pages. The <b> tag was used in previous HTML versions for Bold Text, which is suggested not to to use by HTML5 specifications. I am important and Bold.
Emphasize/Italics - <em> Start tag: required, End tag: required It renders as emphasized text (usually italics), but allow for the actual styling to be controlled via CSS. Hence preferred in modern web pages. The <i> tag was used for italics in previous HTML versions, which is suggested not to use in HTML5. I am Emphasized.

Other commonly used tags and new basic tags in HTML5

Common Tags

Following are some common tags.

Tag syntax Tag restrictions What it does? Demo
Big - <big> Start tag: required, End tag: required Specifies Big text. Content is shown in large type. 
The <big> tag is not supported in HTML5. Use CSS instead.
I am Big.
BlockQuote - <blockquote> Start tag: required, End tag: required Specifies Italics text. Content is shown as an indented block; should be used only for long quotations.
I am in quotes.
Break - <br> Start tag: required, End tag: not required Force line break within paragraph. This is a line before break.
Now this line is after break.
Center - <center> Start tag: required, End tag: required Content is centred on page (can include paragraphs etc).
The <center> tag is not supported in HTML5. Use CSS instead.
I am at center.
Delete - <del> and Insert - <ins> Start tag: required, End tag: required Used to indicate a deletion from a previous version of a document. Normally combined with ins (insert) which marks the new version. Rendered in strike-through font like <S>. I am a row cell.
Division - <div> Start tag: required, End tag: required A Division contains elements, which defines a group. Divisions can be designed using CSS styles.
I am inside a div having background color red.
Font - <font> Start tag: required, End tag: required Used to define characteristics of font, according to attributes e.g. SIZE, COLOR, FACE.
SIZE sets size, 1-7 e.g. SIZE="5".
COLOR sets colour of text e.g. <font color="#FF0000"> makes text red.
Face e.g. face="Verdana".
The <font> tag is not supported in HTML5. Use CSS instead.
My size is 5.
My color is Red.
My font face is Verdana
Heading -
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
Start tag: required, End tag: required Headings (levels 1-6, i.e. h3 is a subheading within a h2 subheading).

I am Heading 1.

I am Heading 2.

I am Heading 3.

I am Heading 4.

I am Heading 5.
I am Heading 6.
Mark the size of each heading.
Note: Here extra styling is applied by Code Project Styles.
Horizontal Line - <hr> Start tag: required, End tag: not required Draw horizontal line across page; used to indicate break between sections.
Attributes: width, e.g. width="50%" makes line half size of page;
size, e.g. size="3" makes line 3 pixels thick
None of the layout attributes are supported in HTML5. Use CSS instead.

Horizontal line -


Horizontal line with width 50% -


Paragraph - <p> Start tag: required, End tag: required A Paragraph.

I am inside one Paragraph having background color green.

Pre- formatted - <pre> Start tag: required, End tag: required Pre-formatted text.
I am Pre-formatted.
Small - <small> Start tag: required, End tag: required  Content appears as smaller-size text I am Small.
Span - <span> Start tag: required, End tag: required A dummy element which contains in-line content. It is used with style sheets. I am inside a Span having a background color gold.
Subscript - <sub> Start tag: required, End tag: required Subscript I am a Subscript.
Superscript - <sup> Start tag: required, End tag: required Superscript I am Superscript.
Underline - <u>  Start tag: required, End tag: required Underline text.
Note: The HTML 5 specification reminds developers that other elements are almost always more appropriate than <u>.
I am underlined.

New Basic Tags in HTML5

The New <canvas> Element

<canvas> is an HTML element which can be used to draw graphics using scripting (usually JavaScript). The <canvas> tag is only a container for graphics, you must use a script to actually draw the graphics.

Example

HTML
<canvas id="myCanvas">Your browser does not support the HTML5 canvas tag.</canvas>

<script>
    var c= document.getElementById('myCanvas');

    var ctx = c.getContext('2d');
    ctx.fillStyle = '#FF0000';
    ctx.fillRect(0,0,80,100);
</script>

Every canvas has a drawing context. Once we find a <canvas> element in the DOM (by using document.getElementById() or any other method), then we should call its getContext() method. You must pass the string "2d" to the getContext().

Demo Here

To explore more on canvas, go through HTML Canvas Reference and the Blog - LET’S CALL IT A DRAW(ING SURFACE).

Semantic Elements 

New elements for headers, footers, menus, sections and articles. Prior to HTML5, we have to arrange divisions (divs) in our Page and apply styles to them using their ID attribute. Now, we have specific tag for specific area of the Page.

Following is the sample web page structure comparison with HTML4 design:

Image 4  Image 5

HTML5 Form Elements

Tag syntax Tag restrictions What it does? Demo
Datalist - <datalist> Start tag: required, End tag: required Defines pre-defined options for input controls. Demo here

Note: The datalist tag is not supported in Internet Explorer 9 and earlier versions, or in Safari.
Keygen - <keygen> Start tag: required, End tag: not required Defines a key-pair generator field (for forms). Demo here

Encryption:

Note: The keygen tag is not supported in Internet Explorer.
Output - <output>  Start tag: required, required Defines the result of a calculation. Demo here

Note: The output tag is not supported in Internet Explorer.
Progress - <progress> Start tag: required, required Defines the progress of a task. Demo here

Downloading progress:


Note: The progress tag is not supported in Internet Explorer 9 and earlier versions.
Meter - <meter> Start tag: required, required Defines a scalar measurement within a known range (a gauge). Demo here

Display a gauge:
2 out of 10

60%

Note: The meter tag is not supported in Internet Explorer.

New Input Types

New input types have been introduced in HTML5. Previously to get these kind of inputs, we had to implement scripts or jQuery Plugins, but now with these types, it reduces work load on developers.

Most interesting thing about these types is that, validations are also handled implicity. As a developer, we know how much work we need to do validate data from a input field.

So, let's discuss more on these types. The new input types are as follows.

  • color
    The color type is used to select a color from popup color picker.

    Example
    HTML
    Select a color: <input type="color" name="favcolor">
  • date
    The date type allows the user to select a date.

    Example
    HTML
    Your Date Of Birth: <input type="date" name="bday">
  • datetime
    The datetime type allows the user to select a date and time (with time zone).

    Example
    HTML
    Select Date Time: <input type="datetime" name="daytime">
  • datetime-local
    The datetime-local type allows the user to select a date and time (no time zone).

    Example
    HTML
    Select Local Date Time: <input type="datetime-local" name="daytime">
  • email
    The email type is used for input fields that can contain an e-mail address.

    Example
    HTML
    E-mail: <input type="email" name="email">
  • month
    The month type allows to select a month and year.

    Example
    HTML
    Select Month and Year: <input type="month" name="daymonth">
  • number
    The number type is used for input fields that can contain a numeric value.

    Example
    HTML
    Select Number : <input type="number" name="quantity" min="1" max="5">
  • range
    The range type is used for input fields that can contain a value from a range of numbers.

    Example
    HTML
    <input type="range" name="points" min="1" max="10">
  • search
    The search type is used for search fields, but behaves same as a Text field.

    Example
    HTML
    Search: <input type="search" name="searchbox">
  • tel
    The tel type is used for input fields that should contain a telephone number.

    Example
    HTML
    Telephone: <input type="tel" name="telephone">
  • time
    The time type allows the user to select a time.

    Example
    HTML
    Select a time: <input type="time" name="yourTime">
  • url
    The url type is used to generate input fields that can contain a URL address. The value of the url field is automatically validated while form is submitted.

    Example
    HTML
    Add your URL: <input type="url" name="homepage>
  • week
    The week type allows the user to select a week and year.

    Example
    HTML
    Select a week: <input type="week" name="week_year">

Media Elements

Tag syntax  Tag restrictions What it does? Demo
Audio - <audio> Start tag: required, End tag: required Defines sound or music content Demo here
Video - <video> Start tag: required, End tag: not required Defines video or movie content. Demo here

Source - <source> 

Start tag: required, required Defines the result of a calculation. Demo here

Embed - <embed>

Start tag: required, required Defines containers for external applications (like plug-ins). Demo here

Using comments

The comment tag is used to insert comments in the source code. Comments are not rendered on the browsers. Comments are usually inserted to explain code, which can help you when you edit the source code later. This is very useful to manage the code when you have a good amount of code.

Syntax

HTML
<!-- I am a comment. -->

So, anything inside <!-- --> is interpreted as a Comment by browser.

Tips for structuring code and making it readable

Good code is always well formatted. So, make sure your code looks good by doing correct indentation. If you are using any Tools for Development, search if that Tool contains some feature to automatically format the code.

There is one online Tool, which can do this for you, that is jsfiddle. Write the HTML code inside HTML Box, then click on "TidyUp" option from the Menu. Let's see how it works.

Before TidyUp

See the code, which seems unformatted.

Image 6

After TidyUp

After we clicked the TidyUp Menu, it formats the code with correct indentation and spacing.

Image 7

While developing on Microsoft Visual Studio, you can use Shortcuts Control(Ctrl)-K-D. You need to press this combination at once. It will format your code and do the indentations for you, provided code is syntactically correct.

Browser support 

HTML5 is not yet fully supported by all browsers. That is because browsers are implementing the new specifications as per their plan. 

So, when you write any HTML5 code, make sure that it is supported across different browsers. To know that, you might refer: 

  • HTML5 Test - provides a HTML5 score with detail on what can be used
  • Can I Use - provides a table comparison of major browsers for different features

You can also take a look at the "Browser Support" Section of each HTML Tag when you read it from W3Schools

Points of Interest

First of all, thanks Code Project for the contest, otherwise this little article would not have been born.

I learnt a lot of thing while doing research on the topic. I will keep the space updated, whenever I find something interesting and useful 

References

http://www.w3.org/[^]
http://www.w3schools.com/[^]
http://caniuse.com/[^]
http://html5test.com/[^]
HTML5 Quick Start Web Application[^

History 

31 March 2014 - Initial Version. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)