HTML and CSS

Intermediates

HTML Form & HTTP Request

An HTML Form (Web Form) allows a web user to interact with the server. An HTML form contains input elements (or fields, controls, widgets), such as text fields, checkboxes, and buttons. These input fields allow web users to supply data (called request parameters or query string) to the web server. Over at the web server, a server-side program collects these data and returns a dynamic response based on the inputs submitted.

An HTML form is enclosed within <form>...</form> tags. The attribute action provides the URL for which this form is to be submitted. The attribute method specifies the HTTP method (GET or POST) to be used for submission.

There are 2 input elements in this form:

<input type="text">: a text field for users to enter data.

<input type="password">: for password entry - displayed as * on the screen.

We use a <label> to label each of the <input>. You can either match the for attribute of the <label> to the id attribute of the <input> element to be labeled (as in the first <input>); or wrap the <input> inside the <label> (as in the second <input>). The <label> improves the usability for the mouse-user. When you click on the <label>, the labeled <input> element is selected.

<input type="reset">: The reset button, which clear all the input fields.

The value attribute of the button appears as the label of the button.

When the user submit the form, the browser collects the request parameters from the input elements, in the form of name=value pairs. The name corresponds to the name attribute of the <input> elements; the value corresponds to the text entered. In this example, there are two sets of name=value pairs - username=xxx and password=yyy. The request parameters are joined together via a & sign, i.e., username=xxx&password=yyy, to form a so-called query string. The query string is then append behind the action URL via a ? sign, i.e., submit.php?username=xxx&password=yyy. As URL does not accept special characters, they are encoded in the form of %hh (called URL encode), where hh is the ASCII code in hexadecimal, e.g., ~ is encoded as %7e; ^ as %5e. Space can be encoded in %20 or + for simplicity.

Try submitting the form. Observe the request parameters in the submitted URL. You are expect to get an error 404, as you have yet to write the server-side processing program "submit.php".

The server-side program receives the query string; URL decodes the special characters; and performs operations based on these parameters (e.g., query the database). It then returns an appropriate response to the client. I will not cover server side programming in this article. Read the respective server-side programming techniques such as PHP, Java Servlet, JSP, and etc.

We can group a set of related input fields into <fieldset> and provide a descriptive <legend>. The input fields will be enclosed in a box, with the legend shown on the top border.

In <input type="text"> (Line ?), attribute required is added to request browser to validate that this field is not empty. Browser will display an error message and will not submit the form if this field is empty.

Radio buttons (can check at most one button) are marked by <input type="radio">'s. Each <input> has its associated <label>. We typically use the same name attribute for all the buttons, and assign different value for each button. You can place the required on any one of the button to request the browser to validate that one is checked.

Checkboxes (can check zero or more boxes) are marked by <input type="checkbox">. We added checked attribute on one of the box, to set its initial state. Attribute checked is applicable to checkboxes, as well as radio buttons.

Pull-Down menu is defined via a <select> element, with each item marked by an <option>. We set the common name in the name attribute of the <select>, and different value in <option>. We can also mark the selected element via attribute selected in the <option>.

Textarea (multi-line input text field) is marked via <textarea>...</textarea>. The attribute placeholder is applicable to all input text fields, which shows a hint in the input field before the user enters a value. The attribute maxlength request browser to limit the length of the input.

Try submitting the form. Observe the request parameters in the submitted URL.

EXAMPLE 3 ("HtmlFormEx3.html"): HTML5 Controls

[TODO]

The HTML Form's Syntax

The <form> Element and its action Attribute

An HTML form is enclosed by a <form> element. The attribute action specifies the URL for which this web form is to be submitted, which default to the current page. The attribute method specifies the HTTP method used for submission, i.e., GET or POST (with default of GET).

Labeling <Input> Fields: The <label> Element

Each <input> field is typically associated with a <label> to label the input field. You can bind the <input> element it labels by matching the for attribute of the <label> element with the id attribute of the element; or place the <input> element within the <label>...</label> element (without the for attribute), as follows:

Label does not have any visual effect. But if you click on the label, the associated input field will be selected.

Input Fields

Input fields are marked by <input>, <textarea>, <select> and <button>. The <input> is a standalone element, with attribute type to specify its sub-types (e.g., type="text" and type="checkbox"). On the other hand, <textarea>, <select>, <button> are container elements.

Element

Control

Description

Example

<input type="text">

Single-line Text Input Field

For text input. The default type for <input>.

<input type="password">

Single-line Password Input Field

Password shown in asterisk (*).

<textarea>...</textarea>

Multi-line Text Input Field

For text input.

<input type="checkbox">

Checkbox

Can check zero or more boxes

<input type="radio">

Radio Button

Can check at most 1 button

<select>...</select>
<optgroup>...</optgroup>
<option>...</option>

Drop-down List

<input type="submit">

Submit Button

Click to submit the form to the server

<input type="reset">

Reset Button

Reset all fields to their default value

<input type="image">

Image Button

Use an image as submit button

<input type="button">

Generic Button

<input type="file">

File Chooser

<input type="hidden">

Hidden Field

<button>...</button>

Button

Same as <input type="button">

<input type="email"> (HTML5)

Email Address

Can be validated.

<input type="url"> (HTML5)

URL

Can be Validated.

<input type="number"> (HTML5)

Numeric value

You can use attributes min|max to specify the min and max values; and step to specify the step size (default of 1).
Many browsers add a spin button (with up/down arrow) to the right corner of the box

<input type="range"> (HTML5)

Numeric value

You can use attribute min|max to specify the min and max values.
Many browsers use a slider for range.

<input type="color"> (HTML5)

Color

Browser may pop-up a color chooser.

<input type="date|time|datetime|month|week"> (HTML5)

Date and Time

Browser may provide a drop-down calendar. Poorly supported now.

<input type="tel"> (HTML5)

Phone number

No validation as phone numbers vary across countries.

<input type="search"> (HTML5)

Search keywords

Search Box for entering search keywords. No validation.

<datalist> (HTML5)

Define a list of pre-defined options for <input>

<output> (HTML5)

Define the result of a computation

<keygen> (HTML5)

Define a public-private key pair field for authentication of the form

HTML5 Web-Form New Features

Adding Hints for Input Text Fields: Attribute placeholder

You can use the placeholder attribute to provide hints for the input, which will be shown in light-grey watermark and disappears when the user clicks on the field. For example,

Placeholders should be used to clear up the ambiguity by providing examples, instead of another label.

Set the Initially-Focus Element: Attribute autofocus

You can add the attribute autofocus (with no value) to the element that is supposed to receive the focus when the page is loaded.

Input Field Validation

HTML5 implemented client-side validation on input fields.

required: You can add attribute required (with no value) to signal to the browser that non-empty input is required for that field. The browser will pop-up an error message if empty value is submitted for that field.

novalidate, formnovalidate: To turn off the validation (e.g., to test the server-side validation), add attribute novalidate to the <form> element; or attribute formnovalidate to the submit button.

pattern="regex": You can also match the input value against a regular expression (regex) via attribute pattern="regex".

Auto-complete with <datalist>

[TODO]

Progress Bar <progress> and Meter <meter>

The progress bar <progress> shows how far a task has progressed. Meter <meter> show the current value (in a known range) or percentage.

HTTP GET/POST Request

The Request Parameter (Name-Value Pair)

Each input field is associated with a name-value pair, which will be submitted to the server, as part of the HTTP request. The name is identified by the name attribute of the input field; while the value could be the user input (for text fields), or identified by the value attribute (for checkboxes, radio buttons and list options).

When the form is submitted, the name-value pair will be sent to the server, as a so-called request parameter.

The Query String (All Name-Value Pairs)

When a user fills in the form and click the submit button, the request parameter from all the input fields, in the form of name=value pair, will be send to the server as part of the request. The processing URL is specified in the action attribute of the <form>. For a GET request, the request parameters are append behind the URL separated by a '?'. The name=value pairs are separated by an '&'. Since the URL cannot accept special characters (such as blank and '~'), they will be encoded in the form of %hh, where hh is the ASCII code of the special character. e.g., '~' as %7E; blank as %20 or '+'. This is known as URL encoding.

For example, suppose that the action URL is http://www.example.com/test/submit.php, with request parameters username=peter, password=1234, gender=m, and comment=testing 1 2 3, the resultant GET request URL is:

Take note that the password are not encrypted, although it does not appear on the screen.

GET vs. POST Request Methods

For GET, the query string is appended behind the action URL. For POST, the query string is sent in the request body, and does not show up in the URL. POST is generally preferred as it can send more data, and does not mess up the URL.

How the Server Processes the Request Parameters?

The server-side program receives the query string; URL decodes the special characters; and performs operations based on these parameters (e.g., query the database). It then returns an appropriate response to the client. I will not cover server side programming in this article. Read the respective server-side programming techniques such as PHP, Java Servlet, JSP, and etc.

[TODO] Simple example on PHP

Color

Color theme is the most important factor affecting the appearance of your web pages. I am NOT an expert on colors, but these are what I understood.

216 Browser-Safe Colors

Not too long ago, the computer monitors can display only 256 colors (aka palettes). Hence, web designers created the so-called 216 browser-safe colors, which can be shown correctly and quite consistently on all the computer displays. Today, most of the computer monitor can display 24-bit true colors, is it still relevant?

Most computer monitors today are at least capable of display 16K (or 16384) colors. You could put values of #00, #08, #10, #18,..., #F0, #F8, #FF on each of the RGB triplets.

Default Color Names

Again, the HTML/CSS provides default color names, such as red, green, blue, grey, and etc. Again, the color value for these color names are obtained numerically. As a result, these colors are really really ugly. Don't use them!

Rules-of-Thumb of Using Color

Stay monochrome (black on white). Use an additional color for highlighting headings, links, and etc.

Use color with restraint. There is no reasons to use more than 4 colors.

Use a lightly shaded background.

Use color in a box.

Fonts & Typography

The choice font faces are probably the one of the most important factor affecting the appearance of your web pages. These are the main categories of fonts:

Serif: Serif fonts come with little horizontal tails, to guide you in reading a long (horizontal) line of texts. Serif fonts are used in printed materials such as newspaper for easy reading. For example,

Fonts look good in prints may not look good on screen. You are recommended to use sans-serif fonts for the web pages, which are displayed on computer screen.

This table shows you some of the common fonts.

Serif

San-serif (Body)

San-serif (Heading)

Monospace

Times New Roman

Segoe UI (Segoe)

Trebuchet MS (uc)

Lucida Console

Georgia

Tahoma

Trebuchet MS (lc)

Courier New

Palatino

Helvetica

Segoe UI

Consolas

Arial

Verdana

Courier

Arial Narrow

Arial Black

Lucida Sans Unicode

Century Gothic

Calibri

Impact

In CSS, fonts are specified in property font-family. You can use generic family names such as "serif", "sans-serif", "monospace", and "cursive". The actual font used depends on the individual browser's settings.

Which Font Should I Use?

This is a million-dollar question. Some sans-serif font is nice when use in body text (normal weight, small font size, may need italics), others are suitable for use in heading (bold, bigger font size, uppercase). Some fonts are nice in lowercase, but not too nice in uppercase. Some nice fonts are not available in all the browsers (Windows 2000/XP/Vista/7, Mac, Linux?). For web publishing, you need to select one that most of your readers can enjoy.

You probably want to use different fonts for body texts and headings:

Headings: use bigger font-size (and most probably in bold face) to draw readers' attention, and help to organize the ideas. There are usually a few levels of headings. Set the letter-spacing for headings.

Body Texts: comprises the main bulk of your writing. Use smaller but legible font-size. Use italics or bold to emphasize certain terms or phrases.

These are my choices of fonts for web publishing (i.e., screen fonts, NOT printing fonts).

For Program Codes - Use Monospace or Fixed-width Font

Consolas (Windows - designed for Visual Studio 2005) is my first choice, but may not be generally available. Zero(0)/oh(O), one(1)/eye(I)/else(l) are clearly differentiated. It has a nice good italic style 1234567890.

Lucida Console (Windows) is another choice. Zero(0)/oh(O) are not clearly differentiated. One(1)/eye(I)/else(l) are better. The italic style 1234567890 is poor. The bold face is broader than normal. It has a bigger size compared with Courier New.

Others (Cursive, Artistic)

Century Gothic (Window, Mac(?)): This is quite a very interesting and artistic font. The font width of each letter varies tremendously. The bold face seems to be more regular. How are the italics?. unusual question mark?!

The em unit is a relative measurement and is a multiple to the current font-size. The exception is when em is used to set the font-size property itself, in this case, it refers to the font-size of the parent element. In other words, for the first three elements in the above example, the font-size are auto×1.5, for the last three elements, they are 0.8×1.5, which are the same for <h1>, <h2>, and <p>.

Which is the Best Font Measurement? em, px?

The px (pixels) unit offers reliable control and consistent scaling across devices and display resolutions. The em unit scales consistently as well and has the added advantage of allowing the end-user to adjust the text size through browser's settings. However, to use em unit, you need to figure out what is the parent element the current element is relative to.

Font File Types

.eot (Embedded Open Type): work only in IE.

.ttf (True Type) and .otf (Open Type): used by the system, word processor and most of the browsers.

.woff (Web Open Font Format): new font format design specifically for the web. They are basically compressed version of .ttf or .otf. They are smaller in file size and hence, can be downloaded faster.

You can use multiple src to load different font files (e.g., one each for .ttf, .otf, .woff).

You can now use the font in your style as usual, via the font-family property:

body {
font-family: xxx, ....;
}

Suggestions

"Don't use too many fonts. It looks ugly. It is distracting. It makes you reader work too hard. Give them a break!"... I read this paragraph somewhere.

Use a font for the body. Use another font for heading. Use a monospace font for program codes and listing.

These are the conservative fonts, available on most systems (Windows, Macs), that won't go wrong:

Times (Serif)

Arial, Helvetica (Sans-Serif)

Courier (monospace)

These are the more exiting fonts, available on most systems:

Verdana, Tahoma, (Sans-Serif)

Georgia (Serif)

Comic Sans MS, Impact, Arial Black

Images

Graphics File Formats

BMP (Windows BitMaP)

Uncompressed, large but fast (no need to decompress).

Small images used for wallpaper, background, and Windows objects.

GIF (Graphic Interchange Format)

GIF has two versions: GIF87a, GIF89a.

Lossless compressed using LZW (as in PKZip, WinZip), but supports only 256 colors.

Palette-based, limited to 256 color palettes. No good for full-color 24-bit real photo, best used for line art, logo, cartoon and so on.

Progressive GIFs to get a sense of the image.

Transparent GIFs (with see-thru background): Of the 256 colors palettes, one of palette can be chosen as the background. The background palette can be set to "transparent" for a see-thru effect.

Animated GIFs: Sequence of GIF images shown repeatedly. Much simpler and faster than server-push or other animation technology.

There was a patent issues on using GIF, resulted in a new PNG (Portable Network Graphic) format and the burn-all-gif campaign. The original LZW patent already lapsed in 2003-2004, and the GIF can be used freely now (??).

PNG (Portable Network Graphics)

Lossless.

More efficient compression algorithm than GIF (using LZW).

No animation.

Support transparency.

Can be used for computer-generated image, as well as photos (but not as good as JPEG).

SVG (Scalable Vector Graphics)

Why Can't JPEG Support Transparency?

The primary reason is that JPEG compression is lossy. That is, a image pixel of a certain RGB value, may not recover its original RGB value exactly (but close) after compression and decompression. Suppose a certain (Rx,Gx,Bx) triplet of the original uncompressed image is picked to be transparent. This triplet is compressed into JPEG format for storage and transmission. It has to be decompressed for display. However, due to the lossy compression algorithm, you may not get back the original (Rx,Gx,Bx) value (but somewhere very close). Thus, the pixel will not be shown as transparent. On the other hand, other pixels with triplet of nearby value such as (Ry,Gy,By) must be decompressed into (Rx,Gx,Bx), and be shown as transparent.

Rule of thumb

Use JPEG for 24-bit color photos. Use GIF/PNG for 256-color line arts, cartoons, and drawing (all the drawings in my website are saved in GIF/PNG).

Use GIF for animation.

Use GIF/PNG for transparency.

72 dpi (or possibly 120 dpi) for web images is sufficient for screen display. This is because a typical display console supports about 60-96 dpi. Take not that quality printing (e.g., printing photos) requires a much higher dpi.

Using Images

Make it "light"! Do not embed a 5MB image. You don't need 600-dpi resolution for displaying image on the computer screen [you need 300dpi for good printing and 600dpi for high-quality printing]. 72 to 96 dpi, or in extreme case - 120 dpi, is good enough for screen display. Use a image editing software to scale down the image resolution before putting on your web page.

Don't let the browser resize your image, even worst, ask the browser to reduce the size of your image (this is a waster of the precious network bandwidth, computer processing power, and generates more heats). Do it yourself!

[This is difficult!] Tune your images' color tone (via the alpha channel), to bend in with the color theme of your website.

Styling Image using CSS

Making Image Float

[TODO]

Absolute Position

[TODO]

Image Sprite

[TODO]

Image Opacity

[TODO]

Styling Your Website

Writing Efficient CSS Selectors

Responsive Web Design (RWD)

Responsive Web Design (RWD) lets you change the layout of a page based on the browser's window width, so as to present the page in a readable manner on all devices (from smartphones to tablets to desktops) without creating multiple versions for your website.

Viewport

Mobile browsers render web pages in a virtual window called viewport, which is usually wider than the screen width, so that they do not need to squeeze the page into the screen. Users can pan or zoom to see the different parts of the web page.

Modern mobile browsers support a <meta> tag to control the viewport, which is typically set as follows for responsive web design:

<meta name="viewport" content="width=device-width, initial-scale=1">

The property width sets the viewport's width (to the device-width in the above example); initial-scale sets the zoom level when the page is first loaded (to no zoom in the above example).

Alternatively, you can also use the CSS @viewport at-rule (instead of the HTML <meta> element) as follows:

@viewport {
width: device-width;
initial-scale: 1;
}

Media Queries

CSS3 include so-called media queries, to let you conditionally assign styles based on the browser's window width and height (browser, not device, you can test RWD by shrinking the browser's window on desktops). In other words, you can use media queries to conditionally assign different styles for smartphones, tablets and desktops.

The strategies are:

Stack columns on small devices for multi-column design: Multi-column design looks good on desktops (or possibly tablets in landscape), but not on smartphones. You can stack on columns on top of each other on small devices, by conditionally removing the float property of the columns.

Flexible (Relative) page width: Set the width of your content divisions to auto or 100%, instead of using absolute pixel numbers.

Shrink margin, padding, and white spaces for small devices.

Shrink the font size, especially for headings on small devices.

Collapse the navigation menu-bar items for small devices into a pull-down menu.

Hide or Collapse less important contents for small devices.

Use smaller resolution images and videos for small devices.

It is common to create 3 (or more) sets of media queries for different devices - smartphone (width <= 480), tablets (481 <= width <= 768), and desktop (width >= 769). Some designers choose to use 1024 instead of 768.

Media Queries in HTML <link> Element

You can apply media query in HTML <link> element to load different style sheets for different window width, e.g.,

How It Works?

You can apply less built-in functions (such as lighten() and floor()) and arithmetic operations (such as +, -, * and /) to variables.

On chrome, you need to run you web page through a web server, as less.js makes Ajax call to server. But, you can run on Firefox without a web server and see the generated CSS output via Firebug or Developer Tools.

We typically keep all the variables in another less file (say "variables.less"); and include the file via "@import variables.less;".

Example 2: Using Mixins

Mixins are similar to variables, but it can include a list of properties. It could take arguments too.

Create the following less script called "LessExMixin.less", under the "less" sub-directory:

Color Operation Functions

method: optional with default of absolute. Set to relative for the adjustment to be relative to the current value.

The commonly-used color Operation Functions are:

saturate(color, percent[, method]) and desaturate(color, percent[, method]): Increase/Decrease the saturation value of the color in the HSL color space, by the absolute/relative amount in percent of 0-100%.

lighten(color, percent[, method]) and darken(color, percent[, method]): Increase/Decrease the brightness (lightness) value of the color in the HSL color space, by the absolute/relative amount in percent of (0-100%).

fadeout(color, percent[, method]) and fadein(color, percent[, method]): Increase/Decrease the transparency (alpha channel) of a color, by the absolute/relative amount in percent of 0-100%.

fade(color, percent): Set the absolute transparency (alpha channel) of a color, in percent of 0-100%.

greyscale(color): Convert to grey scale, same as desaturate(color, 100%).

spin(color, angle): Rotate the hue by the given angle (a positive or negative value in degree).

Conditionals or Guards

You can apply conditionals (or guards) using keyword when. For examples,