Trang chủ‎ > ‎IT‎ > ‎WEB PROGRAMMING‎ > ‎01 - HTML‎ > ‎

Tutorial - Building website using HTML5 and CSS3 - Advanced

Tables

While tables are essential for organizing information, they're a bit tricky to build in HTML: this is why I've waited until now to tell you about them. Indeed, you'll have to embed new HTML tags in a specific order.

We're going to begin by building basic tables and then gradually go on to more complex aspects: merging cells, dividing into multiple sections... We're also going to find out about table-related CSS properties, used to customize their appearance.

A simple table

The first tag you need to know about is <table> </table>. It's this tag that specifies the start and end of a table.

This tag is a block tag, so it has to be placed outside a paragraph. Example:

<p>This is a paragraph before the table.</p>
<table>
<!-- Insert here your table content -->
</table>
<p>This is a paragraph after the table.</p>

OK, so what do you write inside the table?

At this point, get ready for a new avalanche of tags.
To start off slowly, here are two very important new tags:

  • <tr> </tr>: specifies the start and end of a table row;

  • <td> </td>: specifies the start and end of the cell contents.

In HTML, a table is built row by row. In each row (<tr>), the contents of the cells is specified (<td>).
A table is basically constructed as shown in the figure below.

A table, with cells contained in linesA table, with cells contained in lines

It has a row tag (<tr>) which includes a group of cells (<td>).
For example, if I want to build a table with two rows, with three cells per row (thus three columns), I would type this:

<table>
<tr>
<td>Carmen</td>
<td>33 years old</td>
<td>Spain</td>
</tr>
<tr>
<td>Michelle</td>
<td>26 years old</td>
<td>United States</td>
</tr>
</table>

The result is a bit depressing (figure below).

A table without bordersA table without borders

You call that a table?
The text follows on continuously and there aren't even any borders!

Yes, a table without CSS seems pretty empty. And rightly so, since adding borders is very simple. You already know the corresponding CSS code!

td /* All table cells... */
{
border: 1px solid black; /* will have a 1px border */
}

And here's the result in the figure below.

Each cell has its own borderEach cell has its own border

Um, it's not yet as perfect as you'd what. Indeed, we'd really like only one border between two cells and that's not the case here.

Fortunately, there is a CSS property specific to tables, border-collapse, which means "stick borders together".
This property can take two values:

  • collapse: the borders are stuck together; this is the effect we're looking for here;

  • separate: the borders will be split (default value).

table
{
border-collapse: collapse; /* The table borders will be stuck together (nicer looking) */
}
td
{
border: 1px solid black;
}

The figure below shows the result obtained.

The borders are stuck togetherThe borders are stuck together

Now that's better!

The header row

Now that we've what we wanted, we're going to add the table's header row. In the example below, the headers are "Name", "Age" and "Country".
The header row is created with a <tr> tag as we've done so far, but the cells it contains are this time framed by <th> tags and not <td>!

<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Carmen</td>
<td>33 years old</td>
<td>Spain</td>
</tr>
<tr>
<td>Michelle</td>
<td>26 years old</td>
<td>United States</td>
</tr>
</table>

The header row is easy to recognize for two reasons:

  • the cells are <th> tags rather than the usual <td> tags;

  • it's the first row of the table (it has to be pointed out, even though it may be obvious).

As the cell name is slightly different for the header, remember to update the CSS code to tell it to apply a border around normal cells and the header (figure below).

table
{
border-collapse: collapse;
}
td, th /* Assign a border to the td AND th tags */
{
border: 1px solid black;
}
A table with a headerA table with a header

As you can see, your browser has bolded the text in the header cells. Although this is what browsers usually do, you can, if you want, change this using CSS: change the background color, font, borders, etc. of the header cells.

Table title

Normally, all tables must have a title. The title quickly informs the visitor about the table content.
Our example is a just list of people... but so what? What does it represent? Without the table title, we're a bit lost, as you can see.

Fortunately, there's <caption>!
This tag is placed right at the start of the table, just before the header. It's the tag that contains the table title (figure below):

<table>
<caption>Passengers of flight 377</caption>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Carmen</td>
<td>33 years old</td>
<td>Spain</td>
</tr>
<tr>
<td>Michelle</td>
<td>26 years old</td>
<td>United States</td>
</tr>
</table>
A table with a titleA table with a title

Ah, that's a bit clearer!

Note that you can change the title position using the CSS caption-side property which can take two values:

  • top: the title will be placed above the table (as default);

  • bottom: the title will be placed below the table.

A structured table

We have learned how to build small, simple tables. While these small tables are sufficient in most cases, you may sometimes need to build more complex tables.

We are going to find out about two special techniques:

  • Large tables can be divided into three parts:

    • Header;

    • Table body;

    • Table footer.

  • For some tables, you may need to merge cells together.

Dividing up a big table

If your table is fairly big, it's best to divide it into several parts. For this purpose, HTML tags are used to define the three "fields" of the table:

  • the header (at the top): is defined with the tags <thead></thead>;

  • the body (in the center): is defined with the tags <tbody></tbody>;

  • the table footer (at the bottom): is defined with the tags <tfoot></tfoot>.

What should you put in the table footer? If it's a long table, you'll usually copy the header cells. This allows you to see what each column refers to, even at the bottom of the table. Basically, a table is divided into three parts as shown in the figure below.

A table split up into several partsA table split up into several parts

It's a bit confusing, but it's advisable to write the tags in the following order:

  1. <thead>

  2. <tfoot>

  3. <tbody>

So, in the code, you define first the top part, then the bottom part, and finally the main part (<tbody>). Don't worry, the browser will take care of displaying each element in the right place.

So here's the code to be entered to build the table in three parts:

<table>
<caption>Passagers du vol 377</caption>
<thead> <!-- Passengers of flight 377 -->
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tfoot> <!-- Table footer -->
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</tfoot>
<tbody> <!-- Table body -->
<tr>
<td>Carmen</td>
<td>33 years old</td>
<td>Spain</td>
</tr>
<tr>
<td>Michelle</td>
<td>26 years</td>
<td>United States</td>
</tr>
<tr>
<td>François</td>
<td>43 years old</td>
<td>France</td>
</tr>
<tr>
<td>Martine</td>
<td>34 years old</td>
<td>France</td>
</tr>
<tr>
<td>Jonathan</td>
<td>13 years old</td>
<td>Australia</td>
</tr>
<tr>
<td>Xu</td>
<td>19 years old</td>
<td>China</td>
</tr>
</tbody>
</table>

You don't necessarily need to use these three tags (<thead><tbody><tfoot>) in all tables. In fact, you'll use them more especially if your table is fairly big and you need to organize it more clearly.
For "small" tables, you can easily keep the simpler organization we saw at the beginning.

3, 2, 1… Merge!

In some complex tables, you'll need to "merge" the cells together.
An example of merging? The table in the figure below provides a list of films and their intended audience.

A table containing film titles and their audienceA table containing film titles and their audience

For the last film, you can see that the cells have been merged into one This is exactly the effect we are trying to achieve.

To merge, you add an attribute to the tag <td>. There are two types of merging:

    • Merging of columns: this is what I've just done in this example. The cells are merged horizontally.

The colspan attribute is used.

    • Merging of rows: in this case, two rows are merged into one. The cells are merged vertically.

The rowspan attribute is used.

As you know, you have to give a value to the attribute (whether it be colspan or rowspan). You have to specify the number of cells to be merged together. In our example, we merged two cells: the cell of the "For children?" column the cell of the "For adolescents?" column ». We thus have to enter:

<td colspan="2">

… which means: "This cell is the merging of two cells." You can merge several cells at once (three, four, five, etc. as much as you want).

Here's the HTML code that merges the corresponding cells of the table above:

<table>
<tr>
<th>Film title</th>
<th>For children?</th>
<th>For adolescents?</th>
</tr>
<tr>
<td>Chainsaw massacre</td>
<td >No, too violent</td>
<td>Yes</td>
</tr>
<tr>
<td>The care bears go skiing</td>
<td>Yes, suitable</td>
<td>Not violent enough...</td>
</tr>
<tr>
<td>Lucky Luke, goes it alone</td>
<td colspan="2">For the whole family!</td>
</tr>
</table>

Important note: you can see that line 19 only contains two cells instead of three (there are only two tags <td>). This is quite normal as I merged the last two cells together. The <td colspan="2"> specifies that this cell takes the place of two cells at a time.

And how do you proceed for vertical merging with rowspan?

This is a bit more complicated. For our example, we going to "reverse" our table order: instead of putting the film titles on the left, we'll put them at the top.
It's another way of seeing the table: instead of building height-wise, we can build it length-wise.

In this case colspan is no longer suitable and rowspan should be used:

<table>
<tr>
<th>Film title</th>
<td>Chainsaw massacre</td>
<td>The care bears go skiing</td>
<td>Lucky Luke, goes it alone</td>
</tr>
<tr>
<th>For children?</th>
<td>No, too violent</td>
<td>Yes, suitable</td>
<td rowspan="2">For the whole family!</td>
</tr>
<tr>
<th>For adolescents?</th>
<td>Yes</td>
<td>Not violent enough...</td>
</tr>
</table>

Result: the cells are merged vertically (figure below)!

The cells have been vertically mergedThe cells have been vertically merged

Note that you can change the vertical alignment of the text in table cells using the vertical-align that we found out about in the chapter on page layout.

Summing up

  • A table is inserted using the <table> tag and is defined row by row using the <tr> tag.

  • Each row contains <td> cells (normal cells) or <th> cells (header cells).

  • The table title is defined using <caption>.

  • You can add a border to the table cells using border. To merge borders, you use the CSS property border-collapse.

  • A table can be divided into three sections: <thead> (header), <tbody> (body) and <tfoot> (table footer). The use of these tags is not compulsory.

  • You can merge cells horizontally using the colspan attribute or vertically using rowspan. You have to specify how many cells have to be merged.

Forms

Log in or subscribe for free to enjoy all this course has to offer!

Any HTML page can be enhanced with interactive forms that prompt visitors to fill in information: enter text, select options, confirm with a button... anything is possible!

However, we are reaching the limits of the HTML language as you then have to analyze the information that the visitor has entered... and this can't be done in HTML. As we're going to see, the results have to be processed in another language, such as PHP, for example.

In the meantime, we have a large number of new HTML tags to discover. Welcome to the wonderful world of forms. A world where buttons, checkboxes and drop-down lists coexist harmoniously (well almost).

Creating a form

When you have the sudden urge to insert a form in your HTML page, you need to start by writing a<form> </form>tag. This is the form's main tag and it specifies its start and end.

<p>Text before the form</p>
<form>
<p>Text inside the form</p>
</form>
<p>Text after the form</p>

Note that you have to enter block tags (as<p> </p>) inside your form if you want to include text in it.

So much for basic structure. Now, pay attention: what I'm going to tell you isn't easy as we've reached the limits of HTML.

Let's take an example to make things clear. Suppose your visitor has just entered a comment in your form, such as, for example, a message that they'd like to publish in your forums. This message has to be sent so that you can receive it (logical, right?) and display it to your other visitors.

Well, that's the problem, or rather those are the problems, we're going to address:

  • Problem No 1: how do you submit the text entered by the visitor? By what means?

  • Problem No 2: once the data have been sent, how do you process them? do you want to receive the message automatically by e-mail or would you prefer a program to save it somewhere, and then display it in a page that everyone can see?

To provide the solutions to these two problems, you have to add two attributes to the<form>tag:

  • method: this attribute specifies the means by which the data are going to be sent (solution to problem No 1). There are two ways to submit data to the Web:

    • method="get": this is a method that is generally not well suited as it's limited to 255 characters. The particularity comes from the fact that the information will be sent to the page address (http://…), although this detail doesn't really matter for the time being. I recommend you use the other method most of the time:post.

    • method="post": it's the most widely used method for forms as it allows a lot of information to be sent. The data entered in the form don't go through the address bar.

  • action: is the address of the page or program that is going to process the information (solution to problem No 2). This page will send you an e-mail with the message if this is what you want, or else save the message with all other messages in a database.
    This can't be done in HTML and CSS so we generally use another language that you may have heard about: PHP.

So we're now going to complete the<form>tag with two attributes that we've just seen.

Formethod, you've guessed it, I'm going to enter the valuepost.
Foraction, I'm going to enter the name of a fictitious page in PHP (traitement.php). This is the page that will be called when the visitor clicks on the submit button in the form.

<p>Text before the form</p>
<form method="post" action="target.php">
<p>Text inside the form</p>
</form>
<p>Text after the form</p>

For the time being, we don't know what happens inside the pagetarget.php: let's take my word for it and assume that this page is up and running.

Our priority, for the time being, is to find out in HTML/CSS how to insert text fields, buttons and checkboxes in our web page. And this is what we're going to see now.

Basic entry fields

So, let's get back to something tangible.

We're going to review the various HTML tags needed to enter text in a form.
You should know that there are two different text fields:

  • The single-line text field: as its name suggests, you can only enter a single line into it. It's used to enter short texts, such as a user name.

  • The multi-line text field: this text field allows you to enter a large amount of text on several lines, for example, a dissertation on the use of HTML in the development of countries of South-East Asia (just a suggestion, eh... ).

Single-line text field

The figure below shows what a single-line text field looks like.

A single-line text fieldA single-line text field

To insert a text field in a line, we're going to use the tag<input />.

We'll come across this tag several times later in this chapter. In each case, it's the value of thetypethat will change.

To create a single-line text field, you have to enter:

<input type="text" />

This is still not enough: you have to give your text field a name. Although this name doesn't appear on the page, you'll need it later. Indeed, it'll tell you (in PHP, for instance) where the information comes from: you'll know that such and such a text is the visitor's user name, such and such a text is the password they've chosen, etc.

To give a name to a form item, you use the attributename. Here, we're going to assume that the visitor is asked to re-enter their user name:

<input type="text" name="pseudo" />

So let's try to create a very basic form with our text field:

<form method="post" action="target.php">
<p><input type="text" name="username" /></p>
</form>

As usual, I strongly suggest you try this code yourself to see the result.

Labels

This text field is all very well but if your visitor comes across it, they won't know what to enter. This is precisely the role of the<label>tag:

<form method="post" action="target.php">
<p>
<label>Your user name</label> : <input type="text" name="username" />
</p>
</form>

This code gives the exact same result that you saw in the previous figure.

But this is not enough. You have to link the label to the text field.
To do this, you have to give the text field a name, not using thenameattribute but with theidattribute (that can be used with all tags).

Anameand anidin the field? Won't that be redundant?

Yes, somewhat. Personally, I givenameandidthe same value, this is not a problem.

To link the label to the field, it has to be given anforattribute which has the same value of the fieldid... It's best to see this in an example:

<form method="post" action="target.php">
<p>
<label for="username">Your user name</label> : <input type="text" name="username" id="username" />
</p>
</form>

Try clicking on the "Your user name" text: you'll see that the cursor is automatically placed in the corresponding text field.

A few additional attributes

You can add a number of other attributes to the<input />tag to customize its operation:

  • You can increase the size of the field usingsize.

  • You can limit the number of characters that can be entered usingmaxlength.

  • You can pre-populate the field with a default value usingvalue.

  • You can give some indication of the field's contents usingplaceholder. This indication will disappear as soon as the visitor has clicked inside the field.

In the following example, the text field contains an indication providing an understanding of what should be entered; although the field is 30 characters long, you can't enter more than 10 characters inside:

<form method="post" action="target.php">
<p>
<label for="username">Your user name:</label>
<input type="text" name="username" id="username" placeholder="Zozor" size="30" maxlength="10" />
</p>
</form>

Test the result yourself to see how the field behaves. In the meantime, the figure below shows how the field looks in its initial state.

A text field with an indication (placeholder)

Password field

You can easily make the text field behave like a "password field", in other words, a field where you don't see on the screen the characters entered. To create this type of entry field, use the attributetype="password".

I'll fill in my form. It now prompts the visitor to enter their user name and their password:

<form method="post" action="target.php">
<p>
<label for="username">Your user name:</label>
<input type="text" name="username" id="username" />
<br />
<label for="pass">Your password:</label>
<input type="password" name="pass" id="pass" />
</p>
</form>

You'll see that the password characters aren't displayed on the screen, as shown in the figure below.

A password entry field

Multi-line text field

To create a multi-line text field, you change the tag: we're going to use<textarea> </textarea>.

Like any other form item, you have to give it a name usingnameand use alabelthat explains what it is.

<form method="post" action="target.php">
<p>
<label for="improve">How do you think I could improve my website?</label><br />
<textarea name="improve" id="improve"></textarea>
</p>
</form>

And here's the result as an image (figure below)!

A small multi-line entry fieldA small multi-line entry field

As you can see, it's a bit small! Fortunately, you can change the size of<textarea>in two different ways.

  • In CSS: just apply the CSS propertieswidthandheightto<textarea>.

  • With attributes: you can add the attributesrowsandcolsto the tag<textarea>. The first one specifies the number of lines of text that can be displayed simultaneously, and the second one the number of columns.

Why do you open the<textarea>tag and then close it again immediately afterwards?

You can pre-populate<textarea>with a default value. In this case, we don't use the attributevalue: we simply enter the default text between the opening tag and the closing tag!

<form method="post" action="target.php">
<p>
<label for="improve">
How do you think I can improve my website?
</label>
<br />
<textarea name="improve" id="improve" rows="10" cols="50">
Improve your website?!
Come now! It's so great it won't need any improving!
</textarea>
</p>
</form>

And here's the result in the figure below.

A pre-completed multi-line entry fieldA pre-completed multi-line entry field

Enhanced entry fields

HTML5 provides many new features related to forms. Indeed, new field types emerged with this version. Just give thetypeattribute of the<input />tag one of the new available ​​values. Let's do a quick overview!

All browsers don't yet recognize these enhanced entry fields. In their place, older browsers will display a simple single-line text field (as if you'd enteredtype="text"). Between you and me, this is just fine: new browsers can enjoy the latest features, while older browsers display a replacement text field that fits just as well.
So you're advised to use these new entry fields from now on! At best, your visitors will benefit from the new features and, at worst, they won't see any problem.

Email

You can prompt visitors to enter an email address:

<input type="email" />

The field will normally seem the same to you, but your browser now knows that the user has to enter an email address. It can display an indication if the address is not an email, which is what Firefox does, for example (figure below).

An incorrectly entered e-mail is framed in red in FirefoxAn incorrectly entered email is framed in red in Firefox

Note that some browsers, such iPhone and Android mobile browsers for example, display a keyboard suitable for entering email addresses (below).

iPhone e-mail entry keyboardiPhone email entry keyboard

A URL

With theurltype, you can prompt the visitor to enter an absolute address (usually starting withhttp://):

<input type="url" />

Same principle: if the field doesn't seem different on your computer, be aware that it has effectively understood that the visitor is supposed to enter an address. For example, mobile browsers display a keyboard suitable for entering URLs (figure below).

iPhone URL entry keyboardiPhone URL entry keyboard

Phone number

This field is used for entering phone numbers:

<input type="tel" />

On the iPhone, for example, a suitable keyboard is displayed when the visitor has to fill in the field (figure below).

iPhone phone number entry keyboardiPhone phone number entry keyboard

Number

This field is used to enter an integer:

<input type="number" />

The field is usually displayed with small arrows to change the value (figure below).

Number entry field

Number entry field

You can customize the way the field works with the following attributes:

  • min: minimum allowed value.

  • max: maximum allowed value.

  • step: this is the movement "step". If you specify a step of 2, the field will only accept 2 by 2 values (for example, 0, 2, 4, 6, etc.).

A cursor

Therangetype is used to select a number with a cursor (also called a slider), as in the figure below:

<input type="range" />

A cursor through the range type

A cursor through the range type

You can use themin,maxandstepattributes again to restrict the available values.

Color

This field allows you to enter a color:

<input type="color" />

In practice, it is not used all that much by browsers at the present time. Don't be surprised if you only see an ordinary text field.

Date

There are various types of date selection fields:

  • date: for the date (05/08/1985, for example);

  • time: for the time (13:37, for example);

  • week: for the week;

  • month: for the month;

  • datetime: for the date and time (with time zone management);

  • datetime-localfor the date and time (no time zone management).

Example:

<input type="date" />

As you can see, there's a wide choice!
At present, few browsers support this type of field except for Opera.

Search

You can create a search field like this:

<input type="search" />

The browser then decides how to display the search field. It can thus add a small magnifying glass meaning that it's a search field and to possibly store the last searches performed by the visitor.

Options

HTML provides a whole slew of options that can be used in your form. These are items that require the visitor to choose from a list of possibilities. We're going to review:

  • checkboxes;

  • options fields;

  • drop-down lists.

Checkboxes

How do you create a checkbox? Nothing could be easier! We're going to use the<input />tag, this time specifying the typecheckbox:

<input type="checkbox" name="choice" />

Add a<label>in the right position, and there you are!

<form method="post" action="target.php">
<p>
Check the foods you like to eat:<br />
<input type="checkbox" name="fries" id="fries" /> <label for="fries">Fries</label><br />
<input type="checkbox" name="hamburger" id="hamburger" /> <label for="hamburger">Hamburger</label><br />
<input type="checkbox" name="spinach" id="spinach" /> <label for="spinach">Spinach</label><br />
<input type="checkbox" name="oysters" id="oysters" /> <label for="oysters">Oysters</label>
</p>
</form>

And here's the result in the figure below.

CheckboxesCheckboxes

Don't forget to give a different name to each checkbox. Later on, this will allow you to identify the ones checked by the visitor.

Finally, remember that you can have a box checked as default using the attributechecked:

<input type="checkbox" name="choice" checked />

All attributes normally have a value. In this case, however, adding a value is not required: the presence of the attribute is enough to make the computer understand that the box has to be checked.
If this bothers you, remember that you can assign any value to the attribute (some webmasters sometimes writechecked="checked"but it's a bit redundant!). The box will be checked irrespectively.

Options fields

The options fields allow you to choose one (and only one) option from a list of possibilities. They look somewhat like checkboxes but there is a slight additional difficulty: they have to be organized as groups. Although the options in the same group have the same (name), each option has to have a different (value).

The tag to be used is always a<input />, this time with the valueradiofor the attributetype.

The example below will make this clearer:

<form method="post" action="target.php">
<p>
Please indicate your age group:<br />
<input type="radio" name="age" value="moins15" id="moins15" /> <label for="moins15">Less than 15 years old</label><br />
<input type="radio" name="age" value="medium15-25" id="medium15-25" /> <label for="medium15-25">15-25 years old</label><br />
<input type="radio" name="age" value="medium25-40" id="medium25-40" /> <label for="medium25-40">25-40 years old</label><br />
<input type="radio" name="age" value="plus40" id="plus40" /> <label for="plus40">Even older than that?!</label>
</p>
</form>

Which gives result shown in the next figure.

Radio buttonsRadio buttons

Why did you put the same name for each option? Just so that the browser knows which "group" the button belongs to.
Try removing thenameattributes and you'll see that you can then select all the options. However, this is not what we want, which is why we "link" them together by giving them the same name.

You'll notice that this time we've chosen aniddifferent fromname. Indeed, as the values fornameare the same, we couldn't have differentiated the ids (and you know full well that anidhas to be unique!). That's why we've chosen to give theidthe same value asvalue.

If you have two different options fields, you have to give a uniquenameto each group, like this:

<form method="post" action="target.php">
<p>
Please indicate your age group:<br />
<input type="radio" name="age" value="less15" id="less15" /> <label for="less15">Less than 15 years old</label><br />
<input type="radio" name="age" value="medium15-25" id="medium15-25" /> <label for="medium15-25">15-25 years old</label><br />
<input type="radio" name="age" value="medium25-40" id="medium25-40" /> <label for="medium25-40">25-40 years old</label><br />
<input type="radio" name="age" value="plus40" id="plus40" /> <label for="plus40">Even older than that?!</label>
</p>
<p>
Which continent do you live on?<br />
<input type="radio" name="continent" value="europe" id="europe" /> <label for="europe">Europe</label><br />
<input type="radio" name="continent" value="africa" id="africa" /> <label for="africa">Africa</label><br />
<input type="radio" name="continent" value="asia" id="asia" /> <label for="asia">Asia</label><br />
<input type="radio" name="continent" value="america" id="america" /> <label for="america">America</label><br />
<input type="radio" name="continent" value="australia" id="australia" /> <label for="australia">Australia</label>
</p>
</form>

Thecheckedattribute is again available for selecting a default value.

Drop-down lists

Drop-down lists are another elegant way of selecting an option from several possibilities. They work in a slightly different way. We going to use the<select> </select>tag which specifies the start and end of the drop-down list. We add thenameattribute to the tag to give a name to the list.

Then, inside the<select> </select>tag, we're going to insert several<option> </option>tags (one for each possible choice). We add avalueattribute to each of them to identify what the visitor has chosen.

Here's an example of use:

<form method="post" action="target.php">
<p>
<label for="country">What country do you live in?</label><br />
<select name="country" id="country">
<option value="unitedstates">United States</option>
<option value="canada">Canada</option>
<option value="unitedkingdom">United Kingdom</option>
<option value="france">France</option>
<option value="spain">Spain</option>
<option value="italy">Italy</option>
<option value="china">China</option>
<option value="japan">Japan</option>
</select>
</p>
</form>

The result obtained is shown in the figure below.

A drop-down list

If you want an option to be selected as default, this time use the attributeselected:

<option value="canada" selected>Canada</option>

You can also group your options using the tag<optgroup> </optgroup>. In our example, why don't you separate country according to their continent?

<form method="post" action="target.php">
<p>
<label for="country">What country do you live in?</label><br />
<select name="country" id="country">
<optgroup label="Europe">
<option value="unitedkingdom">United Kingdom</option>
<option value="france">France</option>
<option value="spain">Spain</option>
<option value="italy">Italy</option>
</optgroup>
<optgroup label="America">
<option value="unitedstates">United States</option>
<option value="canada">Canada</option>
</optgroup>
<optgroup label="Asia">
<option value="china">China</option>
<option value="japan">Japan</option>
</optgroup>
</select>
</p>
</form>

The result obtained is shown in the figure below.

Options are grouped by continent

Groups cannot be selected. So we can't choose "Europe" in our example: only country names can be selected.

Finalizing and submitting the form

We're almost there. It only remains for us to decorate our form with few final features (such as confirmation) and then add the form submit button.

Grouping fields

If your form has grown and has a lot of fields, it may be useful to group them within several tags<fieldset>. Each<fieldset>can contain a caption with the tag<legend>. Look at this example:

<form method="post" action="target.php">
<fieldset>
<legend>Your contact details</legend> <!-- Fieldset title -->
<label for="lastname">What's your last name?</label></br>
<input type="text" name="lastname" id="lastname" /></br>
<label for="firstname">What's your first name?</label></br>
<input type="text" name="firstname" id="firstname" /></br>
<label for="email">What's your email address?</label></br>
<input type="email" name="email" id="email" /></br>
</fieldset>
<fieldset>
<legend>Your wish</legend> <!-- Fieldset title -->
<p>
Make a wish that you would like to come true:</br>
<input type="radio" name="wish" value="rich" id="rich" /> <label for="rich">Be rich</label></br>
<input type="radio" name="wish" value="famous" id="famous" /> <label for="famous">Be famous</label></br>
<input type="radio" name="wish" value="intelligent" id="intelligent" /> <label for="intelligent">Be <strong>even more</strong> intelligent</label></br>
<input type="radio" name="wish" value="other" id="other" /> <label for="other">Other...</label></br>
</p>
<p>
<label for="specs">If "Other", please specify:</label></br>
<textarea name="specs" id="specs" cols="40" rows="4"></textarea>
</p>
</fieldset>
</form>

The result obtained is shown in the figure below.

The fields are grouped

Automatically selecting a field

You can automatically place the cursor in one of the fields in your form using the attributeautofocus. Once the visitor loads the page, the cursor appears in this field.

For example, to place the cursor as default in the fieldname:

<input type="text" name="firstname" id="firstname" autofocus />

Making a field mandatory

You can make a field mandatory by assigning it the attributerequired.

<input type="text" name="firstname" id="firstname" required />

The browser will then tell the visitor, if the field is empty when the form is submitted, that they are required to fill it in.

Older browsers that don't recognize this attribute, submit the form contents without a check. For these browsers, you'll need to supplement the tests, for example, with JavaScript scripts.

CSS provides pseudo-formats for changing the style of items that are (:required) and (:invalid). Don't forget either that you have the pseudo-format:focusto change the appearance of a control when the cursor is within.

:required
{
background-color: red;
}

The submit button

So all we have to do now is create the submit button. Here again, the<input />tag comes to our rescue It's available in four versions:

  • type="submit": the form main submit button. This is the one you'll use most often. The visitor will be taken to the page specified in the form'sactionattribute

  • type="reset": reset the form.

  • type="image": equivalent of thesubmitbutton, displayed this time as an image. Add thesrcattribute to specify the image URL.

  • type="button": generic button, which will have no effect (as default). In general, this button is handled in JavaScript to perform actions in the page. We won't use it here.

You can change the text displayed inside buttons using the attributevalue.

To create a submit button, we thus write for example:

<input type="submit" value="Submit" />

Which gives result shown in the next figure.

A submit buttonA submit button

When you click the "Submit" button, the form then takes you to the page specified in the attributeaction. Remember, we imagined a fictitious page:target.php.

The problem is that you can't create this page in HTML only. You have to learn a new language, such as PHP, to be able to "retrieve" the entered information and decide what to do with it. As it happens, I'm also writing a course on the PHP language for those who might be interested! This course will be published soon.

Some websites provide services called "Mailform" which send you an e-mail when one of your visitors has filled in the form. Although this eliminates the need to learn a new language, it's not very convenient: you have to either pay, or put up with advertising... and you don't have many possibilities for customizing data processing.

Summing up

  • A form is an interactive area in the page, where your visitors can enter information.

  • A form is circumscribed using the<form>tag to which two attributes have to be added:method(data submitting method) andaction(page to which the visitor is redirected after submitting the form and which processes the information).

  • Many of the form's items can be inserted using the tag<input />. The value of itstypeattribute specifies the field type to be inserted:

    • text: text field;

    • password: text field for password;

    • tel: phone number;

    • checkbox: checkbox;

    • ...

  • The<label>tag is used to enter a label. It is associated with a form field using theforattribute, which must have the same value as the form fieldid.

  • You can make a field mandatory using therequiredattribute, ensure that it is selected as default usingautofocus, and specify an indication in the field usingplaceholder

  • To retrieve what visitors have entered, the HTML language is not sufficient. You have to use a "server" language such as PHP... If you want to go further, you're going to have to learn a new language!

Video and audio

Since the arrival of Youtube and Dailymotion, watching videos on websites has now become commonplace. It has to be said that the arrival of broadband has helped democratize videos on the Web.

Up to now, however, no HTML tags were provided for managing video. You had to use a plugin like Flash instead. Even today, Flash is by far the most widely used way of watching videos on Youtube, Dailymotion, Vimeo and elsewhere. But using a plugin has a number of drawbacks: it makes you dependant on those who manage the plugin (in this case, the company Adobe, which owns Flash), you can't always control its operation, there are occasional security flaws, etc. In the end, it's pretty cumbersome.

For this reason, two new standard tags were created in HTML5: <video> and <audio>!

Audio and video formats

When I talked to you about images and the <img /> tag, I started by quickly reviewing the various image formats (JPEG, PNG, GIF, etc.). For video and audio, I'll do the same... but it's more complicated.

In fact, the way videos work is so complex that you could do a whole course on this subject! But as we're talking about HTML here, we're not going to spend our next few nights exploring the intricacies of video encoding. I'm thus going to simplify things and only tell you what you need to know.

Audio formats

To play music or any sound, many formats can be used. Most of them are compressed (such as are JPEG, PNG and GIF images), which reduces their storage size:

  • MP3: you cannot possibly not have heard of it! It's one of the oldest and also one of the most compatible formats (all devices can read MP3), so it's still widely used today.

  • AAC: mainly used by Apple with iTunes, and is a good quality format. IPods, iPhones and iPads can read it with no problem.

  • OGG: the Ogg Vorbis format is widely used in the freeware world, and in particular in Linux. This format has the advantage of being free, in other words, not protected by any patent.

  • WAV (uncompressed format): this format should be avoided wherever possible as the file it uses is very large. It's roughly the equivalent of Bitmap (BMP) for audio.

No browser handles all these formats at once. Compatibility with MP3 and OGG is the main thing to be borne in mind:

Browser

MP3

OGG

Internet Explorer

Yes

-

Chrome

Yes

Yes

Firefox

-

Yes

Safari

Yes

-

Opera

-

Yes

There's no "ideal" format recognized by all browsers?

Well, no! Fortunately, we can provide browsers with various formats and leave them to select the one they can read.

Video formats

Video storage is much more complex. We need three items:

  • A container format: this is a bit like a box used to contain the two items below. The container type can generally be recognized from the file extension: AVI, MP4, MKV, etc.

  • An audio codec: this is the video sound format, which is usually compressed. We've just seen them and we're going to use the same: MP3, AAC, OGG, etc.

  • A video codec: this is the format that compresses the images. This is where things get tough as these formats are complex and aren't always free to use. The main ones to know about for the Web are:

    • H.264: which is now one of the most powerful, widely used formats... but is not 100% free. In fact, it can be used for free in some cases (such as video streaming on a personal website), but the legal uncertainty around it makes it risky to use on a large scale.

    • Ogg Theora: a codec which is free and not protected by copyright, but less powerful than H.264. Although it's well known in Linux, you have to install software to play it in Windows..

    • WebM: another more recent, free codec not protected by copyright. It's provided by Google and is now H.264's main competitor.

Which video codecs are compatible with which browsers? There again, you'll see that it's a bit of a mess:

Browser

H.264

Ogg Theora

WebM

Internet Explorer

Yes

-

Yes

Chrome

-

Yes

Yes

Firefox

-

Yes

Yes

Safari

Yes

-

-

Opera

Yes

Yes

Yes

There again, no format really stands out. It's advisable to provide each video in several formats to make it playable on as many browsers as possible.

To convert a video into these formats, I recommend the excellent free Miro Video Converter program that you can download through the web code below.

Just drag and drop your video into the program's window and select the desired output format. This will allow you to create several versions of your video!

Inserting an audio item

The <audio> tag we're going to find out about is recognized by all newer browsers, including Internet Explorer from version 9 (IE9) onwards.

In theory, you only need one tag to play a sound on your page:

<audio src="song.mp3"></audio>

In practice, it's a bit more complicated than that.
If you test this code... you won't see anything! Indeed, the browser will only download general information about the file (called metadata) but nothing will happen in particular.

You can add the following attributes to the tag:

  • controls: to add the "Play" and "Pause" buttons and the scroll bar. This may seem essential, and you may be wondering why it's not provided as default, but some websites prefer to create their own buttons themselves and control playback using JavaScript.

  • width: to change the width of the audio playback tool.

  • loop: music will be played in a loop.

  • autoplay: music will be played when the page is loaded. Don't overdo this. A website that plays music all by itself whenever it's loaded is generally irritating!

  • preload: specifies whether music can be preloaded when the page is loaded or not. This attribute can take the following values:

    • auto (default): the browser decides whether to preload all the music, only the metadata or nothing at all.

    • metadata: only loads the metadata (time, etc.).

    • none: no preloading. Useful if you don't want to waste bandwidth on your website.

You can't force the preloading of music, it's always the browser that decides.
Mobile browsers, for example, never preload music to save bandwidth (as the loading time is long on a mobile phone).

It'll be better with controls so let's add them!

<audio src="hype_home.mp3" controls></audio>

The appearance of the audio player varies from one browser to another. The figure below shows, for example, the audio player in Google Chrome.

The audio player in Google ChromeThe audio player in Google Chrome

Why open the tag if you're going to close immediately afterwards?

This allows you to display a message or provide a fallback solution for browsers that don't support this new tag. For example:

<audio src="hype_home.mp3" controls>Please update your browser!</audio>

Those who have a recent browser won't see this message. Older browsers, that don't understand the tag, will, however, display the text inside.

I suggest you provide a fallback solution in Flash, such as Dewplayer. You place the code for Flash between the <audio> and </audio> tags: older browsers will thus display the Flash player, while the newer ones will display the native player.

We've seen that some browsers don't support MP3. What's the solution?

You have to provide several versions of the audio file. In this case, we're going to build our tag like this:

<audio controls>
<source src="hype_home.mp3"></source>
<source src="hype_home.ogg"></source>
</audio>

The browser will automatically take the format it recognizes.

Inserting a video

The <video> tag that we're going to discover is recognized by all browsers, including Internet Explorer from version 9 (IE9).

You only need a single <video> tag to insert a video in the page:

<video src="sintel.webm"></video>

But again, you may be disappointed if you only use this code. There's no control to start the video!

Let's add a few attributes (most of them are the same as for the <audio>) tag:

  • poster: image to be displayed instead of the video until it's run. As default, the browser takes the first frame of the video, but as it's often a black frame or a frame unrepresentative of the video, I advise you to create one! You can simply do a screen capture of any moment in the video.

  • controls: to add the "Play" and "Pause" buttons and the scroll bar. This may seem essential, but some websites prefer to create their own buttons themselves and control playback using JavaScript. In our case, it will be more than enough!

  • width: to change the video width.

  • height: to change the video height.

  • loop: the video will be played in a loop.

  • autoplay: the video will be played when the page loads. There again, don't overdo this. A website that runs something all by itself whenever it's loaded is generally irritating!

  • preload: specifies whether the video can be preloaded when the page is loaded or not. This parameter can take the following values:

    • auto (default value): the browser decides whether to preload the whole video, only the metadata or nothing at all.

    • metadata: only loads the metadata (time, size, etc.).

    • none: no preloading. Useful if you want to avoid wasting bandwidth on your website.

You can't force the preloading of the video, it's always the browser that decides.

The video's proportions are always preserved. If you set a width and a height, the browser will ensure that the specified dimensions aren't exceeded, but it will keep the proportions.

Here's some code that's a bit more complete:

<video src="sintel.webm" controls poster="sintel.jpg" width="600"></video>

And here's the result in the figure below.

A video with the play options and a defined sizeA video with the play options and a defined size

Why do you open and close immediately after the tag?

The answer is the same as for the <audio> tag. It allows you to display a message or provide a fallback solution (in Flash) if the browser doesn't recognize the tag:

<video src="sintel.webm" controls poster="sintel.jpg" width="600">
It's time to update your browser!
</video>

How do you cater for all browsers since they all recognize different video formats?

You use the <source> tag inside the <video> tag to provide various formats. The browser will take the one it recognizes:

<video controls poster="sintel.jpg" width="600">
<source src="sintel.mp4" />
<source src="sintel.webm" />
<source src="sintel.ogv" />
</video>

IPhones, iPads and iPods currently only recognize the H.264 format (.mp4 file)... and only if it appears first in the list! I thus recommend that you specify the H.264 format first to ensure maximum compatibility.

How do you display the video in full screen?

It's not possible at present. In fact, there is indeed a way in Firefox but it's a bit hidden away: you have to right click on the video and select "Full Screen".

There's no way to force full screen, even in JavaScript. This is understandable, since some websites could significantly disrupt browsing by displaying videos in full screen without asking visitors whether they actually want this!

How can I protect my video, I don't want it to be able to be copied easily!

It's not possible. Tags were not designed to limit or prevent downloading. It's logical enough when you think about it: for visitors to be able to see the video, they'll have to download it anyway, one way or another!

So don't imagine you can prevent your video being downloaded using this technique.

Flash video players allow you to "protect" the content of videos, but there again, workarounds exist. Many plug-ins allow you to download videos from Youtube, for example.

Summing up

  • Inserting music or video didn't used be possible in HTML. You had to use a plugin like Flash.

  • Since HTML5, <audio> and <video> tags have been introduced and allow you to play music and video without plugins.

  • There are several audio and video formats. In particular, you should know about:

    • for audio: MP3 and Ogg Vorbis;

    • for video: H.264, Ogg Theora and WebM.

  • No format is recognized by all browsers: you have to provide music or video in various versions to satisfy all browsers.

  • You have to add the controls attribute to <audio> and <video> tags to allow visitors to start or stop the media.

  • These tags are not designed to prevent the downloading of music and video. You cannot protect you media against being copied.

Adaptive page layout with Media Queries

Do you know what webmasters implementing their website's design are most concerned about? Their visitors' screen resolution. Indeed so: the space or number of pixels wide various from one screen to another.

This information is important when you build a design: how should your website be displayed for different screen resolutions? If you have a wide screen, you may forget that some people browse with smaller screens. Not to mention the browsers of smart phones, which are even less wide.

This is where media queries come in. These are the rules to be applied to change the design of a website based on the screen's characteristics! Using this technique, we can create a design that automatically adjusts to each visitor's screen!

Implementation of media queries

Media queries are part of CSS3's new features. They are not new properties but rather rules that can be applied under certain conditions. Specifically, you'll be able to say, "If the visitor's screen's resolution is less than a certain value, then apply the following CSS properties". This allows you to change the website's appearance under certain conditions: You can increase the text size, change the background color, position your menu differently with certain resolutions, etc.
Contrary to what one might think, media queries are not just about screen resolutions. You can change your website's appearance based on other criteria such as screen type (smart phone, TV, projector, etc.), the number of colors, the screen orientation (portrait or landscape), etc. There are a great number of possibilities!

Media queries work in all browsers, including Internet Explorer as of version 9 (IE9) onwards.

Applying a media query

Media queries are thus rules that specify when CSS properties have to be applied. There are two ways to use them:

  • by loading a different .css stylesheet based on the rule (e.g. "If the resolution is less than 1280px wide, load the small_resolution.css") file;

  • by writing the rule directly in the usual .css file (e.g. "If the resolution is less than 1280px wide, load the CSS properties below").

Loading a different stylesheet

You remember the <link /> tag which, in our HTML code, loaded a .css file?

<link rel="stylesheet" href="style.css" />

You can add a media attribute, in which we're going to write the rule to be applied for the file to be loaded. This is known as making a media query. For example:

<link rel="stylesheet" media="screen and (max-width: 1280px)" href="small_resolution.css" />

In the end, your HTML code may provide several CSS files: one as default (which is loaded in all cases) and one or two others which are only charged in addition if the corresponding rule applies.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" /> <!-- For everyone -->
<link rel="stylesheet" media="screen and (max-width: 1280px)" href="small_resolution.css" /> <!-- For those who have a resolution lower than 1280px -->
<title>Media queries</title>
</head>
Loading rules directly in the style sheet

Another technique, which I personally prefer for practical reasons, is to write these rules in the same CSS file as usual.
In this case, we write the rule in the .css file like this:

@media screen and (max-width: 1280px)
{
/* Write your CSS properties here ici */
}

The available rules

There are many rules for building media queries. I'll only mention the main ones here:

  • color: color management (in bits/pixel).

  • height: display field height (window).

  • width: display field width (window).

  • device-height: device height.

  • device-width: device width.

  • orientation: device orientation (portrait or landscape).

  • media: output screen type. A few of the possible values:

    • screen: "conventional" screen;

    • handheld: mobile device;

    • print: printing;

    • tv: television;

    • projection: projector;

    • all: all types of screens.

The prefix min- or max- can be added in front of most of these rules. min-width thus means "Minimum width" and max-height means "Maximum height", etc.
The difference between width and device-width can primarily be seen in mobile browsers for smart phones, as we'll see later.

The rules can be combined using the following words:

  • only: "only";

  • and: "and";

  • not: "not";

Here are a few examples of media queries to help you understand the principle.

/* On screens with a maximum window width of 1280px */
@media screen and (max-width: 1280px)
/* On all screen types with a window width of between 1024px and 1280px */
@media all and (min-width: 1024px) and (max-width: 1280px)
/* On TVs */
@media tv
/* On all vertically oriented types of screens */
@media all and (orientation: portrait)

Older browsers, including IE6, IE7 and IE8, don't know media queries but are able to interpret the start of the rule (they can read @media screen, for example). They will thus read the following CSS properties even if they are not affected by the rule! To avoid this, one trick is to use the only keyword that these old versions don't know: 
"@media only screen" does not cause a bug on older browsers.

Testing media queries

Media queries are mostly used to adapt the website design to different screen widths.

Let's do a very simple test: we're going to change the text size and color if the window is more or less than 1024 pixels wide. For this test, I'm going to use the second method is to write the rule directly in the same .css file as usual:

/* Paragraphs blue as default */
p
{
color: blue;
}
/* New rules if the window width is smaller than 1024px */
@media screen and (max-width: 1024px)
{
p
{
color: red;
background-color: black;
font-size: 1.2em;
}
}

In our CSS, we first asked for the paragraph text to be written in blue. So far nothing new. However, we have added a media query that applies to all screens not wider than 1024px. Inside, we applied CSS rules to paragraphs to write them bigger and in red.

Result: the page appearance varies according to the window size (figure below)! 

The page appearance varies according to the window size

Practical use of media queries in the design

Well, changing the text color is nice but it doesn't really add much. However, using media queries to change your website's appearance depending on screen resolution is immediately much more useful. You'll see that you can do whatever you want!

For this example, I suggest you reuse the design we created for the Zozor website (figure below).

The website built during the practical exampleThe website built during the practical example

Although the website is suitable for most screen resolutions, you have to "scroll" it to the right to see the whole page when the screen is smaller than 1024 px. The website is not very convenient to see on a small screen.

I suggest you use media queries to change the website's appearance for resolutions less than 1024 px wide. We're going to make the following changes:

  • the browsing menu at the top right will be arranged height-wise rather than width-wise, and the links will be written in smaller characters;

  • the banner with the San Francisco bridge (the Golden Gate) Will be deleted as it takes up a lot of space and doesn't provide much information;

  • the "About the author" <aside> block will be placed under the article (rather than next to it), and its content will be reorganized (the Zozor photo be have a floating position).

You could of course make a lot of other changes: change the color, the footer arrangement, etc. But this will already be more than enough to give us some practice with media queries.

We're going to work directly inside thestyle.css file we produced during the practical example and add a few media queries instructions to adjust the design. I suggest you download the practical example files if you haven't done so already.

Download the practical example

The page

The page width is currently set to 900 px and the content is centered:

#bloc_page
{
width: 900px;
margin: auto;
}

I suggest you add the following media query rule after these lines:

@media all and (max-width: 1024px)
{
#bloc_page
{
width: auto;
}
}

This rule means: "if the window width does not exceed 1024 px then run the following CSS rules for all screen types".

The CSS rules in question are very simple; there's actually only one rule: the page wide is adjusted automatically (rather than given a fixed width of 900 px). The page will then take up all the available space in the window. This avoids the appearance of horizontal scrollbars with low resolutions.

auto is the default value of the width property. As default, the blocks have an automatic width (they take up all the available space). This value "overwrites" the 900px value we set a few lines above: so this restores the block's default behaviour.

The browsing menu

We want the browsing menu to take up less space on smaller resolution screens. Rather than giving it a fixed size, we're going to restore its original automatic flexible size. Each menu item is written underneath the previous one: for this purpose, we'll convert the bullets into block tags rather than inline-block.

Finally, the text will be written smaller and the border at the bottom of the links will be removed when hovering, as it's less suitable with such a screen arrangement.

@media all and (max-width: 1024px)
{
nav
{
width: auto;
text-align: left;
}
nav li
{
display: block;
padding-left: 4px;
}
nav a
{
font-size: 1.1em;
}
nav a:hover
{
border-bottom: 0;
}
}

The banner

To remove the banner, nothing could be simpler: we use the display property assigning it with the value none. If the window is too small, it may be preferable to hide the banner completely:

@media all and (max-width: 1024px)
{
#banner_image
{
display: none;
}
}

The "About the author" block

Rather than placing this block on the right of the article, we're going to position it underneath. This type of "top-down" arrangement is more suitable for small screens.

We'll slightly readjust the position of the items slightly, inside the block: in particular, the photo of Zozor will be placed in a floating position on the right.

@media all and (max-width: 1024px)
{
article, aside
{
width: auto;
display: block;
margin-bottom: 15px;
}
#arrow
{
display: none;
}
#zozor_picture img
{
width: 110px;
float: right;
margin-left: 15px;
}
aside p:last-child
{
text-align: center;
}
}

What's the meaning of aside p:last-child?

It's an advanced selector we haven't used so far. aside p means "All paragraphs inside the tag <aside>". :last-child targets only the last paragraph in the aside block (which contains the links to Facebook and Twitter), so as to center the images. Of course, you could have assigned a class or an id to this paragraph to target it directly, but I didn't want to change the HTML code.

The result

The page will now be completely reorganized when the window is 1024 px wide or less. You can see the results in the figure below, which speaks for itself!

The same website, shown differently according to screen width

The same website, shown differently according to screen width

Media queries and mobile browsers

As you probably know, the screens of smart phones are much narrower than our usual computer screens (they're only a few hundred pixels wide). To adapt to this, mobile browsers display the website by "zooming out" to allow the whole page to be seen. The simulated display area is called the viewport: it's the width of the mobile phone's browser window.

With media queries, if, in CSS, you target the screen with max-width on a mobile phone, it will compare the width you specify against the width of its viewport. The problem is that the viewport changes according to the mobile browser used!

Browser

Default viewport width

Opera Mobile

850 pixels

iPhone Safari

980 pixels

Android

800 pixels

Windows Phone 7

1024 pixels

An iPhone behaves as if the window were 980 px wide, while an Android behaves as if the window were 800 px wide!

To target smart phones, it may be better, rather than using max-width, to use max-device-width: this is the device's width. Mobile devices are not more than 480 px wide, so we can target mobile browsers only, using this media query:

@media all and (max-device-width: 480px)
{
/* Your CSS rules for your mobile phones here */
}

Why not target mobile phones using the handheld media rule?

I can see that you're following: very good! Indeed, we could theoretically target mobile screens using the handheld media rule... Unfortunately, no mobile browser except Opera mobile recognizes handheld. They all behave as if they were normal screens (screen). So you can't really use handheld for mobile phones.

You can change the mobile browser's viewport width with a meta tag to be inserted in the document header (<head>):

<meta name="viewport" content="width=320" />

You can use this tag to change the way your page content is organized on mobile phones. To obtain readable render without zooming, you can set the viewport to the same width as the screen:

<meta name="viewport" content="width=device-width" />

Summing up

  • Media queries allow the loading of various CSS styles based on certain settings.

  • There are a large number of settings allowed by media queries: number of colors, screen resolution, orientation, etc. In practice, they are mostly used to change the website's appearance for different screen resolutions.

  • You create a media query with the @media directive followed by the screen type and one or more conditions (such as the maximum screen width). The following CSS style will be enabled only if the conditions are met.

  • Mobile browsers simulate a screen width: this is called the viewport.

  • Smart phones can be targeted by a rule based on the actual number of pixels displayed on the screen: max-device-width.

Digging in

As this course comes to its end, it might be tempting to think that we've seen everything. Seen everything? You didn't really believe that, did you? Come now, you've still hundreds of things to find out about, whether in HTML, CSS, or in related technologies (PHP, JavaScript, etc.).

This chapter aims to give you a few tips to complete your apprenticeship. So don't be sad, there are plenty of other things left to discover!

From the website to the web application (JavaScript, AJAX, etc.)

JavaScript is a language that has been around for some years now and is frequently used on the Web in addition to HTML and CSS. It's probably one of the first languages you'll want to learn now that you know something about HTML and CSS.

What is JavaScript used for? Can't we do everything with HTML and CSS?

You can already do a lot of things in HTML and CSS, but when you want to make your page more interactive, a language like JavaScript is essential.

Here are some examples of what JavaScript can be used for:

  • We'll use it most often to change CSS properties without having to reload the page. For example, you point to a picture and the background of your website changes color (you can't do this with a :hover as it involves two different tags. That's one limit of CSS).

  • It can also be used to edit the HTML source code without having to reload the page while the visitor is viewing the page.

  • It also allows you to display dialogue boxes on the visitor's screen...

  • ... or change the window size.

JavaScript is a language that is closer to programming languages like C, C++, Python, Ruby, etc. HTML and CSS, however, are more description languages: they describe how the page should appear, but they don't give direct instructions to the computer ("do this, do that, etc."), like JavaScript does.

JavaScript has nothing to do with the Java language. Only the names are similar.

JavaScript is commonly used today for AJAX (Asynchronous JavaScript And XML). This technique is used to change any part of the web page viewed by the visitor by exchanging data with the server. This gives the impression that the pages are more dynamic and responsive. The visitor does not need to systematically reload the whole page.

As browsers are increasingly effective in processing JavaScript, pages that use JavaScript are more responsive. Some websites now being built literally become web applications, the equivalent of software but available as websites!
One notable example: Google Docs, Google's office suite available on the Web (figure below).

The Google Docs spreadsheetThe Google Docs spreadsheet

You'll learn more about Javascript in other courses!

HTML5 related technologies (Canvas, SVG, Web Sockets, etc.)

The W3C doesn't just work on the HTML and CSS languages. While these are certainly the best known, the W3C also seeks to identify other technologies supplementing HTML and CSS. There are a large number of these and they are also often confused with HTML5.

In fact, HTML5 has become a widely used term that refers to technologies other than HTML. When someone speaks of "HTML5" today, they may also be referring to other items that go beyond the strict framework of HTML.

Here's a list of the new technologies introduced in parallel with HTML5 (note that some are not really "new" but they are back on the scene):

  • Canvas: allows you to draw in the web page, inside the HTML <canvas> tag. You can draw shapes (triangles, circles, etc.) and also add and do things with images, apply graphic filters, etc. In the end, all this now allows us to develop real games and graphical applications directly in web pages!

  • SVG: allows you to create vector graphics in web pages. Unlike canvas, these graphics can be enlarged to infinity (the vector principle). The Inkscape programis known for being able to produce SVG drawings.

  • Drag & Drop: allows you to "drag and drop" objects into the web page, in the same way as you can drag and drop files onto your desktop. Gmail uses it to allow you to easily add attachments to an email.

  • File API: provides access to files stored on the visitor's computer (with their permission). In particular, you'll use it in combination with Drag & Drop.

  • Geolocalization: to locate the visitor and offer services related to the place where their located (e.g. scheduled times of nearby cinemas). Although the location is not always very accurate, it can identify a visitor to within a few kilometers (with their permission).

  • Web Storage: is used to store a lot of information on the visitor's computer. It's a more powerful alternative to the usual cookies. Information is organized on a hierarchical basis, like in a database.

  • Appcache: tells the browser to put into cache certain files, that it won't seek to systematically download any more. Very useful for creating web applications that can even work "offline" (disconnected).

  • Web Sockets: allows faster exchanges, in real time, between the visitor's browser and the server that manages the website (this is a kind of improved AJAX). It's may be the future of web applications, which will become as responsive as real programs.

  • WebGL: allows the introduction of 3D in web pages, using the OpenGL 3D standard (figure below). 3D scenes are directly managed by the graphics card.

Most of these technologies are used with JavaScript. They are thus new features that can be used in JavaScript.

A 3D web application using WebGLA 3D web application using WebGL

As you can see, there are new worlds for you to discover! Once you know enough JavaScript, you'll be able to go further in managing your website... and even turn it into a real application!

Dynamic websites (PHP, JEE, ASP. NET, etc.)

The languages we're going to discuss here are also programming languages. Like JavaScript? Yes, but with one important difference: JavaScript runs on your visitor's computer, while the languages we're going to see run on the "server" that contains your website.

What difference does it make whether the program runs on the visitor's computer or on the server?

The differences are considerable. Firstly, in terms of power, a server will more often than not be faster than your visitor's computer, and so be able to perform more complex calculations. You also have more control on the server side than in JavaScript... But JavaScript remains irreplaceable as there are some things that you can only do on the "visitor" side.

Server languages generate the web page when the visitor arrives on your website (figure below). Each visitor can thus get a web page personalized according to their needs!

Data exchange with a serverData exchange with a server

The languages are thus not used for the same things, but they complement each other. If you combine HTML + CSS + JavaScript + PHP, for example, you can handle AJAX (data exchange between the page and the server), perform calculations, store information in databases... in short, build real dynamic websites!

There are many "server-side" languages. Let's mention a few:

  • PHP: one of the most well known. This easy to use, powerful language is used in particular by Facebook. I'm also writing a PHP tutorial!

  • JEE (Java): this Java extension is widely used in the professional world to build dynamic, powerful and robust websites. It's a bit more complex than PHP to get started with.

  • ASP .NET (C#): this is the Microsoft's language and is quite similar to JEE. It's used in combination with other Microsoft technologies (Windows Server, etc.). It uses the powerful .NET framework, which is the developer's genuine Swiss Army knife, and which provides many features.

  • Django (Python): this is an extension of the Python language that allows you to build dynamic websites quickly and easily. It is known for generating ready to use administration interfaces.

  • Ruby on Rails (Ruby): an extension of the Ruby language, quite similar to Django, which allows you to build dynamic websites easily and with greater flexibility.

Knowing one of these languages is essential if you want to process the results of HTML forms! Remember the <form> tag: I'd explained to you how to create forms, but not how to retrieve the information entered by your visitors. You must have a server language, like PHP, to retrieve and process such data!

Ultimately, these languages allow you to make your wildest dreams come true on your website:

  • forums;

  • newsletter;

  • visitor counter;

  • automated news system;

  • member management;

  • web games (strategy games, virtual animal breeding, etc.)

  • ...

It's essential to know HTML and CSS before learning a server language like PHP! 
Read on to find out more... but don't forget to complete your last quizz and assessment before that! You will find their links in Part 4 of the course outline


Comments