Basic HTML and CSS Basic
Basic HTML and CSS Basic
| HOME
TABLE OF CONTENTS (HIDE) 1. Introduction 2. HTML/CSS Online Tutorials, References and Specifications 3. Introduction to HTML
3.1 Basic Layout of an HTML Document 3.2 HTML Tags (aka HTML Elements) 3.3 Basic HTML Tags 3.4 Block-Level Tags (aka Block Elements) 3.5 HTML Comment <!-- ... --> 3.6 Character-Level Tags (Inline Elements) - Logical Style vs. Physical Style 3.7 Entity References for Reserved & Special Characters 3.8 Lists - Ordered List, Unordered List and Definition List 3.9 Tables 3.10 Anchor and Link <a>...</a> 3.11 Using Images
4. Introduction to CSS
4.1 Why Style Sheet? 4.2 What is a Style Sheet? 4.3 A Sample CSS Style Sheet 4.4 CSS Syntax 4.5 Types of Styles 4.6 Using CSS for Styling 4.7 Tag's title Attribute 4.8 Types of CSS Selectors 4.9 Inheritance 4.10 Resolving Conflicting Rules: Specificity and Location 4.11 Firebug Plug-in for Firefox 4.12 Validating CSS Files 4.13 Style Properties 4.14 Color Properties 4.15 Length Measurements 4.16 Box Model - Margin, Border, Padding and Content Area 4.17 Font Properties 4.18 Text Properties 4.19 Background Properties 4.20 List Properties 4.21 Table Properties 4.22 Image Properties
5. More HTML
5.1 5.2 5.3 5.4 5.5 Image Maps Frames Embedding Programs Standard Attributes - id, class, style, lang, title, dir HEAD Section's Tags
6. More CSS
6.1 6.2 6.3 6.4 Positioning the HTML Block-Level Elements Floating an Element Left or Right Other Miscellaneous Properties CSS Templates & Comprehensive Examples
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.
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/she has to be concerned about both the contents and appearances at the same time, and can loss 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.
3. Introduction to HTML
What is HTML (HyperText Markup Language)? 1. HTML is the language for publishing web pages on the WWW (World-Wide Web, or WorldWide Wait?). 2. HTML is a Document Description Language (aka Document Markup Language). HTML is NOT a programming language like C/C++/C#/Java, that is used to implement programming algorithm. 3. An HTML document is a text document, and it is human-readable.
The W3C (World-Wide Web Consortium) @ www.w3c.org maintains the HTML and CSS specifications (and many other web technologies). The most commonly-used is "HTML 4.01 (1999)" (@ http://www.w3.org/TR/html401/) and "XHTML 1.0 (2002)" (@ http://www.w3.org/TR/html/). After releasing HTML 4.01, W3C proceeded to work on XHTML, which is cleaner and stricter, and was meant to replace the HTML. However, XHTML does not seen to gain acceptance and XHTML 2.0 is going nowhere. W3C is back to the HTML. It recently released the HTML 5 draft specification (@ http://www.w3.org/TR/html5/) in May 2011. The interesting thing about web standard is that there are too many! Everyone defines and uses its own standard! HTML uses markup tags (called elements in XHTML/XML terminology), 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. HTML documents can be created by a wide range of tools, from simple plain text editors (such as NotePad, NotePad++) to sophisticated WYSIWYG authoring tools (e.g., DreamWeaver). The purpose of a markup language is to relieve the content provider from worrying about the actual appearance of the document. The author merely indicates (via markup tags) the semantic meaning of the words and sentences (such as paragraph, heading, emphasis, and strong), and leave it to the browser to interpret the markups and render the document for display on the screen. In other words, it allows the separation of content and presentation. The content provider focuses on the document contents, while the graphic designer concentrates on the view and presentation. 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>, <b>, <i>, <u>) 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 HTML 5 new tags such as <header>, <footer>, <section>.
Let's go thru the HTML syntaxes. Do not attempt to start designing your website until you finish the CSS.
12</body> 13</html>
1. In the HEAD section, the <title>...</title> tag provides a descriptive title to the page. The browser renders the title on its "title" bar. 2. In the BODY section: a. The <h1>...</h1> tag marks the enclosing texts as Level-1 Heading. There are six levels of heading in HTML, from <h1>...</h1> (largest) to <h6>...</h6>. Line 10 uses a <h3>...</h3> (heading level-3). b. The <hr /> standalone tag (which does not enclose text) draws a horizontal rule (line). c. The <p>...</p> tag marks the enclosing texts as a paragraph. <p> is the most frequently-used tag in HTML.
d. The nested <strong>...<strong> tag (under the <p>...</p> tag) specifies "strong emphasis" (to be displayed in bold); and the nested <em>...</em> tag specifies "emphasis" (to be displayed in italic). Use a text editor (I recommend NotePad++) to enter the above HTML codes and save as "myFirst.html". Open the file in a browser (such as Firefox, IE, Chrome, Safari, Opera), by double-
clicking the file, or drag and drop the file into the browser, or through the browser's "File" menu Open File... "Browse" and select the file.
3. Standalone Tag (aka Empty Tag, Bodyless Tag): A standalone tag does not enclose content but is used to markup 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. Standalone tag should be closed with a trailing '/' in the opening tag (for XHTML/XML compliance). A space may be needed before the '/'. For examples:
4. <br /> 5. <hr /> <img src="logo.gif" />
Alternatively, you can also close a standalone tag with a matching closing tag (which is cumbersome but consistent in syntax to the container tag), e.g.,
<br></br> <hr></hr> <img src="logo.gif"></img>
2. Blanks, tabs, new-lines and carriage-returns are collectively known as white spaces. "Extra" white spaces are ignored. That is, only the first white space is recognized and displayed. For example,
3. <p>See 4. 5. 6. how the tabs and are ignored by the extra white spaces,
line-breaks
browser.</p>
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 layout 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. 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.</p>
W3C Recommends that "at a minimum, every HTML document must at least include the descriptive title element." Other tags in the HEAD section include: <base>, <link>, <meta>, <script>, and <style>, which shall be discussed later.
Attributes "src", "width" and "height" are used in the <img> tag to specify the source-url, and width/height of the image displayed area. Some of the attributes are mandatory (e.g., the "src" attribute 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; 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 shall be enclosed in single or double quotes, for XHTML/XML compliance. The name="value" pairs are separated by space.
<tag-name attName1="attValue1" attName2="attValue2" ...> ... </tag-name>
For example:
<html> <body text="blue" bgcolor="lightblue" link="green" vlink="red" alink="yellow"> <p>Hello</p>
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).
Paragraph <p>...</p>
Function: When the browser reads a <p> tag, it breaks to a new line, and skips some white spaces. For example,
<p>This is a paragraph of texts.</p>
Older HTML documents often omit the closing </p>, which is a bad practice, not recommended, and disallowed in XML/XHTML.
paragraph
}</pre> public class Hello { public static void main(String[] args) { System.out.println("Hello"); } }
Without the <pre> tag, the entire program will be shown in one single line.
HTML comments are enclosed between <!-- and -->. Comments are ignored by the browser. You need to look into the HTML codes ("view source") to read them. Comments are extremely important in programming to explain and document a section of programming codes and logic. HTML documents are textual and self-explanatory, comments are less important (but still nice to have) to describe the various part of the documents.
3.6 Character-Level Tags (Inline Elements) - Logical Style vs. Physical Style
Logical-style formatting tags specify the semantic meaning (e.g., strong, emphasis, code); whereas physical-style formatting tags define the physical or typographical appearance (e.g., bold, italic, teletype). Logical styles should be used instead of physical styles. This is because physical styles deal with the appearance, which should be defined in style sheet, so as to separate the content and presentation.
Logical-Style Tag
<strong>...</strong> <em>...</em> <code>...</code> <q>...</q> <ins>...</ins> <del>...</del> <def>...</def> <cite>...</cite> <kbd>...</kbd> <samp>...</samp> <abbr>...</abbr>
Meaning
strong emphasis (bold) emphasis (italic) program code (fixed-width monospace font) quotation (enclosed in curly double quotes) inserted deleted definition (bold or bold-italic) citation (italic) Keyboard (fixed-width monospace font) sample text (fixed-width monospace font) abbreviation (dotted underline, with title as tool tip) acronym (dotted underline, with title as tool tip) address variable (fixed-width or italic)
The commonly-used tags are: <strong> (displayed in bold), <em> (displayed in italics), and <code> (use monospace font for programming codes). Example:
<p>Lorem sed do <q>curly quoted</q>, incididunt consectetur ut labore et adipisicing dolore magna elit, aliqua.
<cite>citation</cite>
Ut enim ad minim veniam, quis <samp>sample</samp> exercitation ullamco laboris nisi ut <code>code</code> ex ea <kbd>keyboard</kbd> consequat. Duis aute irure dolor in reprehenderit in <def>definition</def> velit esse cillum dolore eu fugiat nulla pariatur. Excepteur <ins>insert</ins> occaecat <del>delete</del> non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
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 definition 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.
<abbr> and <acronym>
The contents are shown with a dotted underline. By including an attribute title="fulltext" to the <abbr> and <acronym> opening tag, the full text will be shown as tool tip, when you point your mouse pointer to the element. For example,
<p>Lorem <abbr title="abbreviation">abbr</abbr> dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor <acronym title="Hypertext Markup Language">HTML</acronym> ut labore et dolore magna aliqua.</p>
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 applicable to almost all of the HTML tags (e.g., <p>, <h1> to <h6>, <img>).
Physical-Style Tag
<b>...</b> <i>...</i> <u>...</u> <big>...</big> <small>...</small> <sup>...</sup> <sub>...</sub> <tt>...</tt> bold italic underline large font small font
Meaning
the HTML reference - I like the arrows, greek symbols, and the mathematical notations). Entity reference is case sensitive.
Character
" < > & non-breaking space (degree) " < > &
Entity Reference
→ ⇒ ↔ ⇔ ° © ® € ¢ ¥ ˜ × ± ∞ π Π σ Σ ω Ω ≥ ≤ ≡ ≈ ⊂ ⊃ ⊆ ⊇ ∈
You need to memorize the first five: " ("), < (<), > (>), & (&) and ( ).
This paragraph contains special character " <, > and & and those between.
words
have
more
spaces in
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:
<p>An OMO web designer must master:</p> <ul> <li>Hypertext Markup Language (HTML)</li> <li>Cascading Style Sheet (CSS)</li> <li>HyperText Transfer Protocol (HTTP)</li> <li>Apache HTTP Server</li> </ul>
Output of the example: An OMO web designer must master: Hypertext Markup Language (HTML) Cascading Style Sheet (CSS) HyperText Transfer Protocol (HTTP) Apache HTTP Server
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>
Example:
<p>These are some of the commonly-encountered web protocols:</p> <dl> <dt>HTTP</dt><dd>HyperText Transfer Protocol</dd> <dt>FTP</dt><dd>File Transfer Protocol</dd> <dt>SMTP</dt><dd>Simple Mail Transfer Protocol</dd> <dt>POP</dt><dd>Post Office Protocol</dd> <dt>PPP</dt><dd>Point-to-point Protocol</dd> <dt>SLIP</dt><dd>Serial Line Internet Protocol</dd> </dl>
These are some of the commonly-encountered web protocols: HTTP HyperText Transfer Protocol FTP File Transfer Protocol SMTP Simple Mail Transfer Protocol POP Post Office Protocol PPP Point-to-point Protocol SLIP Serial Line Internet Protocol 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
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: The topics covered are: HyperText Markup Language (HTML)
o o o
A markup language based on SGML Used to create web pages Maintained by W3C Used to define presentation style for web pages Also maintained by W3C
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: 1. XML: Extensible Markup Language a. Based on SGML b. Maintained by W3C 2. DOM: Document Object Model 3. SAX: Simple API for XML
3.9 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 avoid. 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. The tags used by table are:
<table>...</table>: contains the entire table. <tr>...</tr>: contains a row. <th>...</th> and <td>...</td>: contain a header cell and a data (detail) cell respectively. <caption>...</caption>: specifies a caption. <thead>...</thead>, <tbody>...</tbody>, and <tfoot>...</tfoot>: for table header,
column 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>
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!).
<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>
Example 2:
<table> <tr> <td colspan="2" rowspan="2">11111</td> <td>22222</td> </tr> <tr> <td>33333</td> </tr> <tr>
11111 44444
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.
<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
<a>...</a>
A hypertext-link (or hyperlink, or link) allows users to: 1. navigate to a different document. 2. navigate to an "Anchor Point" (bookmark) in the current document or another document, or 3. request other Internet resources (such as e-mail). The anchor tag <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" (bookmark) within a document, to be targeted by other hyperlinks. Named anchors are useful for long documents.
A URL uniquely identifies a piece of resource over the Internet. A URL is made up of 4 parts as follows:
Protocol://hostname:port/path_and_filename
1. Protocol: e.g., http, ftp, mailto, file, telnet and others. 2. Server hostname (e.g., www.w3c.org) or IP address (e.g., 127.0.0.1). The DNS (Domain Name Service) translates a domain name to an IP address. 3. Port number (optional): the TCP port number on which the server application is running. The default TCP port number is used if port number is omitted from the URL. For example, default TCP port number 80 will be used for HTTP, 21 for FTP. 4. Directory path and file name: Unix-style forward-slash '/' is used as the path separator (instead of Windows-style back-slash '\'). Directory path and filename of the URL are case sensitive. Examples of URLs are:
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
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.
The <a name="anchorName"> was used in older HTML files. The now-preferred method is to use <a id="anchorName"> to set up an anchor point. To reference a named anchor, use a URL in the form of http://hostname:port/documentname#anchorName, by placing a pound sign (#) in front of the anchorName. Example1: A named anchor "eg_2" is set at heading "Example 2" as follows:
<h3><a id="eg_2">Example 2</a></h3>
To set up a link targeting this anchor in the same HTML page, place a pound sign "#" in front of the anchor name as follows:
Go to <a href="#eg_2">Example 2</a>
Example 2:
<h2><a id="eg_1">Example 1</a></h2> ...... ...... <h2><a id="eg_2">Example 2</a></h2> ...... ...... Jump to <a href="#eg_1">Example 1</a> ...... Jump to <a href="#eg_2">Example 2</a>
The above syntax is much neater than using <a id|name="anchorName"> to create an anchor point, and is recommended. However, it might not work in the older browsers. Take note that the attribute id is used extensively in CSS (to be discussed later) and JavaScript.
Example:
<img src="logo.gif" width="200" height="100">
Attributes:
src="imageUrl": mandatory, gives the URL of the image. alt="text": 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. provide the tool tip text.
title="tooltip-text": the attribute title is applicable to most of the HTML tag for you to
Image as Hyperlink
To use an image as a hyperlink, put the image tag <img> between <a herf=...> and </a>. For example:
<a href="http://abc.com/"> <img src="logo.gif" alt="logo Image" 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).
4. Introduction to CSS
4.1 Why Style Sheet?
The original aim of HTML is to let the content providers concentrate on the content of the document and leave the appearance to be handled by the browsers. Authors markup the document content using markup tags (such as <p>, <h1>, <ul>, <table>, <img>) to indicate its semantic meaning ("This is a paragraph", "This is heading Level 1", "This is an unordered list", "This is a table", "This is an image"). The browser then decides on how to display or present the content on the browser's window. However, HTML has gone out of control in the early years. Tons of 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 content. It is important to separate the content and presentation of a document. Document contents are provided by the document authors or content providers, whereas presentation is usually done by a graphic designers. The W3C (World-Wide Web Consortium @ www.w3c.org) responded to the need of separating document's content and presentation by introducing a style sheet language called CSS (Cascading Style Sheet). CSS can be viewed as an extension (or companion) of HTML, which allows web graphic designer to spice up the web pages, so that the content providers can focus on the document contents. There are two CSS levels: 1. CSS Level 1 (1996): CSS1 laid the ground work, introduces the selectors and most of the properties. 2. CSS Level 2 (1998) / 2.1 (2006): CSS2 added new features such as targeting devices and printers, and absolute positioning. CSS2.1 (@ http://www.w3.org/TR/CSS2/) lightly touchup CSS2. 3. CSS Level 3: Still in progress. CSS is humongous!!! Most of the browsers today have yet to fully support CSS 2, which was published in 1998 and lightly updated to Level 2.1 in 2006?!
A Style Sheet is a collection of style rules that can be applied to a selected set of HTML elements. A style rule is used to control the appearance of HTML elements such as its font properties (e.g., type face, size, weight), color properties (e.g., background and foreground colors), alignment, margin, border, padding, and positioning. This is the same as the style in any publishing software like WinWord or LaTex. The word "cascading" means that multiple style rules can be applied to the same HTML element simultaneously. The browser follows a certain "cascading order" in finalizing a style to format an HTML element in a predictable fashion.
font-family: "Trebuchet MS", "Segoe UI", Helvetica, Tahoma, Arial, Verdana, sansserif; color: red; background: black; font-style: italic; font-weight: bold; text-align: center; } p { text-align: justify; font-size: 14px; color: #000000; } /* black */
CSS is a language by itself. It has its own syntax, which is totally different from HTML! (How many syntaxes you have to know to program the web?!). A CSS style sheet is a collection of style rules: 1. A style rule consists of a selector which selects the HTML elements it operates upon (e.g., <body>, <p>, <ul>), and a list of style property names and values enclosed in braces { }, as follows:
2. selector { 3. 4. 5. } property-name-1: property-value-1-1, property-value-1-2, ... ; property-name-2: property-value-2-1, property-value-2-2, ... ; ......
For example,
body { /* Apply to <body> and possibly its descendants */
font-family: "Segoe UI", Tahoma, Helvetica, Arial, Verdana, sans-serif;; font-size: 14px; margin: 10px, auto, 10px, auto; padding: 0; } /* top right bottom left */
The 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 the descendents, unless it is overridden by another style definition. 6. The property name and value are separated by a colon ':' in the form of name:value. Multiple values are separated by commas ',' or whitespace. Values containing space must be quoted, e.g., "Times New Roman" or 'Times New Roman'. 7. The property name:value pairs are separated by semicolon ';'. You can omit the last semicolon ';' before the closing brace '}'. But I recommend that you keep it, so that it is easier to include new entries without a missing ';'. 8. Extra whitespaces (blank, tab and newline) are ignored. 9. If the same styles are applicable to more than one tags, the selectors can be grouped together in one single rule, separated by commas ','. For example, the following rule apply to HTML tags <h1> to <h6>:
10. h1, h2, h3, h4, h5, h6 { 11. text-align: center;
12.
font-family:
"Trebuchet
MS",
"Segoe
UI",
Helvetica,
Tahoma,
Arial,
Verdana, sans-serif; }
13. Comments can be inserted inside the sheet sheet enclosed between /* and */. (The endof-line comment // does not work in CSS?!) Take note that CSS and HTML have different syntaxes. In HTML, tags' attributes uses '=' to separate the name and value pair, in the form of name="value"; attributes are separated by spaces. For example,
<img src="logo.gif" height="10" width="20">
Inline Styles
To apply inline style to an HTML element, include the list of style properties in the style attribute of the 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>
The scope of an inline style is limited to that particular tag. Inline style defeats the stated goal of style sheets, which is to separate the documents 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.
Embedded Styles
Embedded styles are defined within the <style>...</style> tag in the HEAD section. For example,
<!DOCTYPE html> <html> <head> <style type="text/css"> body h2 { background-color:cyan } { color:white; background-color:black }
p.cursive { font-size:18px; font-family:cursive } p.f20px </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> { font-size:20px }
The scope of the embedded styles is the current HTML document. Embedded styles separate the presentation and content (in the HEAD and BODY sections) and can be used if page-to-page uniformity is not required. That is, this set of styles is used for only one single page!? (I use embedded style in this article for illustration, but you should use external style in production.)
The attribute type="text/css" in the <style> opening tag is not needed in HTML 5.
This HTML document references the external style sheet via the <link> tag in the HEAD section:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="testExternal.css"> </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>
The main advantage of external style sheet is that the same styles can be applied to many HTML pages to ensure uniformity in presentation for your entire website. External style sheet is the nowpreferred approach. Note: HTML 5 does not requires the type="text/css" attribute in <link> tag.
To use CSS to style your website and to get the full benefit of CSS, you need to properly structure your web pages.
CSS Selector
As mentioned earlier, a CSS selector is used to select a group of HTML elements to apply the defined styles. The selection can be carried out via: 1. HTML tag name, e.g., body, p, ol, table, and div. 2. HTML tag's id attribute, e.g., <div id="header">. 3. HTML tag's class attribute, e.g., <span class="highlight">. 4. others.
HTML Tag Attributes id=" idValue " and class=" classname "
All the HTML tags supports two optional attributes: id="idValue" and class="className". 1. You can assign an id="idValue" 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 is used by CSS as well as JavaScript to select the element. For example,
2. <div id="header"><h1>Header Section</h1></div> 3. <div id="content"><h1>Content Section</h1></div> 4. <div id="footer"><h1>Footer Section</h1></div>
5. 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. The class attribute is primarily used by CSS to apply a common set of styles to all the elements of the same class. (HTML 5 can also selects elements based on class name). For example,
6. <p class="highlight">A highlighted paragraph</p>
values</p>
Example
The following HTML page is divided into three divisions, with unique id's of "header", "content" and "footer" respectively. Selected texts are marked with the <span> tags, with class of "green" and "blue".
<html> <head> <style> /* style-definitions - see below */ </style> </head>
<div 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> </div>
CSS Tag-name, Id and Class Selectors Tag-name Selector (or Tag Selector or Element Selector): A CSS tag-name selector
selects HTML elements based on the tag-name, e.g.,
/* tag-name selector */ h2 { background-color:black; color:white; text-align:center; }
ID-Selector: You can use CSS to set the display style for each of the three divisions, via the socalled id-selector. A CSS id-selector begins with a '#' followed by the id's value. It selects a specific element. For example,
/* id-selector (id value must be unique) */ #header #content #footer { font-size:18px; color:cyan; } { font-size:14px; color:black; } { font-size:12px; color:orange; }
Class Selector: CSS also provides the so-called class-selector for selecting elements of the same
class value. A CSS class-selector begins with a '.' followed by the classname. For example,
/* class-selector (class value needs not be unique) */ .green { color:green; text-decoration:underline; }
.blue
{ color:blue;
Note: Because of the wide popularity of using <div>'s with id="header", id="footer" to organize an HTML page, HTML 5 defines new tags such as <header>, <footer>, <section>, <article>, <nav> to help you to better organize the HTML page.
4.7 Tag's
title
Attribute
Besides the id and class attributes, you can also assign an attribute title="label" to an HTML tag. The title's label shows up as tool tip when you points your mouse pointer at the element.
Selector)
A tag-name selector selects all elements of the given tag-name. The syntax is:
tag-name { style-definitions }
Example:
h2 { background-color:black; color:white; } S1, S2 - Group Selector
You can apply the same style definitions to multiple selectors, by separating the selectors with a commas ','. The syntax is,
selector-1, selector-2, ... { style-definitions }
Example:
h1, h2, h3 { background-color:black; color:white; } T1 T2 - Descendant Selector
You can define a style rule that takes effect only when a tag occurs within a certain contextual structure, e.g., descendent, 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). For 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. Note: In T1 T2 { ... }, T2 is a descendant of T1 regardless of the generation.
T1 > T2 - Child Selector
The style is applied to tag T2, only if it follows immediately after tag T1. T1 and T2 are siblings in the same hierarchical level.
.C - Generic Class Selector
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. For example,
.f14px_i { font-size:14px; font-style:italic; } .f16px_b { font-size:16px; font-weight:bold; } .red { color:red; } .underline { text-decoration:underline; } <p class="f14px_i">Text is 14px and italic.</p> <p class="f16px_b">Text is 16px and bold.</p> <p class="red">Text is in red.</p> <h5 class="red">Text is in red.</p>
Take note that the class attribute may contain multiple values. This means that you can apply multiple class style rules to an HTML tag. 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> T.C - Class Selector
The selector T.C selects all tag-name T with classname of C. This is a restricted form of the generic class selector, which applies to the specific tag-name only.
An HTML tag (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 tag. For example,
p p.red default) */ p.blue default) */ h1, h2, h3 { color:green; } h3.white default) */ h3.upper { text-transform:uppercase; } { color:white; } /* default style for <h1>, <h2> and <h3> tags */ /* applicable to <h3 class="white"> tags (override { color:blue; } /* applicable to <p class="blue"> tags (override { color:black; } { color:red; /* default style for all <p> tags */ } /* applicable to <p class="red"> tags (override
<p>This paragraph is in black (default style)</p> <p class="red">This paragraph, of class="red", is in red.</p> <p class="blue">This paragraph, of class="blue", is in blue.</p> <h2>H2 in green (default style)</h2> <h3>H3 in green (default style)</h3> <h3 class="white upper">This H3, of class="white", is in white</h3>
Note: Do NOT start a class-name with a number! (This is the same restriction for identifiers in most of the programming languages.)
#D - ID Selector
The id-selector, begins with a '#' followed by the id's value, select a specific element with the given unique id value (or none). 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 parts of different styles. For example,
/* ID selector for the 3 major division of the document */ #header #header h1 #content { font-size:16px; align:center; font-style:bold; } { text-transform:uppercase; } { font-size:14px; align:justify; } /* contextual selector */
#content h3 { color:#FF0000; text-decoration:underline; } /* red, underline */ #footer #footer p { font-size:12px; align:right; } { 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> T#D - Tag's ID Selector
Same as above but only if the id is defined under the tag. Since id value is supposed to be unique, this serves more as proper documentation.
* - selector (Universal Selector)
The * universal selector selects ALL the tags in the document. For example,
* { margin:0; padding:0; } /* all tags have margin and padding of 0 */
CSS pre-defines a number of pseudo-classes for anchor tag <a>, namely, a:link (unvisited link), a:visited (visited link), a:focus (on focus via tab key), a:hover (mouse pointer hovers over), a:active (clicking the link). Note that colon ":" is used to identify pseudo classes instead of "." for ordinary classname. For example,
a a:link { font-size:14px; } { color:red; } /* all <a> tags */ /* unvisited link */ /* visited link */
a:hover a:active
{ color:blue; } { color:black; }
Note: The order is important for anchor pseudo-classes in applying styles. It shall be linkvisited-focus-hover-active (LVFHA). It is called pseudo-class, as it sub-divide the <a> tag into four sub-classes that cannot be marked out manually. You can further restrict the selection via a.classname:pesudo-class. 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; } <a class="green" href="http://www.aaa.com">www.aaa.com</a> <a class="blue" href="http://www.bbb.com">www.bbb.com</a> <a href="http://www.ccc.com">www.ccc.com</a>
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.,
a #header a:hover #footer a:hover { color:black } { color:blue } /* default for a:link, a:visited, a:active */
{ color:green }
These pseudo classes is often used with <a> tag. But some of them, such as :hover, :focus, :active can also be applied to other elements, e.g., <p>, <li>, etc.
The selector p:first-line and p:first-letter select the first line and the first letter of the <p> elements. They are called pseudo-elements because they select a portion of an element that is hard to be marked out (e.g., first line). They can be applied to many tags such as <p>, <em>, <strong>, <li> and etc. You can restrict the selection by applying id or class. For example, p.intro:first-line, em.special:first-letter.
T[att] and T[att="value"] - Attribute Selector
The attribute selector selects elements that possess the given attribute (regardless of value), or the given attribute-value pair. Example: [TODO]
4.9 Inheritance
Many (but not all) CSS properties, such as color properties, affect not only the elements selected by the selector, but also inherited by their descendants. Some properties (such as border, margin, padding, width and height) are not inherited. You can use a special property value called " inherit" to force the inheritance. For example,
<!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 <em> is nested under the <p> tag, the border property is not inherited from the parent element. 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.
The Law of Specificity states that "the more specific the selector, the stronger the rule". For example,
<!DOCTYPE html> <html> <head> <style> p { color:black; } }
p.red { color:red;
p#id1 { color:yellow; background:lightblue; } p#id2 { color:blue; } /* Override the color property in the earlier rule */
<p id="id1">Paragraph with "id1" - green</p> <p id="id2">Paragraph with "id2" - blue</p> <p class="red">Paragraph of class "red" - red</p> <p id="id1" class="red">Paragraph with "id1" and class "red" - green</p> <p>Paragraph without id and class</p> </body> </html>
The p selector is the most general, which selects all the <p> elements; the p.red selects a group of <p> elements with attribute class="red"; the p#id1 and p#id2 selects only one element each with the unique id value. The id-selector is the most specific (and takes precedence); followed by classselector; and followed by general tag-name selector. 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 selector for id1, the later overrides the color property defined earlier. The inline style (applied to a specific tag) overrides the embedded style and external style sheet. For embedded style and external style sheet, the order of <link> (for external style sheets) and <style> (for embedded style) tags in the <head> section determine the precedence. You may place <link> before or after <style> and there could be multiple <link> tags for multiple external style sheets. Again, the last rule that read in by the browser takes effect.
You can override all the cascading rules by appending a special value "!important", e.g.,
p { color:blue !important; background-color:grey; } p { color:red; background-color:lightblue; } <p>color is blue but background is lightblue</p> /* color cannot be overridden */ /* override background-color */
color:
#rrggbb|rgb(r,g,b)|rgba(r,g,b,a)|color-name
background-color: name|transparent
#rrggbb|rgb(rrr,ggg,bbb)|rgba(r,g,b,a)|color-
There are two types of length measurements: relative (to another length properties) and absolute (e.g., inches, centimeters, millimeters). The absolute units are:
in (inch) cm (centimeter) mm (millimeter) pt (point): 1 inch has 72 points. 1pt is 1/72 in 0.014in 0.35mm. pc (pica): 1 pica is 12 points. 1 inch has 6 picas. 1pc 1/6 in 0.17in 4.2mm. pc is not
commonly used.
For example, suppose that you are using a 17-inch (diagonal) monitor with a resolution of 1024x768. The screen width is about 12.5in. At that resolution, 16px is about 16x12.5/1024 inch 0.2in 0.5cm. Note that pt (point) is absolute (because 72 pt is 1 inch) but px (pixel) is relative, which depends on the display devices.
same property of the parent element. For example, table { width:80% } set the table's width to 80% of the width of the parent (probably a <div> or <body>).
em: the width of the letter 'm' of a referenced font, generally, the current font. For example, margin:2em means that the margins are twice the current (referenced) font-
size. However, if em is used to set the font-size property, it needs to find a reference. In this case, it is referenced to the parent's font-size. For example, p { font-size:1.2em; } sets the font-size of <p> to 1.2 times of the parent (possibly a <div> or <body>). used.
ex (not commonly-used): the height of letter 'x' of the parent's font. ex is not commonly
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%; font-size: 1.2em; margin: 1.2em; padding: 10px; border: 0; } /* 80% of the parent's width */ /* 1.2 times of the parent's font */ /* 1.2 times of the current font's letter 'm' */ /* 10 pixels */ /* 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,
line-height: 20px; line-height: 150%; line-height: 1.2em; line-height: 1.5; /* 20 pixels */ /* 150% of the parent's line-height */ /* 1.2 times of the current font's letter 'm' */ /* 1.5 times of the current font */
Take note that 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 rectangular in shape and exhibits the so-called box model, with four virtual rectangles wrap around it "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; }
The actual width of the element is 300+(10+5+20)x2 = 370px. Each of the rectangular bounds has four sides, and can be individually referred to as xxx-top, xxxright, 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.
width: heigth:
The width and height are specified in units such as px (pixels), or percent (relative to the parent element).
auto|n|n% auto|n|n%
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.
Set the four margins individually. The "n" shall be expressed in a proper unit (e.g. 10px and 1.2em). You could use a negative value to overlap two elements (e.g., margin-left:-100px). The value of "auto" lets the browser to compute an appropriate number. "n%" is relative to the same property (i.e. margin-xxx) of the parent.
These are one-line shorthand notations to set all the four margins. If four values are given, they are applied to top, right, bottom, left (in the clockwise manner). If two values are given, they are applied to top-and-bottom, left-and-right. If one value is given, it is applied to all the four borders.
A one-line shorthand notation to set all the four paddings, similar to margin.
border-width:
Set the width of the four borders. "n" can be used to set an absolute thickness. borderwidth is a shorthand notation, you can use border-width-top, border-width-right, border-width-bottom, and border-width-right to set the four borders individually.
border-style: none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset
Set the style of the 4 borders. Similarly, you can use border-style-top, border-styleright, border-style-bottom, and border-style-right to set the four borders individually. Set the color of the 4 borders. Similarly, you can use border-color-top, border-colorright, border-color-bottom, border-color-right to set the four borders individually.. Shorthand notation to set all the properties of the borders, in the order shown. You can also use the border-top, border-right, border-bottom, and border-left to set the four borders individually.
border-color:
#rrggbb|rgb(r,g,b)|rgba(r,g,b,a)|color-name
border:
border-width
border-style
border-color
Margin, border, padding, width are NOT inherited by its descendants. 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
The above diagram was produced using these codes.
<div style="border:thin dotted black; background-color:#ffffdd"> <p style="margin:30px; border:20px solid black; padding:10px; background-
color:#ddffff"> This block-level tag <p> has a 10-px <em>padding</em> (in light-blue, from the edge of the content to the border), 20-px <em>border</em> (in solid black) and 30-px <em>margin</em> (in yellow, from the border up to the dotted lines). Observed the 3 virtual rectangular boxes around the texts.</p> </div>
font-family:
A prioritized list of fonts to be used. The browser will try to use the first font if the it is available, and goes down the list. The generic font family names include: serif (with small tails), sans-serif (without small tails), monospace, cursive, fantasy. Use monospace for program listing. Use sans-serif for
font-name|generic-family-name
computer display. serif are mainly used in prints (such as "Times" for newspapers and books).
normal|bold|bolder|lighter|100|200|...|800|900
font-style:
The italic uses italic font installed (some font families include the italic version); while the oblique is done by tilting the normal font. The samll-caps is smaller than the uppercase.
normal|italic|oblique
font-variant:
normal|small-caps font-size/line-height
font-variant
font-weight
Set all the font properties using a one-line shorthand notation. The properties must follow the order shown above. However, the leading and trailing items can be omitted. For example,
p { font-size: 14px; font-weight: bold; line-height: 140%; font-family: Arial, sans-serif; }
normal|n|n%|factor
text-decoration:
none|underline|overline|line-through|blink
text-transform: text-indent:
none|uppercase|lowercase|capitalize n|n%
Indent the first-line of the paragraph. To indent all the lines of a paragraph (i.e., the whole block), use padding or margin.
Specify how white spaces inside the element is to be handled. For "pre" (pre-formatted), preserve the white-spaces.
#rrggbb|rgb(r,g,b)|rgba(r,g,b,a)|color-
Set the background color of an element. The default is transparent. Use an image as the background.
background-repeat:
Define how the background image shall be repeated in x and y direction or both. Define whether background image shall scroll with the page or fixed.
background-attachment:
background-position: x y|x% y%|top left|top center|top right|center left|center center|center right|bottom left|bottom center|bottom right
Set the initial position of the background image. Note that there are two values, specifying the x and y position respectively.
The background properties has a one-line shorthand notation, with the order shown as below:
background-repeat
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.
Define whether the list item marker shall be inside or outside the item element. Use an image as the list item marker. Shorthand notation to specify all the properties of the list.
inside|outside
list-style-type
collapse|separate n
For separate border, specify the distance between border (i.e., the deprecated cellspacing attribute) Specify which side to show the caption.
caption-side:
top|bottom|left|right
5. More HTML
5.1 Image Maps
Image maps are "clickable" image that loads different pages depending on where (or which hotregions) you click on the image. Each hot region of the image map can be associated with a different link. There are two type of image maps: 1. Client-side image map: browser at the client-side handles the mapping of hot-regions to links. 2. Server-side image map: server handles the mapping of hot-regions to links. The co-ordinates of the location clicked are sent to the server to be processed by a program (such as a CGI/ASP/JSP/PHP script). The mapping information is held on the server.
3. <map id="myMap"> 4. 5. <area shape="circle" href=" url1" coords="xc, yc, r"> <area shape="rect" bottomRightY"> 6. <area shape="poly" href=" url3" coords="x1, y1, x2, y2, ..., x1, y1"> href=" url2" coords="topLeftX, topLeftY, bottomRightX,
Example:
<map id="myMap"> <area shape="rect" coords="20,20,160,60" href="http://www.zzz.com/">
<area>'s attributes: shape="rect|circle|poly|default": define the shape of the hot region. The "default"
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).
5.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. The tags involved are:
<frameset>...</frameset>: to sub-divide the window. <frame>: defines each of the frames in a frameset. <iframe>...</iframe>: for floating or inline or internal frame. <noframe>...</noframe>: alternative text if frame is not supported by browser.
To
divide
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:
<frameset rows="100, 20%, 150, *"> ...frame-declarations...
</frameset>
Divide the window into four rows of sizes: 100 pixels, 20% of the screen, 150 pixels, and the remaining space.
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.
<frameset rows="50, *"> <frame src="navigation.html" name="navigation" noresize> <frameset cols="100, *"> <frame src="summary.html" name="summary"> <frame src="detail.html" name="detail"> </frameset> </frameset>
To control which frame to receive the content of a hyperlink, you could include the target attribute in the <a> tag. Using the previous example, a hyperlink in the "navigation" frame targeting the "detail" frame is:
<a href="chapter5.html" target="detail">Chapter 5</a>
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:
<!-- navigation.html --> <head> <title>navigation bar</title> <base target="detail"> </head>
As mentioned, frames has gone out of favor these day. The HTML 5 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>. Syntax (Container tag):
<noframe>...alternative-text...</noframe>
You could use CSS to position and style the iframe. Iframe is used extensively by JavaScript and Ajax. Example: [TODO]
The standard attributes are applicable to ALL the HTML elements. They include class, id, style, lang, dir, and title.
class=" classname " : specifies the subclass this tag belongs to. The class attribute can have more
than one values. The class value needs not be unique. Classes are primarily used by CSS for applying style rule, selected via the class-selector (in the form of .classname or tagname.classname). See the "CSS Section" above.
id=" idValue " : for declaring an unique, document-wide identifier to a particular tag. No two tags can have the same id value, while many tags can belong to the same class. The id attribute is used by CSS for applying styles (via the id-selector in the form of #idName), and JavaScript for manipulating the element (via document.getElementById() function). style=" rule " : for applying inline style to a tag, applicable to this tag only. See the "CSS Section". title=" tooltip-text " : gives an advisory text description for this tag, and display as tool tip when
lang=" value " : specifies the language used by this particular tag.
dir="LTR|RTL" : specifies the direction of the text for this tag. It takes values of LTR (left-to-right) or RTL (right-to-left).
frame.
<style>...</style>: embedded style rules applicable to this document. <script>...</script>: program scripting codes.
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" />
"ccc/test.html"
is
resolved
to
target="target-frame-name|_blank|_parent|_self|_top" : specifies the target frame into which all linked document should be loaded: "_blank" in new window, "_self" in this frame, "_parent" in the parent frame, "_top" in the full body of the window.
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).
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". To include an icon, provide a <link> tag in the <head> section, as follows:
<link rel="icon" href="favicon.ico" type="image/x-icon" />
-->
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:
<meta name="keywords" content="Java, HTML, CSS" /> <meta name="author" content="Tan Ah Teck" />
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:
<meta http-equiv="http-response-header" content="value" />
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. Example 2: Auto-Refresh every x seconds
<meta http-equiv="Refresh" content="3" />
The server will include this response header in the response message, when the page is downloaded:
Content-Type: text/html; charset=utf-8
6. More CSS
6.1 Positioning the HTML Block-Level Elements
Each element has a natural location inside a page's flow, in the order read in by the browser. The property position can be used to alter the position of block elements.
position: static|absolute|relative|fixed
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:
Set the distance from the edge of this element to the corresponding edge of the containing block.
width: height:
Set the width and height of this block. You can use the width and height to scale this block.
n|n%|auto n|n%|auto
z-index:
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. Specify how to handle content overflowing the block's width/height.
number|auto
overflow:
auto|hidden|scroll|visible|inherit
*/
background: black; color: white; } #main-panel { position: absolute; left: 220px; top: 10px; 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> /* from left edge 10+200+10 */ /* from top edge, same as left-panel */
For example, a fixed <div> is added to the above example in absolute positioning. Take note that zindex is used to ensure that the fixed <div> is always on top of the other <div>'s, irregardless of the order of writing the <div>'s.
#left-panel { position: absolute; left: 10px; top: 10px; width: 200px; height: 600px; background: black; color: white; z-index: 100; } #main-panel { position: absolute; left: 220px; top: 10px; width: 560px; height: 600px; background: cyan; color: black; z-index: 100; } #fixed-panel { position: fixed; left: 100px; top: 200px; width: 200px; /* from left edge 10+200+10 */ /* from top edge, same as left-panel */ /* from left edge */ /* from top edge */
height: 200px;
background: lime; color: red; z-index: 200; } <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> /* larger z-index is on top */
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 />.
10</body> 11</html>
"iframeTest.css"
1body { 2 3} 4 5#myIframe { /* ID-Selector */ background-color: #FFF;
6 7 8 9 10 11}
/* float with the right margin of the browser's window */ /* margin from the top of the window */
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; }
You can use display:none or visibility:hidden to "not display" or "hide" an element. 1. The display:none specifies not to display an element, and it will not take up any space. The page will be rendered as if the element is not present. All the descendants of this element are also not displayed and remove from the normal flow. 2. The visibility:hidden hides an element, but it will still take up the same space as before. The element will be hidden, but it affects the layout. Example: [TODO] The display:block can be used to display an inline element as a block. For example,
image#id1 { /* display this image as block and center */
display:block; margin: 5px auto; } span.block { /* display this class of inline element span as block */
display:block; }
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; }
element from the normal flow of the page. That is, the space occupied by the element is preserved.
position: absolute;
Recall that an absolute-positioned block must be placed in a non-static block, in this case, a relativeposition <div>.
Image Sprite
[TODO]
Property opacity
You can use the property opacity to control the transpancy of an image. For example,
img.thumbnail { opacity:0.5; } img.thumbnail:hover { opacity:1.0; }