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

5.00/5 (10 votes)
3 Apr 2014CPOL17 min read 38.6K   297  
Building on the Basics

List of Articles in Series

  1. Writing Your First Code
  2. Building on the Basics
  3. Styling Your First Web Page
  4. Laying Out Your First Web Page

Now It's HTML 5

In the previous part I wrote a lot about theory and history, but not too much about HTML 5 or CSS 3. Even we touched on some real code it wasn't really HTML 5 (and I hope you don't fell I cheated you). That code is a very good sample of basic HTML but has nothing (besides the document type declaration) that makes it HTML 5. In this part, however, we will learn about the new things that HTML 5 introduces into our document design (for CSS you will have to wait a bit longer).

As you already know HTML is all about structuring your content, marking the different parts according their functionality as a part in the whole document. HTML 5 adds a lot to help you structure your document in a better way by adding a few semantic tags. "What good of semantic tags?" you ask. Oh! You see, semantic tags are useful both for the developer (human) and for the browser (non-human), so both parties can easily understand the purpose of the content inside the tag (and when we will talk about CSS you will see how good semantic helps the designer too). And that is what HTML is about - defining your content in a way that can be presented to humans (using the aid of CSS), but also give the opportunity for non-human 'readers' to 'understand' your HTML document. In this article you will learn about the most important tags we use to create HTML documents. I will put an emphasis on the usage of the new things in HTML 5, and how they can help and improve older tags.

Can You See Me?

My wedding day...

This little magic (not me! but my picture inside the document) is made by using the IMG tag. The source behind the image looks like this:

HTML
<img src="me.jpg" width="150" height="150" alt="My wedding day...">  

You can see that IMG tag has several attributes, of which two, src and alt are required. Let's see the meaning of those attributes.

  • src is declaring the source where the actual image is loaded. You have to understand that the image is not really embedded inside the HTML document, but rather linked to it. It means that src is pointing to an external location from where the image loaded.
  • alt is used to declare some alternative text, that can be displayed on devices without the proper rendering capabilities (today it's rare, but in the early years of HTML text-based devices were more common). It can also help physically impaired people by allowing the browser to read the text out loud.
  • width and height are used to define the dimensions of the picture. These attributes are not required, but it's a good practice to provide them.

Now, remember that we are talking about content. Images may be used as illustrations, figures, diagrams or photos. HTML 5 introduces two new tags to aid you with a better declaration of such content - FIGURE and FIGCAPTION. Let see how it works...

HTML
<figure>
  <img src="green-energy.jpg" width="400" height="269" alt="Usage of green energy..." />
  <figcaption>Worldwide usage of green energy - 2005-2013</figcaption>
</figure>

This code will produce the image and the label below. It may not look like a big deal, but it is! What we have done is to logically (semantically) bind together an image and its corresponding title. From now on, we will not only be able to format it visually as a unit (with CSS of course, of which we currently know nothing) but also mark it for non-human 'readers'! This binding also enables to us to reference this figure as a unit from inside and outside this article.

Usage of green energy...

Worldwide usage of green energy - 2005-2013

Are You Connected?

When HTML (and WWW) started it was all about sharing the research results of scientists. At CERN the people look for a way to connect all the results into one, cross-linked, knowledge base. Like a well organized electronic library.

When it comes to HTML you will find two kind of links:

  1. LINK tag is used to add external resources to your page (where the browser is concerned, this means the resource pointed to by the link is part of the HTML document)
  2. A tag and AREA tag are used to define navigation to other HTML documents, or to other parts of the same HTML document.

Now, for the LINK tag it is one of the 'head elements' I mentioned in the first part, which means it is inside the HEAD tag. The only real life use of the LINK tag is bring the necessary CSS file in (LINK supports other resources, but no browser known to me implements those types). For instance, the article you are reading now has a LINK tag in it's HEAD like this:

HTML
<link type="text/css" rel="stylesheet" href="http://s.codeproject.com/App_Themes/CodeProject/Css/Main.min.css?dt=2.8.140326.1">

The LINK tag has several attributes that will declare its precise behavior.

  • The rel attribute defines the relationship between the HTML document and the resource. For us it will always be "stylesheet".
  • The type attribute tells the browser how to interpret the resource. Since we use LINK exclusively for stylesheets the value for type will be "text/css", which means that the resource file contains text, which is formatted according CSS rules.
  • The href attribute is the actual location of the resource to load. In our case it is somewhere on the CodeProject web server.

AREA tag - used together with IMG and MAP tag - is used to define an area inside an image that, when clicked, navigates you to the HTML document to which the tag points.

HTML
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
  <area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
  <area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

This is a sample is from w3school's site. Now let's understand it. You can see that the IMG tag got a new attribute - usemap. This attribute links the MAP tag, which is used to group the area declarations for that image. Notice the fit between the usemap attribute in IMG and the name attribute of the MAP tag! Now, every AREA tag declares an area inside the image. The shape and the coordinates of the area are declared using the shape and coords attribute respectively. The href attribute is used in exactly the same way as the LINK tag.

And now for the A tag. It's used everywhere. In this article you can see that little blue arrow everywhere. Behind every of them there is an A tag. Let's take a look at one of them.

HTML
<a href="http://www.w3schools.com/tags/tag_a.asp">A</a>

As before, href indicates the location where this link will take you if you hit it. A tag also can be used to define an anchor inside the HTML document. This anchor can be used to build a series of links within a document itself, like a table of contents or end notes. It also can be used to link to a specific part of an external document.

HTML
<a> <a id="figure1><figure>...<figure></a>

This line declares an anchor that can be accessed from within that same HTML document using this A tag:

HTML
<a href="#figure1">See Figure 1...</a>

The next example will take you to the anchor named 'sample' in the page 'tag_a.asp' on the w3school site...

HTML
<a href="http://www.w3schools.com/tags/tag_a.asp#sample">A</a>

You will see that A tag is very useful for building tables of contents, navigation menus, or any kind of internal and external web you can conceive (you can also see a table of contents at the top of this article).

How to Bake Bread

Whenever you make food the first step is to ensure you have all the ingredients, then you go thought the recipe to actually make that food. Both the ingredients and steps involved preparing your dish are lists, and HTML has fine list command for you.

The main list structures are UL - unordered list, and OL - ordered list. Unordered and ordered do not mean that these lists are de facto ordered or not ordered, it's all about semantic meaning. UL tells the browser that the order of the elements in the list is meaningless, while OL tells the browser that the order is important.

Now let's see some examples:

HTML
<ul>
  <li>1 spoon of dried yeast</li>
  <li>3 cups of water</li>
  <li>1 spoon of sugar</li>
  <li>2 spoon of salt</li>
  <li>1/2 cup of olive oil</li>
  <li>1 kg wheat</li>
</ul>
  • 1 spoon of dried yeast
  • 3 cups of water
  • 1 spoon of sugar
  • 2 spoon of salt
  • 1/2 cup of olive oil
  • 1 kg wheat
HTML
<ol>
  <li>Mix the wheat with the yeast and the sugar</li>
  <li>Add oil and water and knead until it became smooth</li>
  <li>Add salt and knead until concealed</li>
</ol>
  1. Mix the wheat with the yeast and the sugar
  2. Add oil and water and knead until it became smooth
  3. Add salt and knead until concealed

As you can see the browser made the two lists visually different. UL has dots before its items but OL has numbers - indicating an order. What is common between these two types of lists is LI, which represents a single item in the list for both types of lists.

These lists can be nested to achieve a multi-level list. You will find that in every site with a menu the developer used an unordered list to create that menu. For instance, the HTML behind the articles menu in CodeProject looks like this (with a bit of simplification):

HTML
<ul>
  <li>Chapters and Sections
    <ul>
      <li>[More menues]</li>
    </ul>
  </li>
  <li>Search</li>
  <li>Latest Articles</li>
  <li>Latest Tips/Tricks</li>
  [More items]
</ul>

You may notice that the real menu looks completely different from the lists we just saw. That is because of the magic CSS can perform when used (be patient, we get to CSS).

Another type of list HTML supports is the description list - DL. This is a two-level list for terms and their definition. These may be used in dictionaries or whenever you need to list terms, like in a preface for a scientific article. To declare the term(s) we use the DT tag, and to list the definitions we use the DD tag...

HTML
<p><strong>Description:</strong>
  <dl>
    <dt>Synonyms</dt>
      <dd>Definition</dd>
      <dd>Explanation</dd>
      <dd>Information</dd>
      <dd>Characterization</dd>
    <dt>Antonyms</dt>
      <dd>Concealment</dd>
      <dd>Misrepresentation</dd>
  </dl>
</p>

Description:

Synonyms
Definition
Explanation
Information
Characterization
Antonyms
Concealment
Misrepresentation

If you stop for a moment you can understand that this list can be done with any of the previously examined list types. But remember HTML is all about the structure and semantics of your content. So these different types of lists are not for you as a developer but as tools for content definition!

Show your data

We already saw an image of a chart as a way of presenting data inside an HTML document, now I will show you how to add some tabular data.

But just before that I want to take you back to the first part of this series. Back then I wrote about the layout of the document and mentioned that some developers (and designers too) used tables to do layouts. I warn you not to do that! It has a huge maintainability problem. In a few minutes you will understand that tables can became extremely complicated while layouts should be simply. So do not use them!

So let's see some tabular data sample from the CodeProject weekly poll results (I removed all the formatting to help your understanding).

HTML
<table>
  <caption>Weekly poll</caption>
  <thead>
    <tr>
      <th>Option</th>
      <th>Votes</th>
      <th>%</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <td>Responses</td>
      <td>1991</td>
      <td>&nbsp;</td>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Back / neck problems</td>
      <td>945</td>
      <td>47.46</td>
    </tr>
    <tr>
      <td>Shoulder / Elbow joint problems</td>
      <td>445</td>
      <td>22.35</td>
    </tr>
    <tr>
      <td>Forearm / wrist / hand (including carpel tunnel)</td>
      <td>553</td>
      <td>27.77</td>
    </tr>
    <tr>
      <td>Other Musculoskeletal problems</td>
      <td>143</td>
      <td>7.18</td>
    </tr>
    <tr>
      <td>Vision / eye problems</td>
      <td>806</td>
      <td>40.48</td>
    </tr>
    <tr>
      <td>Headaches</td>
      <td>445</td>
      <td>22.35</td>
    </tr>
    <tr>
      <td>Obesity</td>
      <td>506</td>
      <td>25.41</td>
    </tr>
    <tr>
      <td>Mental health issues</td>
      <td>245</td>
      <td>12.31</td>
    </tr>
    <tr>
      <td>Other</td>
      <td>117</td>
      <td>5.88</td>
    </tr>
    <tr>
      <td>No issues for me!</td>
      <td>360</td>
      <td>18.08</td>
    </tr>
  </tbody>
</table>
Weekly poll
Option Votes %
Responses 1991
Back / neck problems 945 47.46
Shoulder / Elbow joint problems 445 22.35
Forearm / wrist / hand (including carpel tunnel) 553 27.77
Other Musculoskeletal problems 143 7.18
Vision / eye problems 806 40.48
Headaches 445 22.35
Obesity 506 25.41
Mental health issues 245 12.31
Other 117 5.88
No issues for me! 360 18.08

OK. That was a good piece of code. As you see the TABLE tag is used to enclose your tabular data. It has four children where every one of them defines a semantically different part of the date:

  • CAPTION - is used to declare a human readable caption for the table.
  • THEAD is used to declare some heading information for every column.
  • TFOOT is used to display some closing info - in our case a kind of summary about the votes.
  • TBODY is encloses the actual data to be displayed.

You may be surprised by the orders of the tags - simple human logic says use that it should be header, body, footer. However, HTML has nothing with simple human logic. It states that footer has to come just after header and before body (I may spoil it, but I will tell you that browsers don't actually care about that order so you can put footer at the end).

For the rest, TR is defines a row of information and TD or TH define a data cell. The only differences between the two is semantic. TH used inside THEAD and TD is used everywhere else.

Now think of some financial data, then think of that data as a figure inside a monthly report. Yes, you can wrap tables inside FIGUREs just as we did with the image a few paragraphs above! That's a good example of using semantics to define content and that's the first thing you have to use on your way to becoming an HTML expert.

More Semantics

In this part I would like to show you some more tags you can use to define your content in a better way. I will spit it into two parts:

  • Article level semantics. The tags in this group used to define different parts of the HTML document.
  • Text level semantics are used inside a block of text to define parts of text
  • PRE tag

Article level semantics

We already talked about headings (H1-H6) that can be used to build some kind of hierarchy inside an HTML document. However, we have some more tags that can be used to such hierarchy...

ARTICLE tag is used to define a part of an HTML document that is totally independent from the other parts. It means that the content inside an ARTICLE tag makes sense on its own, it can be moved out of its original context without changing its meaning. For instance, this article can be marked as an ARTICLE, or inside a blog-site where every single blog can be marked that way.

SECTION tag is used to define smaller parts of an article like chapters. The info inside a section is connected, but will not stand by itself.

HEADER and FOOTER tag is used to mark a global opening and closing content for the whole HTML document in an article or section.

NAV tag is used to enclose the major navigation links inside an HTML document, article or section. The most sufficient use is to enclose the site menu with a NAV tag. You have to remember that not ALL the navigation links have to be enclosed by the NAV tag, it's only used to mark the main block of navigation list. If you search for design samples for the NAV tag you will mostly find that there is one inside the HEADER tag and one inside the FOOTER tag.

ASIDE tag is used to define some content that is not directly connected to its counterpart (the content ASIDE placed in) but the reader may have some interest in it. Let's say you are writing a blog about a place you just visited, you may put the contact info of the place in an ASIDE tag.

This example shows you how these tags can be related to each inside HTML document:

HTML
<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title></title>
</head>
<body>
  <h1>My Blog</h1>
  <header>
    <nav>
      <ul>
        <li>How to count from 1 to ten using your fingers...</li>
        <li>Do not kiss him on the first meeting...</li>
      </ul>
    </nav>
  </header>
  <article>
    <h2>How to count from 1 to ten using your fingers...</h2>
    <section>
      <p>
        Paragraph one
      </p>
      <p>
        Paragraph two
      </p>
    </section>
    <section>
      <p>
        Paragraph one
        <aside>A funny joke I just remembered</aside>
      </p>
      <p>
        Paragraph one
      </p>
    </section>
  </article>
  <article>
    <h2>Do not kiss him on the first meeting...</h2>
    <section>
      <p>
        Paragraph one
      </p>
      <p>
        Paragraph two
      </p>
    </section>
    <section>
      <p>
        Paragraph one
        <aside>What to tell him to make him go!</aside>
      </p>
      <p>
        Paragraph one
      </p>
    </section>
  </article>
  <footer>
    <nav>
      <ul>
        <li>How to count from 1 to ten using your fingers...</li>
        <li>Do not kiss him on the first meeting...</li>
      </ul>
    </nav>
    <p>Copyright 2014</p>
  </footer>
</body>
</html>

Text level semantics

These semantic tags are not breaking your content into large parts, but define small parts (sometimes words only) as semantically different from its surrounding.

EM tag is used to mark some part of the content as emphasized. By default browsers render EM as italic.

STRONG tag is used to mark text as important. The default rendering for this is bold.

SMALL tag is used to mark text that less important. The default rendering for SMALL is - smaller font.

CITE tag is used to mark the person who's word is being cited. The default rendering is italic text for CITE.

Q tag is used to mark parts of content that are quoted from other source. Browsers will enclose such text in quotation marks.

BLOCKQUOTE tag is the same as Q but used for large blocks of quoted text. Browsers will indent text inside BLOCKQUOTE.

ABBR tag is used to define the meaning of an abbreviation in the text. The browser will use ABBR to create a tool tip on the abbreviation.

MARK tag is used to mark some element that should be highlighted. Browsers use different background color for such a text.

CODE tag is used to mark content that represents some computer source code. Browsers render such content in different font.

Remember that these tags are not to used for large parts of text and with the exception of BLOCKQUOTE, are used for a small number of words only.

These samples were taken from w3c...

HTML
<p><strong>EM tag</strong></p>
<p>I must say I <em>adore</em> lemonade.</p>
<p><strong>STRONG tag</strong></p>
<p>This tea is <strong>very hot</strong>.</p>
<p><strong>SMALL tag</strong></p>
<p>These grapes are made into wine. <small>Alcohol is addictive.</small></p>
<p><strong>CITE tag</strong></p>
<p>The case <cite>Hugo v. Danielle</cite> is relevant here.</p>
<p><strong>Q tag</strong></p>
<p>The judge said <q>You can drink water from the fish tank</q> but advised against it.</p>
<p><strong>BLOCKQUOTE tag</strong></p>
<blockquote><p>
    The truth may be puzzling. It may take some work to grapple with.
    It may be counterintuitive. It may contradict deeply held
    prejudices. It may not be consonant with what we desperately want to
    be true. But our preferences do not determine what's true. We have a
    method, and that method helps us to reach not absolute truth, only
    asymptotic approaches to the truth — never there, just closer
    and closer, always finding vast new oceans of undiscovered
    possibilities. Cleverly designed experiments are the key.
</p></blockquote>
<p><strong>ABBR tag</strong></p>
<p>Organic food in Ireland is certified by the <abbr title="Irish Organic Farmers and Growers Association">IOFGA</abbr>.</p>
<p<strong>>MARK tag</strong></p>
<p>Elderflower cordial, with one <mark>part</mark> cordial to ten <mark>part</mark>s water, stands a<mark>part</mark> from the rest.</p>
<p><strong>CODE tag</strong></p>
<p>The <code>fruitdb</code> program can be used for tracking fruit production.</p>

Image 3

PRE tag

I put this tag in it's own section because before you can understand it you have to understand something about HTML. You already have seen some HTML code samples, and all those samples were formatted nicely with indentations and spaces for easy reading. What you have not seen is that white-spaces are does not matter for HTML. HTML is ignorant about white-spaces. You may break text inside your paragraph, add an extra 200 spaces, but HTML will ignore it. HTML collapses continuous white-spaces into one single space and them renders the content, introducing its own breaking according the physical size of the rendering device. So what if you want to preserve a special formatting (like in sample code inside this article)? For that we have the PRE tag. Text inside PRE tag will preserve its original formatting including breaks and white-spaces.

Some Good News

HTML 5 introduced a lot of tags to aid the creation of HTML document. Most of these tags are about semantically tight content, but there are two that are about the type of content itself.

VIDEO tag

You never will guess it so I will tell you. The VIDEO tag is used to add some video content to your document.

HTML
<video controls width="480px">
  <source src="video.ogg">
  No video for you. Move to some decent browser...
</video>

Image 4

AUDIO tag

By the same idea AUDIO tag can be used to add some audio to your HTML document.

HTML
<audio controls width="240px">
  <source src="audio.mp3" />
  No audio for you. Move to some decent browser...
</audio>

Image 5

No comment

In some cases a developer adds comments to his code. It can be useful to explain some tricky solutions to other developers on the same team or just to remember why you did something the way you did.

The HTML comment tag is different from any other tag, it looks like this

HTML
<!--In fact there is a comment...-->

Use this tag anywhere you feel the need for some explanation for yourself and do not be afraid because these comments are invisible in browsers.

Best practices for code writing

HTML lacks any rules about how you should write it. No formatting restrictions, or when to break lines and how to indent code. However, you may noticed that I always do indentations and break lines and the reason why is to make my code as readable as possible. I would advise you do the same.

You may also notice that I use lower case for all the HTML tags (except DOCTYPE). It's not mandatory to use any case, you can even mix between upper and lower case, but I would advise you to stick to one case, which will also help you to understand the code you write.

Browser Support

After all the years of forming HTML 5, it's still in 'Candidate Recommendation' status. It means that until recently it was changed at a very high rate. The immediate result of that is that different browsers support different tags in a different way (if at all). So when using a new HTML 5 tag you have to prepare yourself for the case that the tag isn't supported on the client's browser.

For checking browser support you may use w3school.com.

Summary

I bombarded you in this article with a large amount of information, of which most may not make total sense to you. It's all right, you may read again and again until it does. But there is a short-cut. Practice! If you decided to learn HTML 5 it's not without a reason. You probably have some thoughts about to where to use it, so go on, open you editor and try to implement your ideas using your new knowledge. Becoming an expert is 5% learning - the other 95% comes from hard work.

License

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