HTML and CSS Tutorial - The Basics
HTML and CSS Tutorial - The Basics
| HOME
Basics
3.4 HTML Template
3.5 HTML Document Validator
3.6 Debugging HTML
4. HTML Basics
4.1 HTML Tags, Attributes and Elem
4.2 The Basic Document Skeleton
4.3 HTML Comment <!-- ... -->
1. Introduction to HTML/CSS 4.4 Block Elements vs. Inline Eleme
4.5 Block Elements
If you are the “content provider”, read HTML. If you are the
4.6 HTML5's New Semantic Block El
“graphic designer”, read CSS. If you are a programmer and want
4.7 Inline Elements - Logical Style vs
to add dynamic effects to your web page, read JavaScript. But if
4.8 HTML5's New Semantic Inline E
you operate in OMO (one-man-operated) and are expected to
4.9 Entity References for Reserved &
create a reasonably good-looking website, you need to
4.10 Lists
understand HTML, CSS and JavaScript. This is the reason that I
4.11 Tables
combine both the HTML and CSS in this article as they are
4.12 Anchors and Hyperlinks
inseparable.
4.13 Images
To create an OMO website, I suggest that: 5. Introduction to CSS
1. Understand HTML, CSS and JavaScript thoroughly. 6. CSS By Examples
6.1 CSS Example 1: CSS Syntax and
2. Pick an authoring tool: Use Dreamweaver if you can afford.
6.2 CSS Example 2: CSS Class-Select
Otherwise, find a free source-code editor (such as VS Code,
6.3 Validating CSS
Sublime Text, Sublime Text, NotePad++). For programmers,
6.4 Inspecting Element's Styles via F
Eclipse/NetBeans/VSCode are good choice for
7. CSS Basics
HTML/CSS/JavaScript as they perform syntax checking and
7.1 CSS Syntax
provide auto-code-complete.
7.2 Inline, Internal and External Sty
3. Design and organize your page. Decide on the look and feel 7.3 Inheritance
of your website. How many columns? What are the major 7.4 Resolving Conflicting Rules
sections (e.g., header, navigation menu, main content, 7.5 How to Use CSS for Styling HTM
sidebar, table of content, footer)? Do you need a navigation 7.6 Types of CSS Selectors
menu or panel? What is your theme (colors, fonts)? And so
8. CSS Style Properties
on. 8.1 CSS color and background-col
4. Take a close look at your favorite websites!!! CSS is 8.2 CSS Length Measurements
humongous and complex! You can't invent this wheel! Use 8.3 CSS Box Model and Properties m
F12 Debugger to inspect HTML/CSS of your favorite websites. 8.4 CSS font Properties
Use a CSS framework, such as BootStrap, to jump-start your 8.5 CSS text Properties
design. 8.6 CSS background Properties
5. Start with an initial CSS design. Website design begins with 8.7 CSS list-style Properties
CSS, NOT HTML?!. Work on your CSS: 8.8 CSS Table Properties
a. Partition your web page into logical section via <div> (or 9. More HTML
HTML5' <header>, <footer>, <section>, <nav>), such as 9.1 Image Maps
header, content, footer. Assign an id to <div> that is 9.2 Frames
9.3 Embedding Programs
unique (e.g., "header", "footer". Assign a common 9.4 HTML Global Attributes
classname to sections (non-unique) that share the same 9.5 HEAD Section's Tags
style (e.g., "entry", "side-note"). Write the CSS id- 10. More CSS
selectors and class-selectors (e.g., #header tag- 10.1 CSS Variables (Custom Propert
name,... #footer tag-name,... #menu tag-name,...) 10.2 Modifying CSS Properties from
10.3 CSS position Property - Positi
for common tags (such as h1, h2, h3, p, a:link,
10.4 CSS float and clear Property
a:visited, a:hover, a:active), in each of the <div>'s.
10.5 CSS display and visibility P
Basically, what I am saying is to design each of the
10.6 CSS cursor Property
sections by itself - a "divide and conquer" strategy.
b. Create sub-classes for common styles, such as layout out
tables and images and special effects (e.g., ".highlight",
".underline", ".center"). They could be used in <div>
and <span>.
c. There are many good and free CSS templates (or web templates) available online (just google
"CSS Templates" or "Web templates"). Pick one that meets your taste to model after. You can also
look at the CSS of any website that you find interesting. Be aware of the Intellectual Property
Right, do not use any images or graphics unless they are in the public domain. It is extremely
easy to create one yourself with an imaging tool, such as PhotoShop, Element, Illustrator or even
Paint.
Use a CSS framework, such as BootStrap; and pick your favorite design from the samples.
6. Write your HTML pages. You may need to modify the CSS as you go along. The most challenging thing
for an OMO web author is that he has to be concerned about both the contents and appearances at
the same time, and can lose focus at times!
7. Repeat the previous steps until you are happy with your page's look and feel, layout, and most
importantly, the contents - try not to create yet another insignificant website.
I wrote the above many years ago while creating these web pages (You can check out my CSS). Today, I
would recommend that you learn the basics of HTML/CSS, but quickly jump into a framework such as
BootStrap to produce professional-looking web pages. You can't write better than these people!
2. Introduction to HTML
HTML Versions
HTML Draft (October 1991): Tim Bernes-Lee (of CERN) proposed the early HTML (with 18 tags) for
sharing of document in a hypertext system.
HTML 2.0 (November 24, 1995): Published as IETF RFC 1866.
HTML 3.2 (January 14, 1997): Published as W3C HTML 3.2 Recommendation.
HTML 4.0 (December 1997): Published as W3C HTML 4.0 Recommendation, with strict, transitional
and frameset. In December 24, 1999, HTML 4.01 was published as the final HTML specification by
W3C. In May 2000, HTML 4.01 Strict as published as ISO/IEC International Standard 15445:2000.
XHTML 1.0 (January 2000): W3C considered HTML 4.01 as the final 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 28, 2014): HTML 5 was published as W3C Recommendation, followed by HTML 5.1
on November 1, 2016, and HTML 5.2 in December 14, 2017.
On 28 May 2019, the W3C announced that WHATWG would be the sole publisher of the HTML and
DOM standards.
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>.
3. HTML By Examples
Let's go thru some HTML examples and the syntaxes. Do not attempt to start designing your website until
you understand the CSS.
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 <mark>markup tag</mark> to <em>markup</em> a document.</p>
13 </body>
14 </html>
How it Works?
1. An HTML document begins with a Document-Type Declaration <!DOCTYPE html> (Line 1) to identify
itself as an HTML document to the browser.
2. The HTML content is contained within a pair of <html>...</html> container tags. You can specify the
default language of your document via attribute lang="en" (for English) inside 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; and <mark>...</mark> (HTML 5) requests for
highlight.
Note: For macOS'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.
1 <!DOCTYPE html>
2 <html lang="en">
3 <!-- Save as "HtmlEg2.html" -->
4 <head>
5 <meta charset="utf-8">
6 <title>Lists and Hyperlinks</title>
7 </head>
8 <body>
9 <h1>Lists and Hyperlinks</h1>
10 <p>There are two types of <em>lists</em> in HTML:</p>
11 <ol>
12 <li>Ordered List.</li>
13 <li>Unordered List.</li>
14 </ol>
15
16 <p>This is a nested unordered list of links:</p>
17 <ul>
18 <li>Online Validator:
19 <ul>
20 <li>W3C Online HTML Validator @ <a href="https://validator.w3.org/">https:/
21 <li>W3C Online CSS Validator @ <a href="https://jigsaw.w3.org/css-validato
22 </ul>
23 </li>
24 <li>Specifications:
25 <ul>
26 <li>HTML5 @ <a href="http://www.w3.org/TR/html5/">http://www.w3.org/TR/html
27 <li>CSS3 Selectors @ <a href="http://www.w3.org/TR/css3-selectors/">http://
28 </ul>
29 </li>
30 </ul>
31 </body>
32 </html>
How it Works?
1. The <!-- ... --> (in Line 3) is an HTML comment. Comments are ignored by the browsers, 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 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>.
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.
4. Hyperlink is marked by <a> standalone tag. The attribute href="url" provides the destination URL of
the link.
3.3 Example 3: Tables and Images
1 <!DOCTYPE html>
Lists and
2
3
<html lang="en">
<!-- Save as "HtmlEg3.html" -->
Hyperlinks
4 <head>
There are two types of lists in
5 <meta charset="utf-8">
HTML:
6 <title>Table and Images</title>
7 <style> 1. Ordered List.
8 table { /* table */ 2. Unordered List.
9 border: 1px solid black;
This is a nested unordered list of
10 border-spacing: 5px;
links:
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.
32 </tr>
33 <tr>
34 <td>2.</td>
35 <td>CSS3</td>
36 <td><img src="../images/css3.png" alt="
37 </tr>
38 <tr>
39 <td>3.</td>
40 <td>JavaScript</td>
41 <td><img src="../images/js3.png" alt="J
42 </tr>
43 </table>
44 </body>
45 </html>
How it Works?
1. A table, consisting of rows of cells, can be marked via <table>...</table>.
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).
3. The <caption>...</caption> element can be nested under
<table> to provide a caption for the table.
4. Image is marked via the <img> tag. The mandatory attribute src Table and
specifies the path (or url) for the image source file; alt gives the
alternative text if the image cannot be displayed. I used relative
Images
path in the src, where ".." denotes the parent directory. You need
Logo of Languag
to find some images, store them and figure out your own relative
path. S/No Language
5. The <img>'s optional attributes width and height specify the width
and height of the image displayed area. They are used here to
1. HTML5
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.
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>YOUR TITLE HERE!</title>
6 <link href="filename.css" rel="stylesheet">
7 <script src="filename.js"></script>
8 </head>
9 <body>
10 <!-- YOUR CODE HERE! -->
11 </body>
12 </html>
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.
In most of the browsers, you can push F12 to get into Web Developer Tools, which support debugging
HTML, CSS, JavaScript, DOM and more.
To debug HTML:
1. Choose the "Inspector" panel to view your HTML codes.
2. To inspect an element, click on the "picker" and point to the HTML element of interest. You can
check/modify the "Style", "Layout", "DOM" and "Events" (on the right panel) associated with the
selected element.
Try it out on the earlier examples.
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 height of the image displayed area.
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. Void Element (or Standalone Element or Empty Element): A void 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 the above rules. Today, most developers omit the trailing '/' for brevity,
e.g., <br>, <hr>.
HTML4 has these void elements: <area>, <base>, <br>, <col>, <hr>, <img>, <input>, <link>, <meta>,
<param>.
HTML5 added <command>, <keygen>, <source>.
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 &nb
This is a paragraph.
Another paragraph
with a line-break in between and more spaces before this.
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 contain 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):
<link href="filename.css" rel="stylesheet">
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).
Comments are also useful in temporarily disable a certain part of the HTML codes during development.
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.
Quote <blockquote>...</blockquote>
Function: Mark out a block of quote. Browsers typically indent the entire block to the right. For example,
<blockquote>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod 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
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.</blockquote>
Best Practices:
Notes: With the introduction of many new semantic block elements in HTML5, such as <header>,
<footer>, <main>, <section>, it is strongly encouraged "to view the <div> element as an element of
last resort, for when no other element is suitable. The use of more appropriate elements instead of
the <div> element leads to better accessibility for readers and easier maintainability for authors".
Avoid deep nested container layouts using <div>. "should be not nested deeper than 6 layers".
Use as little HTML elements as possible (to increase the content to tag ratio and reduce page load).
<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>
Article <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.
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).
Which Element to Use?
The HTML5 Doctor provides a nice flowchart for you to decide which HTML5 element to use @
http://html5doctor.com/downloads/h5d-sectioning-flowchart.pdf.
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.
<ins>...</ins> inserted
<del>...</del> deleted
<address>... address
</address>
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 mag
na aliqua. Ut enim ad minim veniam, quis sample exercitation ullamco laboris nisi ut code ex ea ke
yboard consequat. Duis aute irure dolor in reprehenderit in velit esse cillum dolore eu fugiat nulla p
ariatur. Excepteur insert occaecat delete non proident, sunt in culpa qui officia deserunt mollit ani
m id est laborum.
For example,
Lorem abbr dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor HTML ut labore et d
olore 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.
Physical-Style
Meaning
Tag
<b>...</b> bold
<i>...</i> italic
<sup>...</sup> superscript
<sub>...</sub> subscript
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.
< <
> >
& &
° (degree) °
˜ ˜
☎ ☎
🔍 (search) 🔍
✓ ✗ ✓ ✗
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.
<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 (or Description 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. HTML 5 call it Description List.
<dl>
<dt>term-1</dt>
<dd>definition-for-term-1</dd>
<dt>term-2</dt>
<dd>definition-for-term-2</dd>
......
</dl>
Example:
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:
<p>The topics covered are:</p>
<ul>
<li>HyperText Markup Language (HTML)
<ul>
<li>Based on SGML</li>
<li>Used to create web pages</li>
<li>Maintained by W3C</li>
</ul>
</li>
<li>Cascading Style Sheet (CSS)
<ul>
<li>Used to define presentation style for web pages</li>
<li>Also maintained by W3C</li>
</ul>
</li>
</ul>
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.
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>
44444 66666
55555
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
44444 55555 66666
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>
<td>Col 1 in the group 1</td>
<td>Col 2 in the group 1</td>
<td>Col 3 in the group 2</td>
<td>Col 4 in the group 2</td>
</tr>
<tr>
<td>Col 1 in the group 1</td>
<td>Col 2 in the group 1</td>
<td>Col 3 in the group 2</td>
<td>Col 4 in the group 2</td>
</tr>
</table>
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,
http://www.w3c.org/css/index.html
http://www.mytest.com:8080/default.html
ftp://ftp.faqs.org
news:soc.culture.singapore
mailto:[email protected]
javascript:myFunction() //See example below
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,
<h2><a name="eg_1">Example 1</a></h2>
......
......
<h2><a name="eg_2">Example 2</a></h2>
......
......
Jump to <a href="#eg_1">Example 1</a>
......
Jump to <a href="#eg_2">Example 2</a>
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8" />
5 <title>HTML Testing</title>
6 <script>
7 function myFunction() {
8 alert("hello, world")
9 }
10 </script>
11 </head>
12 <body>
13 <a href="javascript:myFunction()">Run JavaScript</a>
14 </body>
15 </html>
The "return false" is needed to prevent the page from scrolling to the top following href="#".
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:
src="imageUrl" (required): gives the URL of the image.
alt="text" (required): alternative text to be displayed if the image cannot be displayed.
width="n|n%", height="n|n%": specify the width and height of the image display area (in pixels or
percentage). Browsers use these values to reserve space for the image (before the image is
downloaded) and continue rendering the rest of the contents. You can also use the width and height
to scale an image. This is not recommended because scaling-up results in a blur image and scaling-
down is a waste of bandwidth.
I recommend that you use the width and height tags for images, so that the browser can reserve
spaces for the images. This is more efficient and could avoid a jerky display if you page contains many
images. You can find out the width and height of an image easily by checking the "Properties" of the
image.
title="tooltip-text": the attribute title is applicable to most of the HTML elements for you to
provide the tool-tip text.
Many attributes were added in HTML5. Some of them will be discussed in the later sections.
crossorigin="anonymous|use-credentials":
referrerpolicy="no-referrer|no-referrer-when-downgrade|origin|origin-when-
cross-origin|same-origin|strict-origin|strict-origin-when-cross-origin|unsafe-
url":
decoding="sync|async|auto":
fetchpriority="high|low|auto":
loading="eager|lazy":
sizes=list:
srcset=list:
<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
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>
How it Works?
1. /* ... */ is a CSS comment. Comments are ignored by the Test CSS
browsers but provide important information to the readers, as well
as the author.
Style Sheet
2. A CSS style sheet contains style rules.
This is heading
3. A style rule begins with a selector, followed by the list or
presentation properties enclosed within {...}.
level 2
4. A property is identified by its name, followed by its value, separated
Lorem ipsum dolor sit
by colon ":". The name:value pairs are separated by semicolon ";". amet, consectetur
A name could have multiple values, separated by commas "," (e.g., adipiscing elit, sed do
eiusmod tempor
the font-family property).
incididunt ut labore et
5. A selector selects a set of HTML elements to apply the styles. This dolore magna aliqua. Ut
example uses the so-called Tag-Selector, which select all elements having the tagname. For
example, the first rule is applicable to the <body>; the 3rd to <h2>, and the 4th rule to all the <p>
elements.
6. Selectors having the same rules can be grouped together and separated by commas ",". For
example, the 2nd rule is applicable to <h1> to <h6>.
7. Some of the properties are inherited by the nested elements. For example, the <p> nested under
<body> inherits the font-family from the <body>. Some properties are not inherited.
8. If more than one rules are applicable, the properties are accumulated. But, the last rule will take
effect if there is conflict. For example, both Rule 3 and 4 are applicable to <h2>. The <h2> accumulates
the properties from both rules. It takes the font-weight:bold from Rule 3 (which is not specified in
Rule 4); but uses the color:blue from the Rule 4 (instead of Rule 3).
9. Style properties:
The font-family list the font faces, in the order of preferences. Browsers search through the list
(from the beginning) to an available font face.
color and background-color: specify the foreground and background colors, respectively. Color
can be expressed in #rrggbb (hex value), rgb(r, g, b) (decimal value between 0 and 255), or
with the pre-defined color names (such as red, blue).
text-align: text alignment of either left, right, justify, center.
font-weight: normal, bold, and others.
font-style: normal, italic, and others.
Take note that CSS is a language with its own syntaxes. CSS syntax is totally different from HTML!
6.2 CSS Example 2: CSS Class-Selector, ID-Selector with <div> and <span>
How it Works?
1. In the earlier example, we use Tag-Selectors which select Test CSS Style
elements based on tagname. Besides the Tag-Selector,
there are Class-Selector which selects elements based on Sheet
class attribute; and ID-selector which selects an
element based on the id attribute. This is heading level 2
2. An ID-Selector begins with a # sign, followed by an id-
name, e.g., #header and #footer, which select element Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do
with id="header" and id="footer", respectively. Since
eiusmod tempor incididunt ut
id-value is meant to be unique within an HTML labore et dolore magna aliqua. Ut
document, ID-selector select at most one element. enim ad minim veniam, quis nostrud
3. A Class-Selector begins with a dot "." followed by a exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat
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.
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 id="footer"> to
semantically identify their contents, and use the ID-Selectors #header and #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.
For example,
Recommendation: Use ID for JavaScript and internal <a> link (which refers to one single element in the
HTML document); and class for CSS (which refers to a group of elements with the same style).
To debug CSS:
1. F12 to launch Web Developer Tools.
2. To inspect the style of an HTML element ⇒ Choose the "HTML" panel ⇒ Click on the "Inspect" button
and then select the HTML element of interest from the browser window ⇒ You can check/modify the
"Style", "Layout", "DOM" and "Events" (on the right panel) associated with the selected element.
3. To check/modify the CSS Style rules ⇒ Choose the "CSS" panel.
7. CSS Basics
For example,
body { /* Apply to <body> and possibly its descendants */
font-family: "Open Sans", Helvetica, Arial, sans-serif;
font-size: 16px;
margin: 10px auto; /* top-down right-left */
padding: 0;
}
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'.
6. Extra whitespaces (blank, tab and newline) are ignored.
7. If the same set of styles is applicable to more than one elements, the selectors can be grouped
together in one single rule (called Group-Selector). The tagnames are separated by commas ",". For
example, the following rule apply to elements <h1> to <h6>:
8. Comments can be inserted inside the style sheet enclosed between /* and */. The end-of-line
comment // is not applicable in CSS?!
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:16px; font-family:monospace">This paragraph uses 16px monospace f
<p>This paragraph uses default font.</p>
<p>This paragraph uses <span style="font-size:12px">12px inside this span</span>
but default font size here.</p>
</body>
</html>
This paragraph uses 12px 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.monospace {
font-size:16px;
font-family:monospace;
}
p.f20px {
font-size:20px;
}
</style>
</head>
<body>
<h2>H2 is white on black</h2>
<p>This paragraph is normal.</p>
<p class="monospace">This paragraph uses 16-px monospace font.</p>
<p class="f20px">This paragraph uses 20-px font.</p>
</body>
</html>
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.
@import is a CSS directive (part of CSS language). It can also be used in one CSS file to include rules from
another CSS file, for example,
/* in CSS fie */
@import '/css/more-styles.css';
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>The <em class="inherit-border">border</em> property is inherited.</p>
</body>
</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.
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.
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,
eiusmod <span class="green">tempor incididunt ut labore et dolore magna aliqua. Ut enim
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo c
Duis aute irure dolor in</span> reprehenderit in voluptate <span class="blue">velit ess
cillum dolore eu fugiat nulla pariatur.</p>
</section>
<footer>
<p>Footer</p>
</footer>
</body>
</html>
[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.
S1~S2 a ~ span { } General Sibling Selector: All S2(s) that are siblings after
S1
Tag Selector: T
A Tag-selector selects all elements of the given tag-name. The syntax is:
tag-name { style-declaration }
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,
<p class="f14px_i underline">Text is 14px and italic, and underlined.</p>
<p class="f16px_b red underline">Text is 16px and bold, in red and underlined.</p>
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,
p { color:black; } /* default style for all <p> tags */
p.red { color:red; } /* applicable to <p class="red"> tags (override default)
p.blue { color:blue; } /* applicable to <p class="blue"> tags (override default)
h1, h2, h3 { color:green; } /* default style for <h1>, <h2> and <h3> tags */
h3.white { color:white; } /* applicable to <h3 class="white"> tags (override defaul
h3.upper { text-transform:uppercase; }
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,
/* ID selector for the 3 major division of the document */
#header { font-size:16px; align:center; font-style:bold; }
#header h1 { text-transform:uppercase; } /* contextual selector */
#content { font-size:14px; align:justify; }
#content h3 { color:#FF0000; text-decoration:underline; } /* red, underline */
#footer { font-size:12px; align:right; }
#footer p { color:#00FF00; text-decoration:none; } /* green, not underline */
<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:
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.,
The above rules will add a double-quote (Unicode 0022H) in before and after all elements having
class="title". Take note that these selectors generate contents!
Another Example: To change the bullet of an unordered list. Try it out.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test ::before</title>
<style>
ul {
list-style-type: none;
}
ul > li::before {
content: "";
display: inline-block;
margin-right: 10px;
height: 9px;
width: 9px;
background: linear-gradient(blue, lightblue);
}
</style>
</head>
<body>
<ul>
<li>A for Apple</li>
<li>B for Boy</li>
</ul>
</body>
</html>
::selection (CSS3): Select the user-selected-text on the screen. You are only allow to set the color
and background-color properties in the selector. For example,
p::selection { /* selected text in any paragraph */
color: red;
background-color: black;
}
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.
<style>
input:in-range {
border: 2px solid blue;
}
:not(input:in-range) {
border: 2px solid red;
}
</style>
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%. I prefer the decimal form over the hex triplets as it is easier to
visualize the values.
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.
html {
font-size: 16px; /* base measurement for rem (CSS3) */
}
p {
font-size: 1rem; /* relative to root html element */
width: 80%; /* 80% of the parent's width */
margin: 0.5em 2em; /* relative to current font-size */
border: 5mm; /* absolute millimeters */
padding: 0;
line-height: 140%; /* 1.4 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).
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,
h6 {
font-size: 1.2rem; /* 1.2 times of the <html> font-size */
width: 80%; /* 80% of the parent's width */
margin: 0.5em 1.2em; /* relative to the current font's letter 'm' */
padding: 10px; /* 10 logical 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.
Recommendation
Define a font-size for <html>.
Use rem for font-size of other elements - relative to <html>.
Use em for other properties such as margin and padding, which is relative to the current font-size.
Use other relative measurement such as % if appropriate. Avoid absolute measurements.
For example,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Measurement Test</title>
<style>
html {
font-size: 16px;
}
input[type="button"] {
font-size: 1rem;
padding: 0.4em 2.5em;
}
input[type="text"] {
font-size: 1rem;
padding: 0.4em; /* same top/bottom as other input elements for proper alignment */
}
input[type="number"] {
font-size: 1rem;
padding: 0.4em; /* same top/bottom as other input elements for proper alignment */
}
</style>
</head>
<body>
<input type="button" value="Button">
<input type="text" value="This is a Text Box">
<input type="number" value="5" min="0" max="10" size="2">
</body>
</html>
8.3 CSS Box Model and Properties margin, border, padding and Content
Area
Recall that HTML defines two kinds of elements: block element and inline element.
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.
1. The content area contains the texts, image, or child elements.
2. The padding is the space between the content area and the border. It clears an area outside the
content area. It has the same background as the content area.
3. The border goes between padding and margin. You can set a color and a style (such as solid, dash,
dotted) to the border.
4. The margin is the space outside the border (to another element). It clears an area outside the border.
The margin does not have a background, and is totally transparent.
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:
#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.
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.
Google Fonts
"Google Fonts" @ https://fonts.google.com/ is a huge set of high-quality, free and open-source fonts. It is
certainly the choice of the fonts today.
To use particular fonts, e.g., "Roboto" and "Roboto Mono", you can either:
1. Add a <link> to CSS (in your HTML's HEAD section, e.g.,
<link rel="stylesheet" href='https://fonts.googleapis.com/css2?family=Open+Sans&fami
2. Use a @import in your CSS (you need not update all your HTML pages):
@import url('https://fonts.googleapis.com/css2?family=Open+Sans&family=Roboto+Mono&d
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]
[TODO: More]
9. More HTML
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.
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).
9.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.
frameborder: sets to 1 to show the border, 0 to suppress.
scrolling: "yes" to show scrollbars and allow scrolling; "no" to suppress scrolling; and "auto" to let
the browser to decide (e.g., auto-hide).
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]
<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:
<base href="http://www.aaa.com/bbb/index.html" />
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:
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.
// HTML5
<meta charset="utf-8" />
The server will include this response header in the response message, when the page is downloaded:
Rules:
1. The name of the variables shall begin with two dashes (--), e.g., --main-bg-color.
2. To reference the variable, use var(--varname).
3. To define global-scope CSS variables, place them in the :root pseudo-class.
For examples,
:root {
--dark-theme-bg-color: black;
--dark-theme-color: white;
}
......
body {
background-color: var(--dark-theme-bg-color);
color: var(--dark-theme-color);
......
}
You can use the property position to alter the position of block elements.
Each element has a natural location inside a page's flow, in the order read in by the browser. By default
(position:static), 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 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-flow position (position:relative).
For non-static positioned elements, the new position is specified via top, left, bottom, right, width,
height properties:
top|left|bottom|right: n|n%|auto: Set the distance from the edge of this element to the
corresponding edge of the containing block.
width|height: n|n%|auto: Set the width and height of this block element.
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|overflow-x|overflow-y: auto|hidden|scroll|visible|inherit: Specify how to
handle content overflowing the block's width/height.
overflow-wrap: normal|break-word|inherit: specify whether or not the browser can break
lines with long words, if they overflow the container.
position:static (default)
The default position:static positions the element according to the normal flow of the page, in the
order that is read by the browser. Properties top, right, bottom, left has no effect for static.
position:relative
Move the element relative to its normal-flow position. The original space occupied by this element is
preserved. The surrounding elements are not affected. For example,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test CSS "position" Property</title>
<style>
div.up {
position: relative; /* relative to normmal-flow position */
top: -20px; /* from the top of normal-flow */
left: 30px; /* from the left of normal-flow */
}
div {
height: 80px;
width: 200px;
background-color: lightgray;
margin: 5px;
}
</style>
</head>
<body>
<div>Division 1</div>
<div class="up">Division 2</div>
<div>Division 3 (Division 2 preserves its space)</div>
</body>
</html>
position:absolute
Position the element relative to the first non-static ancestor element; or <body> if no such element is
found. Absolute-positioned element is taken out from the normal flow, as if it does not present.
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,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test CSS "position" Property</title>
<style>
#left-panel {
position: absolute;
top: 10px; /* from top edge */
left: 10px; /* from left edge */
width: 200px;
height: 600px;
background-color: lightblue;
}
#main-panel {
position: absolute;
top: 10px; /* from top edge, same as left-panel */
left: 220px; /* from left edge 10+200+10 */
width: 560px;
height: 600px;
background-color: lightgray;
}
</style>
</head>
<body>
<div id="left-panel">Left Panel</div>
<div id="main-panel">Main Panel</div>
</body>
</html>
position:fixed
The element is fixed at the position relative to the browser's window, and it does not scroll away. The
position is defined in top, left, bottom, right (or width and height) properties. Fixed-positioned
element is taken out of the normal flow, as if it is not present.
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test CSS "position" Property</title>
<style>
#left-panel {
position: absolute;
top: 10px; /* from top edge */
left: 10px; /* from left edge */
width: 200px;
height: 600px;
background-color: lightblue;
}
#main-panel {
position: absolute;
top: 10px; /* from top edge, same as left-panel */
left: 220px; /* from left edge 10+200+10 */
width: 560px;
height: 600px;
background-color: lightgray;
}
#fixed-panel {
position: fixed;
top: 50px;
left: 100px;
width: 200px;
height: 200px;
background: lightgreen;
z-index: 200; /* larger z-index is on top */
}
</style>
</head>
<body>
<div id="left-panel">Left Panel</div>
<div id="main-panel">Main Panel</div>
<div id="fixed-panel">Fixed Panel (does not scroll away)</div>
</body>
</html>
10.4 CSS float and clear Property - Floating an Element Left or Right
float: left|right|none
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;
margin-right: 10px; /* add margin-right for float:left */
width: 120px;
height: 100px;
}
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
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;
}
On the other hand, display:inline can be used to display a block element inline. For example,
li { /* display this block element inline without line break */
display:inline;
}
inline-block: blend the element in with the flow of the text, while allowing us to use padding,
margin, height and similar properties which has no visible effect on inline elements.
none: will NOT be displayed and not taking up space (vs. visibility:hidden would not display the
element but the element still take up space)
list-item: display the element as if it is a <li>.
table, table-row, table-cell: to display the element (<div>) as <table>, <tr>, <td>.
grid: display in a grid, for example,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test grid layout</title>
<style>
#main {
display: grid;
grid-template-columns: 100px 50px 100px;
grid-template-rows: 100px 100px;
}
section {
height: 50px;
width: 80px;
background-color: lightgray
}
#main #section1 {
grid-column: 1; /* column numnner */
grid-row: 1; /* row number */
}
#main #section2 {
grid-column: 2;
grid-row: 1;
}
#main #section3 {
grid-column: 1;
grid-row: 2;
}
#main #section4 {
grid-column: 3;
grid-row: 2;
}
</style>
</head>
<body>
<main id="main">
<section id="section1">Section 1</section>
<section id="section2">Section 2</section>
<section id="section3">Section 3</section>
<section id="section4">Section 4</section>
</main>
</body>
</html>
visibility: hidden|visible: 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.
Example: [TODO]
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan ([email protected]) | HOME