HTML and CSS Tutorial - The Basics
HTML and CSS Tutorial - The Basics
header, content, footer. Assign an id to <div> that is unique (e.g., "header", "footer". Assign a common classname 7. CSS Basics
to sections (non-unique) that share the same style (e.g., "entry", "side-note"). Write the CSS id-selectors and class- 7.1 CSS Syntax
7.2 Inline, Internal and External Styles
selectors (e.g., #header tag-name,... #footer tag-name,... #menu tag-name,...) for common tags (such as
7.3 Inheritance
h1, h2, h3, p, a:link, a:visited, a:hover, a:active), in each of the <div>'s. Basically, what I am saying is to
7.4 Resolving Conflicting Rules
design each of the sections by itself - a "divide and conquer" strategy.
7.5 How to Use CSS for Styling HTML Document?
b. Create sub-classes for common styles, such as layout out tables and images and special effects (e.g., ".highlight", 7.6 Types of CSS Selectors
".underline", ".center"). They could be used in <div> and <span>. 7.7 Style Properties
c. There are many good and free CSS templates (or web templates) available online (just google "CSS Templates" or 7.8 Color Properties
"Web templates"). Pick one that meets your taste to model after. You can also look at the CSS of any website that 7.9 Length Measurements
you find interesting. Be aware of the Intellectual Property Right, do not use any images or graphics unless they are in 7.10 Box Model - Margin, Border, Padding and Conte
the public domain. It is extremely easy to create one yourself with an imaging tool, such as PhotoShop, Element, 7.11 Font Properties
Illustrator or even Paint. 7.12 Text Properties
Alternatively, use CSS framework such as BootStrap and pick your favorite design from the samples. 7.13 Background Properties
7.14 List Properties
6. Write your HTML pages. You may need to modify the CSS as you go along. The most challenging thing for an OMO web
7.15 Table Properties
author is that he has to be concerned about both the contents and appearances at the same time, and can lose focus at
7.16 Image Properties
times!
8. More HTML
7. Repeat the previous steps until you are happy with your page's look and feel, layout, and most importantly, the contents -
8.1 Image Maps
try not to create yet another insignificant website.
8.2 Frames
8.3 Embedding Programs
8.4 HTML Global Attributes
2. Introduction to HTML 8.5 HEAD Section's Tags
9. More CSS
What is HTML (HyperText Markup Language)? 9.1 Positioning the HTML Block-Level Elements
1. HTML is the language for publishing web pages on the WWW (World-Wide Web, or World-Wide Wait?). 9.2 Floating an Element Left or Right
2. HTML is a Document Description Language (aka Document Markup Language). HTML is NOT a programming language like 9.3 Other Miscellaneous Properties
C/C++/C#/Java, which is used to implement programming algorithm.
3. An HTML document is a text document, and it is human-readable.
1 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
HTML Draft (October1991): Tim Bernes-Lee (of CERN) proposed the early HTML for sharing of document in a hypertext system.
HTML 2.0 (November 1995): Published as IETF RFC 1866.
HTML 3.2 (January 1997): Published as W3C Recommendation.
HTML 4.0 (December 1997): Published as W3C Recommendation, with strict, transitional and frameset.
HTML 4.01 (December 1999): Touched up HTML 4.0. The supposedly final HTML specification published by W3C.
XHTML 1.0 (January 2000): W3C considered HTML 4.01 as the final release for HTML, and moved on to develop XHTML 1.0 with stricter rules and syntaxes, followed by
XHTML 2.0. XHTML 2.0, although theoretically elegant, is impractical as it is not backward compatible with HTML4/XHTML1.0. A rebel group called WHATWG (Web
Hypertext Application Technology Working Group) continued to work on extending HTML with more features in a backward-compatible manner. In 2004, WHATWG
released HTML5. By 2007, HTML5 has captured the attention of the developers. W3C decided to abandon the XHTML 2.0 and embraced the HTML5.
HTML 5 (October 2014): Published as W3C Recommendation.
Today, the prevailing specifications are HTML5 (2014) (@ http://www.w3.org/TR/2014/REC-html5-20141028/). Nonetheless, the most interesting thing about standards is
that nobody really follows them strictly. Every browser (Chrome, Firefox, Opera, Safari and Internet Explorer) has its own variations and support the standards to various
extents.
Markup Tags
HTML uses markup tags, such as <p> (for Paragraph), <h1> to <h6> (for Heading Level 1 to 6), <img> (for Image), <a> (for Anchor or Hyperlink), to markup a document.
HTML markup tags perform these functions:
1. Layout the documents, e.g., <p> (layout as a paragraph), <h1> to <h6> (layout as heading level 1 to 6), <br> (perform a line break), <hr> (draw a horizontal rule),
<table> (tabulating data), <ol> (layout an ordered list).
2. Provide link (called hyperlink) to another HTML document, via the <a> (Anchor tag). These hyperlinks, a distinct feature in HTML, greatly help the users in navigating
the web and enrich the users' experience. Hyperlinks make the HTML popular.
3. Embed images, audios, videos, programs (in JavaScript, VBScript, Applet, Flash, or MS ActiveX control), and objects within an HTML document. HTML is multimedia!
The hypertext document may contain texts, images, audios, videos, and even programs.
Nowadays, HTML should be used solely to markup the contents, while its companion technology known as CSS (Cascading Style Sheet) be used for defining the
presentation of the document, so as to separate the content and presentation.
These are the common pitfalls in older HTML documents and you should avoid:
Do not specify "appearance" properties, such as foreground and background color, text alignment, font face, font size, border, margin and padding, in the HTML
document. Use an external CSS instead to set the appearance and presentation. Presentation-related tags (such as <font>, <center>) and attributes (such as align,
bgcolor, link, vlink, alink) have been deprecated in HTML 4, in favor of CSS.
Do not use nested tables or frame for formatting the document, use <div> and <span>, or HTML5 new tags such as <header>, <footer>, and <section>.
Let's go thru some HTML examples and the syntaxes. Do not attempt to start designing your website until you understand the CSS.
3. HTML By Examples
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Basic HTML Document Layout</title>
6 </head>
7 <body>
8 <h1>My First Web Page</h1>
9 <hr>
10 <p>This is my <strong>first</strong> web page written in HTML.</p>
11 <h3>HTML</h3>
12 <p>HTML uses <em>markup tag</em> to <em>markup</em> a document.</p>
13 </body>
14 </html>
Use a programming text editor to enter the above HTML codes and save as "MyFirstWebPage.html".
2 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Open the file in a browser (such as Firefox, Internet Explorer, Chrome, Safari, Opera) by double-clicking the file; or
Web Page
drag and drop the file into the browser; or through the browser's "File" menu ⇒ "Open File..." ⇒ "Browse..." and
select the file.
This is my first web page
written in HTML.
How it Works?
1. An HTML document begins with a Document-Type declaration <!DOCTYPE html> (Line 1) to identify itself as HTML
an HTML document to the browser.
HTML uses markup tag to
2. The HTML content is contained within a pair of <html>...</html> tags. You can specify the default language
markup a document.
of your document via attribute lang="en" (for English) in the <html> opening tag.
3. There are two sections in the document: HEAD and BODY, marked by <head>...</head> and <body>...</body> tags, respectively.
4. In the HEAD section:
a. The <meta charset="utf-8"> element (Line 4) specifies the character encoding scheme of the document. Today, virtually all (English) HTML documents are
encoded using the UTF-8 character encoding scheme, which is compatible with ASCII code for English alphabets and allow you to include other Unicode
characters (such as Chinese, Japanese and Korean) efficiently.
When saving your file, you need to choose "UTF-8 encoding" in the "save-as" dialog menu.
b. The <title>...</title> element (Line 5) provides a descriptive title to the page. The browser displays the title on the title-bar of the tab/window.
5. In the BODY section:
a. The <h1>...</h1> container tags (Line 8) mark the enclosing texts as Level-1 Heading. There are six levels of heading in HTML, from <h1>...</h1> (largest)
to <h6>...</h6>. Line 11 uses a <h3>...</h3> (Heading Level-3).
b. The <hr> standalone element (Line 9), which does not enclose text content, draws a horizontal rule (or line).
c. The <p>...</p> container tags (Line 10 and 12) mark the enclosing texts as a paragraph. <p>...</p> is the most frequently-used tag in HTML.
d. The <strong>...<strong> tags (nested under the <p>...</p> in Line 10) specify "strong emphasis" for its content - rendered in bold by the browser.
Similarly, the nested <em>...</em> tags (Line 12) specify "emphasis" - rendered in italic by the browser.
Note: For Mac's Safari, you may need to enable "Show Page Source" via "Preferences" ⇒ Advanced ⇒ "Show Develop menu in menu bar".
I shall illustrate the use of these elements through the following examples.
3 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
How it Works?
1. The <!-- ... --> (in Line 3) is an HTML comment. Comments are ignored by the browsers, Lists and
but are important to provide explanations to the readers as well as the author.
2. There are two types of lists in HTML: ordered list and unordered list. An ordered list is marked Hyperlinks
by <ol>...</ol> and displayed with numbers; while a unordered list is marked by
<ul>...</ul> and displayed with bullets. Each of the list items is marked by <li>...</li>. There are two types of lists in
HTML:
3. You can nest a list inside another list, by placing the complete inner list definition inside a list
item <li>...</li> of the outer list. 1. Ordered List.
4. Hyperlink is marked by <a> standalone tag. The attribute href="url" provides the 2. Unordered List.
destination URL of the link.
This is a nested unordered list of
links:
3.3 Example 3: Tables and Images
1 <!DOCTYPE html>
2 <html lang="en">
3 <!-- Save as "HtmlEg3.html" -->
4 <head>
5 <meta charset="utf-8">
6 <title>Table and Images</title>
7 <style>
8 table { /* table */
9 border: 1px solid black;
10 border-spacing: 5px;
11 border-collapse: separate;
12 }
13 th, td { /* cells */
14 border: 1px solid #aaa;
15 padding: 5px 10px;
16 }
17 </style>
18 </head>
19 <body>
20 <h1>Table and Images</h1>
21 <table>
22 <caption>Logo of Languages</caption>
23 <tr>
24 <th>S/No</th>
25 <th>Language</th>
26 <th>Logo</th>
27 </tr>
28 <tr>
29 <td>1.</td>
30 <td>HTML5</td>
31 <td><img src="../images/HTML5_Logo_128.png" alt="HTML Logo" height="64" width="64"></td>
32 </tr>
33 <tr>
34 <td>2.</td>
35 <td>CSS3</td>
36 <td><img src="../images/css3.png" alt="CSS Logo" height="64" width="64"></td>
37 </tr>
38 <tr>
39 <td>3.</td>
40 <td>JavaScript</td>
41 <td><img src="../images/js3.png" alt="JavaScript Logo" height="64" width="64"></td>
42 </tr>
43 </table>
44 </body>
4 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
45 </html>
How it Works?
1. A table, consisting of rows of cells, can be marked via <table>...</table>. Table and
2. A HTML table is row-centric. You shall first mark a row via <tr>...</tr>, and then mark the cells of the row
via <th>...</th> (for header cell) or <td>...</td> (for details cell). Images
3. The <caption>...</caption> element can be nested under <table> to provide a caption for the table.
Logo of Languages
4. Image is marked via the <img> tag. The mandatory attribute src specifies the path (or url) for the image source
file; alt gives the alternative text if the image cannot be displayed. I used relative path in the src, where ".."
S/No Language Logo
denotes the parent directory. You need to find some images, store them and figure out your own relative path.
5. The <img>'s optional attributes width and height specify the width and height of the image displayed area. 1. HTML5
They are used here to resize the images for consistent display.
6. In the HEAD section, I added some so-called style rules under the <style>...</style> tags, so as to nicely
display the table. You could ignore the styles now, which will be covered later in the CSS section.
External CSS and JavaScript are often used in an HTML document. Line 6 includes an external CSS file; and line 7 includes an external JavaScript file.
4. HTML Basics
HTML Tags
An HTML opening tag is enclosed by a pair of angle brackets in the form of <tag-name> (e.g., <p>, <title>), which is associated with a matching closing tag
</tag-name> having a leading forward slash, (e.g., </p>, </title>). The tag-name shall be in lowercase.
Tag's Attributes
Attributes, in the form of name="value" pairs can be included in the opening tag to provide additional information about the element.
Example 1: In <html lang="en">, the attribute lang="en" specifies the natural language for this document.
Example 2: In <meta charset="utf-8">, the attribute charset="utf-8" specifies the character encoding scheme.
The attribute "src" specifies the source-URL of the image; "alt" specifies an alternate text, if the image cannot be displayed; "width" and "height" specify the width and
5 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Some of the attributes are mandatory (e.g., the "src" and "alt" attributes of the <img> tag); while some are optional (e.g., the "width" and "height" attributes of the
<img> tag, which are used by browser to reserve space for the image and resizing the image; but browser can figure out the width and height after the image is loaded).
Attributes are written in the form of name="value" pairs. The value should be enclosed in single or double quotes for XHTML/XML compliance (although HTML5 does
not enforce it).
HTML Elements
An HTML element consists of the opening and closing tags, and the content in between, e.g., <p>A for apple</p>, <strong>Caution!</strong>.
2. Standalone Element: A standalone element does not enclose content but is used to achieve a certain effect, e.g., <hr> is used to draw a horizontal rule; <br> to
introduce a manual line-break; and <img> for embedding an external image.
In XHTML, you need to end a standalone element with a trailing '/' in the opening tag. For examples:
<br />
<hr />
<img src="logo.gif" />
Alternatively, you can also close a standalone element with a matching closing tag. This is cumbersome but consistent in syntax to the container element. For
example,
<br></br>
<hr></hr>
<img src="logo.gif"></img>
HTML5 no longer enforces this rule. Today, most developers omit the trailing '/' for simplicity, e.g., <br>, <hr>.
A valid HTML document exhibits a tree structure (called DOM or Document Object Model), with the element <html> as the root element of the document tree, with two
child elements: <head> and <body>.
produces the following single-line output on screen with words separated by a single space:
See how the extra white spaces, tabs and line-breaks are ignored by the browser.
You need to use the paragraph tag <p>...</p> to lay out a paragraph; or insert a manual line-break tag <br> to break into a new line. In other words, you control
the new-lines via the mark-up tags. The <p>...</p> leaves additional space after the paragraph; while <br> does not.
To get multiple whitespace, use a special code sequence (which stands for non-breaking space). For example,
<p>This is a
paragraph.</p>
<p>Another paragraph<br>with a line-break in between and more spaces before this.</p>
This is a paragraph.
Another paragraph
with a line-break in between and more spaces before this.
6 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
The <html> Element and its Child Elements <head> and <body>
An HTML document has the following skeleton:
<!DOCTYPE html>
<html>
<head>...</head>
<body>...</body>
</html>
The HEAD Section and the <title>, <meta>, <link>, <script> Elements
The HEAD section may contains these elements: <title>, <meta>, <link>, <script>, <base>.
The <title>...</title> container element encloses the title for the page. You should use a meaningful title because:
The title shows up at the title-bar of the browser window.
The title shows up in bookmarks and history lists (the URL is stored if there is no title).
Titles are used by search engines' to index your page.
The <meta> element contains meta-information, for use by browser to properly render the document. For example, <meta charset="utf-8"> specifies the character
encoding scheme for the document.
You can use a <link> element to add an external CSS Style Sheet (and <style>...</style> element for internal styles):
You can use a <script>...</style> element to define programming scripts. For example, to add an external JavaScript file:
<script src="filename.js"></script>
Note: HTML4/XHTML1 require an additional attribute language="JavaScript" in the <script> tag. Also take note that the closing </script> tag is needed, even
though there is no content within <script> and </script>. We usually place the JavaScript after CSS, as the JavaScript may use the CSS.
The <body> tag has the following optional presentation attributes. All of these presentation attributes are concerned about the appearance instead of the content, and
have been deprecated in HTML 4 in favor of style sheet. However, many older textbooks present them in Chapter 1. Hence, I shall list them here for completeness. BUT do
not use these attributes. I shall describe how to control the appearance of <body> using CSS very soon.
text="color": color of body text.
bgcolor="color": background color.
background="url": URL of an image to be used as the background.
link="color": color of un-visited links.
vlink="color": color of visited links.
alink="color": color of active (clicked) links.
For example:
<html>
<body text="blue" bgcolor="lightblue" link="green" vlink="red" alink="yellow">
<p>Hello</p>
<a href="http://www.google.com">Google</a>
</body>
</html>
The foreground color (of the texts) is "blue", on background color of "lightblue". You can set different colors for the three types of links via attributes "link" (for
un-visited links), "vlink" (for visited links), and "alink" (for active link - the "alink" color shows up when you click on the link).
7 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Comments are also useful in temporarily disable a certain part of the HTML codes during development.
1. Block Elements: A block element (such as <p>, <h1> to <h6> and <div>) starts on a new line, takes the full width, and ends with a new line. It is rectangular in
shape with a line-break before and after the element.
2. Inline Elements (or Character Elements): An inline element (such as <em>, <strong>, <code> and <span>) takes up as much space as it needs. It does not
force a line-break before and after the element, although it can span a few lines.
In brief, a block element is always rectangular in shape, while an inline element spans a continuous run of characters.
Paragraph <p>...</p>
Function: When the browser reads a <p> tag, it breaks to a new line, and skips some white spaces. For example,
Older HTML documents often omit the closing </p>, which is a bad practice, not recommended, and disallowed in XML/XHTML.
To create an empty paragraph, you need to use <p> </p> which encloses a non-breaking space. This is because browsers typically ignore <p></p>.
<p>This
paragraph<br>with a
line-break
in between.</p>
This paragraph
with a line-break in between.
<h1>Heading</h1>
<hr>
<p>Discussion begins here...</p>
Without the <pre> tag, the entire program will be shown in one single line.
8 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Quote <blockquote>...</blockquote>
Function: Mark out a block of quote. Browsers typically indent the entire block to the right. For example,
<div class="header">
......
</div>
<div class="content">
......
</div>
<div class="footer">
......
</div>
This is less than desirable, as <div> elements do not provide semantic information about the sections.
HTML5 added many semantic block elements, which extends <div>, to structure a document. They are: <header>, <footer>, <nav>, <section>, <article>, <summary>,
<details>, <aside>, <figure>, <figcaption>, and <main>. You are encouraged to replace some of the <div>'s with these more descriptive semantic elements.
Nonetheless, it is important to note that NOT all browsers (notably older IE versions) support these new elements.
The <section>...</section> element can be used to markup each content section in a document (such as each chapter of the book). (HTML5 does not define a
<content> element!) For example,
<header>
......
</header>
<section>
......
</section>
<section>
......
</section>
<footer>
......
</footer>
Ar ticle <article>...</article>
The <article>...</article> element is used to markup an independent and self-contained article such as a news story, which could have its own header, footer and
content sections.
<figure>
<img src="...." alt="...">
<figcaption>......</figcaption>
</figure>
You can remove the alt attribute from the <img> tag, as <figcaption> typically provides better description.
9 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
In a web page, figures are typically float alongside the text. For example, you can apply the following style rules to <figure> and <figcaption> to float the figure to the
left:
figure {
float: left;
margin-left: 0px;
margin-top: 0px;
margin-right: 20px;
margin-bottom: 0px;
}
figcaption {
font-size: small;
font-style: italic;
margin-bottom: 5px;
}
Sidebar <aside>...</aside>
The <aside> element can be used to introduce related contents, typically formatted in a floating sidebar alongside the main texts.
<nav>
<h1>....</h1>
<ul>
<li><a href="...">......</a></li>
<li><a href="...">......</a></li>
......
</ul>
</nav>
You can place the <nav> under an <aside> if the navigation menu is to be shown in a sidebar (or side panel).
However, the browser supports for these two tags are poor, and it is best to avoid them.
<header>......</header>
<main>
<article>......</article>
<section>......</section>
<section>......</section>
<article>.......</article>
</main>
<footer>......</footer>
The <main> element shall NOT be a descendant of an <article>, <aside>, <footer>, <header>, or <nav> tags.
Providing Backward-Compatibility
Chrome, Firefox, Safari and Opera have no problems with these HTML5 tags, so does IE (Internet Explorer) 10. However, IE 9 and IE 8 may have problems rendering these
tags.
article, aside, figure, figcaption, footer, header, main, nav, section, summary {
display: block;
}
10 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
2. Use the HTML5 Shiv (@ https://github.com/afarkas/html5shiv), which contains JavaScript to create these elements.
3. Use Modernizr (@ http://modernizr.com/) - a JavaScript library that detects HTML5/CSS3 features.
The commonly-used tags are: <strong> (displayed in bold), <em> (displayed in italics), and <code> (use monospace font for programming codes).
Example:
Lorem “curly quoted”, consectetur adipisicing elit, sed do citation incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis sample exercitation
ullamco laboris nisi ut code ex ea keyboard consequat. Duis aute irure dolor in reprehenderit in velit esse cillum dolore eu fugiat nulla pariatur. Excepteur insert
occaecat delete non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
For example,
Lorem abbr dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor HTML ut labore et dolore magna aliqua.
The title="tooltip-text" attribute is actually applicable to almost all of the HTML tags (e.g., <p>, <h1> to <h6>, <img>).
However, theHTML5 restores the <b>, <i>, <small>, <sup>, <sub>, <u> tags. The <big>, <tt> remains unsupported.
11 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
<u>...</u> underline
<big>...</big> large font
<small>...</small> small font
<sup>...</sup> superscript
<sub>...</sub> subscript
<tt>...</tt> teletype (typewriter, in monospace font)
Span <span>...</span>
Similar to its block-level counterpart <div>, <span> elements are extensively used in the modern web pages to mark out a run of texts, primarily for applying style.
DateTime <time>
For marking up date, time, or datetime.
You need to memorize the first five which are extensively used: " ("), < (<), > (>), & (&) and ( ).
Example:
<p>This paragraph contains special character " <, > and &
and those words have
more spaces in between.</p>
This paragraph contains special character " <, > and & and those words have more spaces in between.
4.10 Lists
List-related tags are meant for marking up a list of items. HTML supports three types of lists: ordered list, unordered list and definition list.
12 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Function: An unordered list is shown with a bullet in front of each item. The <ul>...</ul> contains an unordered list. Each of items in the list is enclosed in <li>...
</li>, as follow:
<ul>
<li>list-item-1</li>
<li>list-item-2</li>
......
</ul>
Example:
You can use attribute type in <ul> tag to choose the style of the bullets:
type="disc": a black dot (default).
type="circle": an empty circle.
type="square": a filled square.
You can use attribute start="number" in the <ol> tag to specify the starting number (which default to 1).
You can use the type attribute of the <ol> tag to choose the numbering style:
type="1": numbers 1, 2, 3, ... (default)
type="a": lowercase letters a, b, c, ...
type="A": uppercase letters A, B, C, ...
type="i": lowercase Roman numerals i, ii, iii, iv, ...
type="I": uppercase Roman numerals I, II, III, IV, ...
Definition List <dl>...</dl>, Definition Term <dt>...</dt> and Definition Detail <dd>...</dd>
Function: <dl>...</dl> tag contains a Definition List. Each of <dt>...</dt> and <dd>...</dd> pair contains a Definition Term and the Definition Detail, as follow:
<dl>
<dt>term-1</dt>
<dd>definition-for-term-1</dd>
<dt>term-2</dt>
<dd>definition-for-term-2</dd>
......
</dl>
Example:
13 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
The "unordered list" and "ordered list" are used in most of the HTML documents. But I don't find many web pages using the "definition list".
Nested Lists
You can place a list inside another list (called nested lists), by writing a complete list definition under an <li> item of the outer list. You can nest any types of lists (ordered
list, unordered list).
Example 1:
Output of Example 1:
Example 2:
<ol>
<li>XML: Extensible Markup Language
<ol>
<li>Based on SGML</li>
<li>Maintained by W3C</li>
</ol>
</li>
<li>DOM: Document Object Model</li>
<li>SAX: Simple API for XML</li>
</ol>
Output of Example 2:
4.11 Tables
Table-related tags are meant for tabulating data. (Older HTML documents tend to use <table> for formatting the document to divide the document into
columns/sections, which should be avoided. Use style sheet for formatting instead.)
The basic unit of a table is a cell. Cells are grouped into row. Rows are grouped to form the table. This corresponds well to the "row-centric" approach in the display.
14 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
<th>...</th> and <td>...</td>: contain a header cell and a data (detail) cell respectively.
For Example:
<table>
<caption>Price List</caption>
<tr>
<th>Fruit</th>
<th>Price</th>
</tr>
<tr>
<td>Apple</td>
<td>$0.50</td>
</tr>
<tr>
<td>Orange</td>
<td>$0.65</td>
</tr>
</table>
Price List
Fruit Price
Apple $0.50
Orange $0.65
Table <table>...</table>
Function: Set up a table, consisting of rows of cells.
Three optional presentation attributes, border="n" (specifies the width of borders, in pixels), cellspacing="n" (specifies the spacing between cells, in pixels), and
cellpadding="n" (define the spacing between the content of the cell and its boundaries, in pixels), are often used in older HTML pages but now deprecated. The
now-preferred approach is to use CSS (again! but coming soon!).
Example 1:
<table>
<tr>
<td>11111</td>
<td>22222</td>
<td>33333</td>
</tr>
<tr>
<td>44444</td>
<td rowspan="2">55555</td>
<td>66666</td>
</tr>
<tr>
<td>77777</td>
<td>88888</td>
</tr>
</table>
15 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
77777 88888
Example 2:
<table>
<tr>
<td colspan="2" rowspan="2">11111</td>
<td>22222</td>
</tr>
<tr>
<td>33333</td>
</tr>
<tr>
<td>44444</td>
<td>55555</td>
<td>66666</td>
</tr>
</table>
22222
11111
33333
Table Header <thead>...</thead>, Table Body <tbody>...</tbody> and Table Footer <tfoot>...</tfoot>
Function: Used to define a header, body and footer sections for a table. Browser may duplicate the header or footer when breaking the table across multiple pages (in
print-out). They can also be used to apply styles to each of the sections.
Function: <colgroup>...</colgroup> can be used to group a set of columns, so that styles can be applied to all the columns in the group. Similarly, <col> can be used
to identify a column for applying styles.
The attribute span="numOfColumns" specifies the number of columns belonging to this <colgroup> or <col> declaration.
Example 1:
<table>
<!-- col group 1 spans 3 columns -->
<colgroup span="3" style="background-color:lightgrey"></colgroup>
<!-- col group 2 spans 1 columns -->
<colgroup span="1"></colgroup>
<tr>
<td>Col 1 is in the group</td>
<td>Col 2 is in the group</td>
<td>Col 3 is in the group</td>
<td>Col 4 is NOT in the group</td>
</tr>
<tr>
<td>Col 1 is in the group</td>
<td>Col 2 is in the group</td>
<td>Col 3 is in the group</td>
<td>Col 4 is NOT in the group</td>
</tr>
</table>
Col 1 is in the group Col 2 is in the group Col 3 is in the group Col 4 is NOT in the group
Col 1 is in the group Col 2 is in the group Col 3 is in the group Col 4 is NOT in the group
Example 2:
<table>
<!-- colgroup 1 consists of col 1 and col 2 -->
<colgroup>
<col style="background-color:lightyellow" />
<col style="background-color:white" />
</colgroup>
<!-- colgroup 2 consists of col 3 and col 4 -->
<colgroup style="background-color:lightgrey" >
<col span="2" />
</colgroup>
<tr>
16 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Col 1 in the group 1 Col 2 in the group 1 Col 3 in the group 2 Col 4 in the group 2
Col 1 in the group 1 Col 2 in the group 1 Col 3 in the group 2 Col 4 in the group 2
The anchor element <a>...</a> can perform one of these two functions:
1. It can be used to set up a hyperlink, where user can navigate to the target document by clicking the link.
2. It can also be used to set up a "named anchor point" (or bookmark) within a document, to be targeted by other hyperlinks. This function is hardly used, as we
nowadays use the id attributes as targets.
Examples:
[Note: The target attribute has been deprecated in HTML 4.01 and XHTML 1.0. But it seems to be back in HTML5.]
For example,
17 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
protocol://hostname:port/path_and_filename
http://www.w3c.org/css/index.html
http://www.mytest.com:8080/default.html
ftp://ftp.faqs.org
news:soc.culture.singapore
mailto:help@zzz.com
For example, suppose that the base URL is http://www.mytest.com/abc/index.html, the base path (excluding the filename) is http://www.mytest.com/abc/.
The relative URL "test.html" refers to http://www.mytest.com/abc/test.html.".
The relative URL "../home.html" refers to http://www.mytest.com/home.html, where the double dot ".." denotes the parent directory, and single dot "." refers
to the current directory.
Rule of Thumb: Always use relative URLs for referencing documents in the same server for portability (i.e., when you move from a test server to a production server).
Use absolute URLs only for referencing resources from a different server.
Link Checker
You can use the W3C Online Link Checker (@ http://validator.w3.org/checklink) to check all the links in your document.
For example,
4.13 Images
<img src="imageUrl"
alt="alternate-text-if-image-cannot-be-shown"
width="pixels|n%"
height="pixels|n%"
title="tooltip-text" />
Example:
Attributes:
18 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
<a href="http://abc.com/">
<img src="logo.gif" alt="logo" width="30" height="20">
</a>
<p>click the above image to visit us</p>
Image used as hyperlink anchor automatically gets a border. The color of the border is given in the link (unvisited), vlink (visited), alink (active) attributes of the
<body> tag (or the a:link, a:visited, a:hover, and a:active CSS properties - to be discussed later).
5. Introduction to CSS
However, HTML has gone out-of-control in the early years. Many markup tags and attributes were created for marking the appearance and the display styles (e.g., <font>,
<center>, align, color, bgcolor, link, alink, vlink are concerned about the appearance in font, color and alignment) rather than the meaning of the contents. These
tags flood the document and make creation and maintenance of the contents extremely difficult. Furthermore, over the years, we have engaged graphic designers to work
on the appearance and leave the content providers to focus on the contents. Hence, there is a need to separate the contents and presentation of the HTML document.
The W3C (World-Wide Web Consortium @ www.w3c.org) responded to the need of separating document's contents and presentation by introducing a Style Sheet
Language called CSS (Cascading Style Sheet) for presentation, and removing the presentation tags and attributes from HTML. CSS can be viewed as a companion of HTML.
It allows web graphic designers to spice up the web pages, so that the content providers can focus on the document contents with HTML.
CSS Specifications
W3C defines three CSS levels:
1. CSS Level 1 (December 1996): CSS1 laid the ground work and introduced the selectors and most of the properties.
2. CSS Level 2 (May 1998) and CSS Level 2.1 (Last revised on June 2011): CSS2 added new features such as targeting devices and printers, and absolute positioning.
CSS2.1 (@ http://www.w3.org/TR/CSS2/) touches up CSS2.
3. CSS Level 3: CSS3 is not a single piece of specification. As CSS grows, W3C decided to break it into modules, such as the Selectors module, the Values and Units
Modules, the Box Alignment module, and so on. Each module is then developed independently. The CSS3 Selectors module (@ http://www.w3.org/TR/selectors/)
and CSS3 Colors module (@ http://www.w3.org/TR/css3-color/) were completed in 2011. Other modules are still work-in-progress.
The word cascading means that multiple style rules can be applied to the same HTML element. The browser follows a certain cascading order in finalizing a style to format
the HTML element in a predictable fashion.
6. CSS By Examples
19 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
6 margin: 5px 15px 5px 15px; /* top right bottom left - no commas in between */
7 padding: 0;
8 background-color: #eee; /* light gray, same as #eeeeee */
9 }
10
11 /* Rule 2: Apply to <h1> to <h6> elements */
12 h1, h2, h3, h4, h5, h6 {
13 font-family: "Trebuchet MS", "Segoe UI", Helvetica, Tahoma, Arial, Verdana, sans-serif;
14 color: red;
15 font-weight: bold;
16 text-align: center;
17 }
18
19 /* Rule 3: Specifically for <h2>. Override the previous rule */
20 h2 {
21 color: blue;
22 font-style: italic;
23 }
24
25 /* Rule 4: Apply to all the <p> elements */
26 p {
27 text-align: justify;
28 color: black;
29 }
A CSS style sheet provides style rules to HTML documents. You test out the above styles, by creating an HTML document, which references the CSS via the <link>
element, as follows:
1 <!DOCTYPE html>
2 <!-- CSS Example 1. Save as "CSSEg1.html" -->
3 <html lang="en">
4 <head>
5 <meta charset="utf-8">
6 <title>Testing CSS Style Sheet</title>
7 <link href="CSSEg1.css" rel="stylesheet">
8 </head>
9 <body>
10 <h1>Test CSS Style Sheet</h1>
11 <h2>This is heading level 2</h2>
12 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
13 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
14 veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
15 commodo consequat.</p>
16 </body>
17 </html>
20 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Take note that CSS is a language with its own syntaxes. CSS syntax is totally different from HTML!
1 <!DOCTYPE html>
2 <!-- CSS Example 2. Save as "CSSEg2.html" -->
3 <html lang="en">
4 <head>
5 <meta charset="utf-8">
6 <title>Testing CSS Style Sheet</title>
7 <link href="CSSEg2.css" rel="stylesheet">
8 </head>
9 <body>
10 <div id="header">
11 <h1>Test CSS Style Sheet</h1>
12 </div>
13
14 <div id="content">
15 <h2>This is heading level 2</h2>
16 <p>Lorem ipsum dolor sit amet, <span class="new">consectetur adipiscing elit</span>, sed do eiusmod
17 tempor incididunt ut labore et dolore <span class="highlight">magna aliqua</span>. Ut enim ad minim
18 veniam, <span class="new highlight">quis nostrud exercitation</span> ullamco laboris nisi ut aliquip ex ea
19 commodo consequat.</p>
20 </div>
21
22 <div id="footer">
23 <p>This page is created with <span class="new">HTML5/CSS3</span></p>
24 </div>
25 </body>
26 </html>
How it Works?
1. In the earlier example, we use Tag-Selectors which select elements based on tagname. Besides the Tag-Selector, there are Class-Selector which selects elements based
on class attribute; and ID-selector which selects an element based on the id attribute.
2. An ID-Selector begins with a # sign, followed by an id-name, e.g., #header and #footer, which select element with id="header" and id="footer", respectively.
Since id-value is meant to be unique within an HTML document, ID-selector select at most one element.
3. A Class-Selector begins with a dot "." followed by a class-name, e.g., .new and .highlight, which select all elements with class="new" and class="highlight",
respectively. Unlike id-value that is unique, many elements can have the same class-name.
21 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
4. In the test HTML document, we partition the body into three sections, via <div>. We assign a
unique id to each <div>, i.e., <div id="header">, <div id="content"> and <div The system cannot find the file
id="footer"> to semantically identify their contents, and use the ID-Selectors #header and specified.
#footer to apply styles to the <div>'s.
5. Similarly, we mark texts with <span class="new"> and <span class="highlight">, and
use the Class-Selectors .new and .highlight to apply styles to these texts.
6. Take note that:
<div> is a block element, while <span> is a inline element.
The class attribute can take multiple values, as in class="new highlight" (Line 18).
Both styles are applied.
7. CSS Basics
selector {
property-name-1: property-value-1-1, property-value-1-2, ... ;
property-name-2: property-value-2-1, property-value-2-2, ... ;
......;
}
For example,
This selector selects the <body> tag. Hence, the defined style is applied to the <body>...</body> element. Many (but not all) of the CSS properties (such as color,
font) are inherited by its descendants, unless they are overridden by other style rules.
2. The name:value pairs are separated by semicolon ";". You can omit the last semi-colon before the closing brace "}". But I recommend that you keep it, so that it is
easier to include new entries without a missing ";".
3. The name and value are separated by a colon ":" in the form of name:value.
4. Multiple values for the same property name are separated by commas "," (as in the font-family). However, multiple parts of the same property value are
separated by space " " (as in the margin, which has a value with 4 parts).
5. Values containing space must be quoted, e.g., "Times New Roman" or 'Times New Roman'.
22 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
8. Comments can be inserted inside the style sheet enclosed between /* and */. The end-of-line comment // is not applicable in CSS?!
2. Internal (Embedded) Style Sheet : Embedded inside the <style>...</style> tags in the HEAD section of the HTML document. The styles are applicable to
that entire document.
3. External Style Sheet (Recommended) : Stored in an external file, which is then linked to HTML documents via a <link> element in the HEAD section. The
same external style sheet can be applied to all HTML pages in your website to ensure uniformity in appearance.
Inline Styles
To apply inline style to an HTML element, include the list of style properties in the style attribute of the opening tag. For example,
<!DOCTYPE html>
<html>
<body>
<p style="font-size:18px; font-family:cursive">This paragraph uses 18px cursive font.</p>
<p>This paragraph uses default font.</p>
<p>This paragraph uses <span style="font-size:20px">20px inside this span</span>
but default font size here.</p>
</body>
</html>
This paragraph uses 20px inside this span but default font size here.
Take note that the name and value are separated by colon ':', and the name:value pair are separated by semicolon ';', as specified in the CSS syntax.
The scope of an inline style is limited to that particular element. Inline style defeats the stated goal of style sheets, which is to separate the document’s content and
presentation. Hence, inline style should be avoided and only be used sparsely for touching up a document, e.g., setting the column width of a particular table.
<!DOCTYPE html>
<html>
<head>
<style>
body { background-color:cyan }
h2 { color:white; background-color:black }
p.cursive { font-size:18px; font-family:cursive }
p.f20px { font-size:20px }
</style>
</head>
<body>
<h2>H2 is white on black</h2>
<p>This paragraph is normal.</p>
<p class="cursive">This paragraph uses 18-px cursive font.</p>
<p class="f20px">This paragraph uses 20-px font.</p>
</body>
</html>
23 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
External Styles
The style rules are defined in an external file, and referenced in an HTML document via the <link> element in the HEAD section.
/* testExternal.css */
body { background-color:cyan; color:red; }
h2 { background-color:black; color:white; text-align:center; }
p { font-size:12pt; font-variant:small-caps; }
p.f24pt { font-style:italic; font-size:24pt; text-indent:1cm; }
#green { color:green; }
This HTML document references the external style sheet via the <link> element in the HEAD section:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="TestExternal.css" rel="stylesheet">
</head>
<body>
<h2>H2 is white on black</h2>
<h2 id="green">This H2 is green on black</h2>
<p>The default paragraph uses 12-pt small-cap font.</p>
<p class="f24pt">This paragraph uses 24-pt, italics font with text-indent of 1cm.
It inherits the small-cap property from the default paragraph selector.</p>
</body>
</html>
You can use multiple <link> elements to include multiple CSS files.
The main advantage of external style sheets is that the same set of styles can be applied to all HTML pages in your website to ensure uniformity in presentation. External
style sheet is the now-preferred approach.
<style>
@import url("cssURL1.css");
@import url("cssURL2.css");
</style>
@import is part of the CSS language. It can also be used in one CSS file to include rules from another CSS file.
Priority
Inline styles have the highest priority, followed by internal styles, and followed by external styles.
7.3 Inheritance
Many (but not all) CSS properties, such as color and font-family, affect not only the elements selected by the selector, but also inherited by their descendants.
Inheritance is a big time-saver for designing styles. For example, you set the default color and font-family in the <body> element, which will then be inherited by all the
elements. You then override the default properties for specific elements, if needed.
Some properties (such as border, margin, padding, width, height, background-color) are not inherited. This is for good reason. For example, if border is defined for
<ul> and is inherited, then all descendants (<li>) will be drawn with border!
<!DOCTYPE html>
<html>
<head>
<style>
p { border: 5px solid red; }
.inherit-border { border: inherit; }
</style>
</head>
<body>
<p>The <em>border</em> property is not inherited.</p> <p> here parent/ ancestor
<p>The <em class="inherit-border">border</em> property is inherited.</p>
</body> and <em> child
</html>
Although the first <em> is nested under the <p> tag, the border property is not inherited from the ancestor. That is, you will not see a border around the <em>'s content.
We can force the inheritance by assigning a special value "inherit" as shown in the Class Selector .inherit-border.
24 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Style Conflict
Style conflict on an element arises:
1. A property is inherited from multiple ancestors.
2. More than one rules are applicable to the element. For example, Tag-selector p, Class-selector .red and ID-selector #comment are all applicable to element <p
id="comment" class="red">.
Specificity
Specificity means that "the more specific the selector, the stronger the rule". For example,
<!DOCTYPE html>
<html>
<head>
<style>
p { color:black; background-color:white; }
/* Override the color properties */
p.red { color:red; }
p#id1 { color:yellow; background-color:lightblue; }
p#id2 { color:blue; }
p#id1 { color:green; }
</style>
</head>
<body>
<p id="id1">Paragraph with id of "id1" (green)</p>
<p id="id2">Paragraph with id of "id2" (blue)</p>
<p class="red">Paragraph of class of "red" (red)</p>
<p id="id1" class="red">Paragraph with id of "id1" and class of "red" (green)</p>
<p>Paragraph without id and class with default colors (black)</p>
</body>
</html>
The p Tag-selector is the most general, which selects all the <p> elements; the p.red Class-selector selects a class of <p> elements with attribute class="red"; the p#id1
and p#id2 ID-selectors select only one element each with a unique id value. The ID-selector is the most specific (and takes precedence); followed by Class-selector; and
followed by the general Tag-selector.
Locality
If the "Law of Specificity" cannot resolve the conflict, apply the "Law of Locality". The style-rule that read in last by the browser takes effect. In the above example, there are
two ID-selector for id1, the latter takes effect.
The inline style (applied to a specific tag via style attribute) overrides the internal style (defined in <style>) and external style sheet (defined via <link>). For internal
and external styles, the order of <link> and <style> elements determine the precedence. It is recommended to place the <link> before <style> so that the internal
styles can override the external styles.
The <div> and <span> are generic tags for identifying contents. They do not possess any inherent visual properties (unlike <h1>, <p>, <em> which are expected to be
presented in a certain way). They shall be further qualified with id or class attribute, and attached with CSS styles selected via the ID-selector or Class-selector.
Modern-day HTML pages use <div> and <span> extensively to structure the document for applying CSS styles. Old HTML pages uses tables and frames, which should be
avoided. HTML5 introduces new semantic elements such as <header>, <footer>, <section>, <nav>, <article> to help you better structure your page.
25 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
You can assign an id="id-value" attribute to an HTML element to uniquely identify that element. The id-value must be unique within the HTML document. In other
words, no two elements can have the same id-value. The id attribute can be used by CSS (as well as JavaScript) to select that particular element. For example,
Similarly, you can assign class="class-value" attribute to a class of elements having the same presentation properties and appearance. The class-value needs not
be unique. That is, the same class-value can be assigned to many HTML elements. In other words, these HTML elements form a sub-class (hence, the keyword class).
The class attribute is primarily used by CSS to apply a common set of styles to all the elements of the same class. For example,
/* tag selector */
h2 { background-color:black; color:white; text-align:center; }
Applying CSS
1. Firstly, partition your web page in semantic partitions using the <div> and <span> elements, or the newer HTML5's <header>, <footer>, <section>, <article>,
<nav> elements.
2. Assign id or class to each of the partitions. Use id if it is unique (in formatting); otherwise, use class (more than one partitions have the same formatting).
3. Write the CSS style rules for tag, id and class.
Example: The following HTML page is divided into three sections. Selected texts are marked with the <span> tags, with class of "green" and "blue".
<!DOCTYPE html>
<html lang="en">
<head>
<title>Structure Web Page and apply style</title>
<meta charset="utf-8">
<link href="MyStyle.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Heading</h1>
</header>
<section id="content">
<h2>Hello</h2>
<p>Lorem ipsum dolor sit amet, <span class="green">consectetur adipisicing</span> elit, sed do
eiusmod <span class="green">tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in</span> reprehenderit in voluptate <span class="blue">velit esse</span>
cillum dolore eu fugiat nulla pariatur.</p>
</section>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
26 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
[TODO]
CSS is humongous! E.g., Read "The 30 CSS Selectors you Must Memorize". I shall list the frequently-used types of CSS selectors here.
Tag Selector : T
A Tag-selector selects all elements of the given tag-name. The syntax is:
tag-name { style-definitions }
Example:
h2 { background-color:black; color:white; }
The selector-x could be any kind of selectors, such as Tag-selector, Class-selector, or ID-selector.
Example:
Descendant Selector : T1 T2
You can define a style rule that takes effect only when a tag occurs within a certain contextual structure, e.g., descendant, immediate-child, first-child, sibling, etc.
To create a descendant selector, list the tags in their hierarchical order, with no commas separating them (commas are meant for grouping selectors).
Example:
ul li { color:red; }
ul ul li { color:blue; }
ul ul ul li { color:green; }
The first-level list items are in red; second-level in blue; and third-level in green.
Generic-Class Selector : .C
The Generic-Class Selector, which begins with a dot '.' followed by the classname, selects all elements with the given classname, regardless of the tag name.
Example:
Take note that the class attribute may contain multiple values. This means that you can apply multiple class style rules to an HTML element. For example,
27 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
An HTML element (such as <p>) can be sub-divided into different style sub-classes via the class attribute. This subclass mechanism allows us to apply different styles to
different subclass of a particular element.
For example,
Note: Do NOT start a class-name with a number! (This is the same restriction for identifiers in most of the programming languages.)
ID Selector : #D
The ID-selector, begins with a '#' followed by the id value, selects a specific element with the given unique id value. Recall that the id value must be unique in an HTML
document.
You can use <div>'s with unique id to divide the document into partitions of different styles. For example,
<body>
<div id="header">
<h1>H1 in the "header" division</h1>
<h3>H3 in the "header" division</h3>
<p>Paragraph in "header" division</p>
</div>
<div id="content">
<h1>H1 in the "content" division</h1>
<h3>H3 in the "content" division</h3>
<p>Paragraph in "content" division</p>
</div>
<div id="footer">
<p>Paragraph in "footer" division</p>
</div>
</body>
Universal Selector : *
The universal selector * selects ALL the elements in the document.
Example:
These pseudo classes is commonly-used with the <a> element. But :hover, :focus, and :active can also be applied to other elements, such as <p>, <li>, and etc.
Example:
28 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Another Example,
a {
font-size:10pt;
font-decoration:underline;
color:red;
}
a.blue:link { color:blue; }
a.green:link { color:green; }
a:hover {
font-decoration:none;
color:yellow;
}
The anchor pseudo-classes can be combined with ID-selectors as a Descendant-selector, so that the appearance of the links is different for the different divisions of the
document, e.g.,
You can restrict the selection by applying id or class. For example, p.intro:first-line, em.special:first-letter.
In CSS3, pseudo-elements are prefixed with 2 colons to differentiate with the pseudo-class, i.e., ::first-line and ::first-letter.
The above rules will add a double-quote (Unicode 0022H) in front and behind all elements having class="title".
In CSS3, pseudo-elements are prefixed with 2 colons to differentiate with the pseudo-class, i.e., ::before and ::after.
Note: Firefox does not support ::selection yet. You need to use ::-moz-selection instead. Include both ::selection and ::-moz-selection in your CSS.
Attribute Selectors
T[att]: selects elements that possess the given attribute, regardless of value.
T[att="value"]: selects elements that possess the given attribute, with the given value.
T[att^="value"]: selects elements that possess the given attribute, beginning with the given value. (Symbol ^ represent beginning in regex.)
T[att$="value"]: selects elements that possess the given attribute, ending with the given value. (Symbol $ represent ending in regex.)
T[att*="value"]: selects elements that possess the given attribute, containing with the given value.
29 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
:not(...) Selector
The :not(S) selector lets you select elements not meeting the criterion in selector S. For example, :not(.highlight) select elements not belonging to class highlight.
Specifying Color
Color can be expressed as:
1. RGB hexadecimal triplets in the form of #rrggbb, where rr, gg, bb are values of red, green and blue. The values are between 00 and FF, in hexadecimal. For example,
#12ABFF. The color value #112233 can be shorthand as #123.
2. RGB in the form of rgb(r, g, b). The r, g, b can be expressed in a decimal value between 0 and 255; or in percentage between 0% and 100%.
3. RGBA in the form of rgba(r, g, b, a): RGB with an additional A (alpha channel). The A is used to control the transparency/opacity, with a=1 for opaque; and a=0
for totally transparent.
4. HSL in the form hsl(hue, saturation, lightness): Hue is the color on the color wheel in degrees between 0 to 360. Saturation (purity of color) is expressed in
percentage between 0% and 100% (pure color). Lightness (brightness or intensity) is also expressed in percentage between 0% (darkest) and 100% (brightest).
5. HSLA in the form of hsla(hue, saturation, lightness, alpha).
6. The 16 pre-defined English color names as follows. These 16 colors are numerically generated and are really really ugly. You should avoid using them!! Many
browsers also support other color names such as lightblue, lightgreen, etc.
p {
width: 80%; /* 80% of the parent's width */
margin: 10px; /* pixels */
border: 5mm; /* millimeters */
padding: 0;
font-size: 1.2em; /* 1.2 times of the parent's font-size */
line-height: 1.5; /* 1.5 times of the current font-size */
}
There are two types of length measurements: relative (to another length property) and absolute (e.g., inches, centimeters, millimeters).
30 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
There shall be no space between the number and the unit, as space is used to separate multiple values.
Take note that % and em measurement are relative to another element (percentage values are always relative, e.g., 50% of something). For example,
p {
width: 80%; /* 80% of the parent's width */
font-size: 1.2em; /* 1.2 times of the parent's font */
margin: 1.2em; /* 1.2 times of the current font's letter 'm' */
padding: 10px; /* 10 pixels */
border: 0; /* zero does not need a unit */
}
To add to the confusion, some properties, such as line-height, can also accept a bare number, without a unit. This bare number is treated as a factor to be multiplied by
a reference. For example,
NOTE: In HTML tag attributes, such as width="400", the bare number is measured in pixels.
A block element (such as <p>, <div>, <h1> to <h6>) is always rectangular in shape and exhibits the so-called box model, with four virtual rectangles wrap around its
"content area", representing the content area, padding, border, margin, as illustrated below.
As illustrated in the box model diagram, margin pushes its border (and content) away with a transparent background showing the parent (having the effect of pushing
itself away from the parent); while padding pushes its content inwards with the same background. Margin and padding serve the same purpose if there is no border and
background applied.
Take note that the width and height that you set for the element specify its content area, exclude the margin, border and padding. To get the actual size of the element,
you need to add the margin, border and padding to the width/height. For example, suppose that:
31 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
#elm {
width: 300px;
margin: 10px;
border: 5px solid black;
padding: 20px;
}
Each of the rectangular bounds has four sides, and can be individually referred to as xxx-top, xxx-right, xxx-bottom, and xxx-left in a clockwise manner, where xxx
could be margin, border or padding. The four sides can be controlled individually or as a group.
As mentioned earlier, CSS length measurement requires a proper unit, e.g., width:400px or width:80%. Take note that width:400 is meaningless in CSS (this is a very
common error!) However, in HTML, width="400" means 400 pixels.
The width and height properties are NOT inherited by its descendants. The default value is "auto", which lets the browser to compute a suitable value. We shall discuss
"width:auto" value later.
32 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Example: [TODO]
width:auto
For most of the block elements (e.g., <div>, <p>), the default of width:auto sets the width to the width of the parent minus its own margin, border and padding. Images
<img> have an auto width equals to its actual width. Float elements have auto width of 0.
Example: [TODO]
Example: [TODO]
div#header {
margin: 10px auto; /* 20px for top and bottom, auto for left and right */
}
div#footer {
margin: 10px auto 5px auto /* top right, bottom, left */
}
div#content {
margin-top: 10px;
margin-right: auto;
margin-bottom: 5px;
margin-left: auto;
}
Example
The above box-model diagram was produced using these codes.
p {
font-size: 14px;
font-weight: bold;
line-height: 140%;
font-family: Arial, sans-serif;
}
33 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Example: [TODO]
The background properties has a one-line shorthand notation, with the order shown as below:
background: background-color background-image background-repeat background-attachment background-position
In all the above, the term background refers to the background of the elements selected (not necessary the entire window). In other words, you can set an image as the
background of an element.
Example: [TODO]
34 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
empty-cells: show|hide
table-layout: auto|fixed
[TODO: More]
8. More HTML
<map id="myMap">
<area shape="circle" href="url1" coords="xc, yc, r">
<area shape="rect" href="url2" coords="topLeftX, topLeftY, bottomRightX, bottomRightY">
<area shape="poly" href="url3" coords="x1, y1, x2, y2, ..., x1, y1">
</map>
<img usemap="#myMap" src="client_map.gif">
Example:
<map id="myMap">
<area shape="rect" coords="20,20,160,60" href="http://www.zzz.com/">
<area shape="circle" coords="80,120,60,60" href="http://www.yyy.com/">
</map>
<img usemap="#myMap" src="banner.jpg">
<map id|name="map-name">
<area shape="rect|circle|poly|default"
coords="coordinates-list"
href="URL" nohref
target="_blank|_parent|_self|_top|target-frame-name"
alt="alternative-text" />
... more-area-declarations ...
</map>
<map>'s attributes:
id|name="map-name": declares a unique name for the map, to be targeted in attribute usemap="#map-name" of the <img>.
(The attribute name is used the older browsers. XHTML specifies using id instead, which automatically create a named anchor.)
<area>'s attributes:
shape="rect|circle|poly|default": define the shape of the hot region. The "default" value for any point not part of another hot region.
coords: list of coordinates that made up the hot region.
For shape="rect", coords="topLeftX, topLeftY, bottomRightX, bottomRightY" to specify the upper-left and lower-right corners.
For shape="circle", coords="xc, yc, r", where (xc, yc) is the center and r is the radius.
For shape="poly", coords="x1, y1, x2, y2, ..., x1, y1", where (xi, yi) are coordinates that made up the polygon. You should close the polygon by
putting (x1, y1) as the last coordinates.
href="url": gives the target URL of the hyperlink.
nohref: deactivate the hot region, pointing to nowhere.
If two hot regions overlap, the first takes effect.
A client-side image map can be used as a navigation bar on top of the page, instead of using individual images. This may save some transmission overhead, as each
individual image triggers its own HTTP request.
35 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
When the image is clicked, the (x, y) position of the click is send to the server as query parameters. For example,
http://www.zzz.com/search.jsp?39,22
It is up to the server to decide on how to process the (x, y) position received via a server-side program (such as CGI/ASP/JSP/PHP/Servlet).
8.2 Frames
You can divide the browser's window into multiple regions called frames. Each of the frames can contain a distinct and complete HTML document. Framed layout enables
you to display several HTML document at once. Framed layout is popular for:
Dividing the window into a navigation frame (on the top or left-side of the window) and an actual content frame.
Dividing the window into a small summary frame and a detail frame. Java API documentation is a good example.
However, use frames with extreme care! Frame (especially the "header" frame) occupied precious screen asset, as it does not scroll away! Framed layout have fallen out of
favor over the years. Use <div> and CSS to organize your web page instead.
Syntax:
<frameset rows="list-of-row-sizes">
...frame-declarations...
</frameset>
<frameset cols="list-of-column-sizes">
...frame-declarations...
</frameset>
Attributes:
rows|cols="n|n%|*, n|n%|*, ...": a list of frame sizes in pixels or percentage separated by commas. Wildcard "*" can be used to indicate the remaining space.
Example:
Divide the window into four rows of sizes: 100 pixels, 20% of the screen, 150 pixels, and the remaining space.
Syntax:
<frame
src="url"
name="frame-name"
noresize
frameborder="0|1"
scrolling="yes|no|auto" />
Attributes:
src:="url": provides the URL of the document to be displayed inside this frame.
name: specifies an unique identifier, to be used as the target of other tags, such as <a>, <form>.
noresize: suppresses resizing by dragging of border.
36 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Example: Divide the screen into 3 frames, top, left and right.
If all the links in the "navigation" frame are targeting the "detail" frame, you can use the <base> tag (in the HEAD section) to set up a global target reference:
As mentioned, frames has gone out of favor these day. The HTML5 introduced new elements such as <header>, <footer>, <section>, <nav>, <article> to help you in
organizing your web page, instead of using frame, division, or table.
No Frame <noframe>...</noframe>
Function: Provides an alternative text if the browser does not support framed layout. <noframe> must be placed within a <frameset>.
<noframe>...alternative-text...</noframe>
<iframe
src="URL"
name="frame-name"
frameborder="0|1"
scrolling="yes|no|auto">
...alternative-text...
</iframe>
You could use CSS to position and style the iframe. Iframe is used extensively by JavaScript and Ajax.
Example: [TODO]
<applet
code="applet-main-class-name"
archive="applet-jar-file"
object="serialized-applet-file"
width="applet-window-width-in-pixels"
height="applet-window-height-in-pixels"
codebase="base-URL-of-the-applet"
37 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
alt="alternative-text">
...alternative-text...
</applet>
<object
classid="program-info"
codebase="base-URL-of-the-program"
codetype="code-mime-type"
data="URL-of-the-data"
type="data-mime-type"
archive="list-of-archive"
usemap="#map-name"
tabindex="tabbing-position">
...alternative-text...
</object>
<param
id="unique-identifier"
name="parameter-name"
value="parameter-value"
valuetype="data|ref|object"
type="parameter-mime-type">
Syntax:
Attributes:
href="baseUrl": All relative URLs in this document are relative to this base-URL. For example, if <base>’s href is set to:
38 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Syntax:
<link href="url"
type="mime-type"
rel="forward-relationship"
rev="reverse-relationship"
charset="character-encoding"
hreflang="language-of-href"
media="intended-display"
target="target-frame-name" />
Attributes:
rel, rev: indicates the forward or reverse relationship to the current document. Take value of home, stylesheet, help, index, toc, up, next, previous, glossary,
copyright, and made (i.e., author).
Example:
<head>
<link href="master.css" rel="stylesheet" type="text/css" />
<link href="index.html" rel="home" />
<link href="help.html" rel="help" />
<link href="chapter5.html" rev="previous" />
<link href="chapter3.html" rev="next" />
</head>
The above <link> tags indicate that "master.css" is the stylesheet of MIME type "text/css"; "index.html" is the home page; "help.html" is the help page; this page
("chapter4.html") is the previous page of "chapter5.html" (in a reverse relationship), and this page is the next page of "chapter3.html".
The most-commonly used <link> is to specify the external CSS style sheet. The rests are hardly used.
Including an Icon
A favicon (aka favorite icon, shortcut icon, URL icon) is a file containing a small 16x16 icon. Browser can display the icon besides the URL bar or bookmark. The favicon file
is usually called "favicon.ico".
You can use PhotoShop/Element to create a favicon file; or use a simple imaging tool (such as MS Paint) to create a small image and then submit to an online converter to
generate a favicon file.
Examples:
The <meta> tag can also be used to ask the server to insert an HTTP response header (read "HTTP Basics"). The syntax is as follow:
<html>
<head>
<meta http-equiv="Refresh" content="3; Url=http://www.google.com/" />
</head>
<body>
<p>You will be redirected to ... in 3 seconds unless you push the STOP button</p>
One thousand...<br>
Two thousand...<br>
Three thousand...
</body>
</html>
The above <meta> tag triggers the server to include the following "Response Header" in the HTTP response message, when the page is downloaded:
Refresh: 3; Url=http://www.google.com/
The browser, in response to this response header, redirect to the given URL after 3 sec.
39 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
// HTML5
<meta charset="utf-8" />
The server will include this response header in the response message, when the page is downloaded:
9. More CSS
By default, elements are displayed from top to bottom in the normal flow. For block elements, line breaks are inserted at the beginning and the end to form a rectangular
box. You can leave the box in the default normal flow (position:static); you can remove the box from the normal flow and specify its location with respect to either its
parent element (position:absolute) or the browser window (position:fixed); you can also move the box with respect to its normal position in the flow
(position:relative).
For non-static positioned elements, the new position is specified via top, left, bottom, right, width, height properties:
top: n|n%|auto
left: n|n%|auto
bottom: n|n%|auto
right: n|n%|auto
Set the distance from the edge of this element to the corresponding edge of the containing block.
width: n|n%|auto
height: n|n%|auto
Set the width and height of this block. You can use the width and height to scale this block.
z-index: number|auto
When two blocks overlap due to re-positioning, the one with larger z-index number is on top (i.e., z-axis is pointing out of the screen as in the standard 3D graphics
coordinates system). Negative number is allowed. The default auto stacks the element at the same level as its parent. If the z-index of two elements are the same or
no z-index are defined, the last element rendered is placed on top. z-index with alpha can create see-thru effect.
overflow: auto|hidden|scroll|visible|inherit
Specify how to handle content overflowing the block's width/height.
div#up {
position: relative;
top: -2em; /* move this element up by 2em */
}
To absolutely position an element in a containing element (other than <body>), declare the containing element relative without any movement, e.g., container {
position:relative }.
Absolute positioning is interesting. You can create animation (such as bouncing ball and falling snow) by absolutely position (and repeatedly re-position) images on the
browser's screen. See my "JavaScript Examples".
For example,
#left-panel {
40 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
position: absolute;
left: 10px; /* from left edge */
top: 10px; /* from top edge */
width: 200px;
height: 600px;
background: black;
color: white;
}
#main-panel {
position: absolute;
left: 220px; /* from left edge 10+200+10 */
top: 10px; /* from top edge, same as left-panel */
width: 560px;
height: 600px;
background: cyan;
color: black;
}
<body>
<div id="left-panel">
<h2>Left Panel</h2>
<p>This paragraph is on the left panel</p>
</div>
<div id="main-panel">
<h2>Main Panel</h2>
<p>This paragraph is on the main panel</p>
</div>
</body>
For example, a fixed <div> is added to the above example in absolute positioning. Take note that z-index is used to ensure that the fixed <div> is always on top of the
other <div>'s, regardless of the order of writing the <div>'s.
#left-panel {
position: absolute;
left: 10px; /* from left edge */
top: 10px; /* from top edge */
width: 200px;
height: 600px;
background: black;
color: white;
z-index: 100;
}
#main-panel {
position: absolute;
left: 220px; /* from left edge 10+200+10 */
top: 10px; /* from top edge, same as left-panel */
width: 560px;
height: 600px;
background: cyan;
color: black;
z-index: 100;
}
#fixed-panel {
position: fixed;
left: 100px;
top: 200px;
width: 200px;
height: 200px;
background: lime;
color: red;
z-index: 200; /* larger z-index is on top */
}
<body>
<div id="left-panel">
<h2>Left Panel</h2>
<p>This paragraph is on the left panel</p>
</div>
<div id="main-panel">
<h2>Main Panel</h2>
<p>This paragraph is on the main panel</p>
</div>
<div id="fixed-panel">
<h2>Fixed Panel</h2>
<p>This panel does not move when your scroll up/down.</p>
</div>
</body>
41 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
You can push an element to the left or right edge of the containing element via property float. Float is often used for images, with texts surrounding the floated element.
The elements preceding the floated element are not affected. The element after the floated element flows around it.
You can float horizontally (i.e., left and right), not up and down. Other than images, a float element shall have the width and height explicitly specified. Float elements are
actually taken out of the normal flow. The following element acts as if the floated element is not there, but the enclosing texts would wrap around the floated element.
If many images are floated together (says to the left), the second image will be pushed to the left edge of the first image, and so on if there is available horizontal space;
and shifted down otherwise. For example, we can float many thumbnail images to the left as follows:
img.thumbnail {
float: left;
width: 120px;
height: 100px;
margin: 5px;
}
To turn off the float, use property clear, and specify which side (left, right or both) does not allow a floating element.
clear: left|right|both|none
clear:left means that the left side of this element cannot be a floating element. That is, the left shall begin with left margin of the containing element. clear:left is
similar to <br>.
[TODO] more
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>iframe Test</title>
5 <link rel="stylesheet" href="iframeTest.css">
6 </head>
7 <body>
8 <iframe src="iframeContent.html" name="myIframe" id="myIframe"></iframe>
9 <h1>Hello</h1>
10 </body>
11 </html>
"iframeTest.css"
1 body {
2 background-color: #FFF;
3 }
4
5 #myIframe { /* ID-Selector */
6 float: right; /* float with the right margin of the browser's window */
7 margin-top: 100px; /* margin from the top of the window */
8 border: 1px solid black;
9 width: 350px;
10 height: 300px;
11 }
The CSS property float: left|right|none (also applicable to <img>) floats the iframe to the left or right margin of the browser's window.
You can also use CSS property position: absolute|fixed|relative|static to position the iframe (and other HTML elements), "absolute" positions the element
relative to its first positioned ancestor element; "fixed" is relative to the browser window and does not scroll away; "relative" means relative to its normal position; the
default "static" positions the element in the order it appears in the document.
#myIframe {
position: absolute;
left: 300px;
top: 50px;
border: 1px solid black;
width: 350px;
height: 300px;
}
42 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Example: [TODO]
The display:block can be used to display an inline element as a block. For example,
On the other hand, display:inline can be used to display a block element inline. For example,
visibility:hidden|visible can be used to hide or show the element without removing the element from the normal flow of the page. That is, the space occupied by
the element is preserved.
Property cursor
cursor: auto|crosshair|default|help|move|wait|pointer|progress|text
cursor: n-resize|ne-resize|nw-resize|s-resize|se-resize|sw-resize|w-resize|e-resize
Example: [TODO]
Property clip
clip:mask|auto|inherit
Clip an absolutely-positioned element. The "mask" sets a rectangular mask in the form of rect(top right, bottom, left), where top, right, bottom, and left are
relative to the containing block. For example,
.clip {
position: relative; /* container for absolute-positioned image */
height: 180px; /* original width and height of image */
width: 180px;
border: solid 1px grey;
}
.clip img {
position: absolute; /* can clip */
clip: rect(10px 160px 80px 20px); /* clip top, right, bottom, left */
}
Recall that an absolute-positioned block must be placed in a non-static block, in this case, a relative-position <div>.
Image Sprite
[TODO]
Property opacity
You can use the property opacity to control the transparency of an image. For example,
img.thumbnail {
opacity:0.5;
}
img.thumbnail:hover {
opacity:1.0;
}
43 of 44 7/21/2016 3:57 PM
HTML and CSS Tutorial: The Basics https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/...
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME
44 of 44 7/21/2016 3:57 PM