Building Pages
Raw Materials
The HTML page is the basic molecule of the Web. It is the package for content on the Web, since Web sites are simply (admittedly a gross oversimplification) collections of Web pages. HTML pages contain both the content (text, pointers to images and other content, etc.) and the instructions for how to put it all together in a pleasing display. A Web page combines four elements: the actual content, HTML, CSS, and Javascript.
Four Basic Elements of HTML Pages
- The Content: the actual content of the page is the point of the page. It’s easy to get excited about whizzy effects and a dazzling color palette, but remember that people visit for the content. Very few people care about the design as long as it doesn’t get in the way, and then they care a lot.
- Hypertext Markup Language (HTML)
- An HTML file is a simple text file, where annotations in a language called HTML (HyperText Markup Language) have been embedded in the text. No special editor is required for working with HTML, although specialized editors can be a big help. Editors like Dreamweaver highlight the HTML code when you are working on a Web page, and typically can check your code for syntax errors.
- HTML provides a way to describe both the semantics (what it "means") and the presentation (how it looks) of the information on a Web page.
- HTML also provides hypertext linking, a mechanism for describing relationships between things.
- HTML is wrapped around the actual content of the page.
- Cascading Style Sheets (CSS) enhance HTML by providing richer ways to describe the appearance, meaning, position, and behavior of elements in an HTML page.
- Javascript (JS) is a programming language that runs inside Web browsers. Javascript programs can directly (and asynchronously) interact with Web pages and Web servers. Javascript is typically used to display menus and image rollovers, and it is the core technology behind Ajax.
How Elements Combine to Create HTML Pages
Here are 6 ways in which these elements are combined to create Web pages.
- Provide Content: HTML contains or links to text, images, links, and embedded multimedia.
- Page Mechanics: HTML is used to provide non-content info needed to display the page properly: doctype, style information, Javascript code, page meta information (keywords, etc). HTML also is used to load files containing CSS styling and Javascript functions.
- Provide Structure via HTML: boxes (DIVs), spans, paragraphs, lists, tables, headings, forms, hypertext links
- Control Appearance: a combination of HTML and CSS
- Typography: Font families. Sizes. Serif vs sans. Small caps. Italics. Bold. Drop caps. Text alignment. Line height (leading) and spacing (tracking).
- Colors and Transparency: how they are represented and applied.
- Borders: can be applied to any or all 4 sides of any container.
- Margins and Padding: how to separate an element from things around it.
- Backgrounds: colors and images can be used as backgrounds of elements.
- Provide Position via CSS: absolute and relative positioning, floating
- Implement Behaviors via CSS and Javascript: CSS can define actions to be taken when certain events occur, such as mousing over a menu item. Javascript can watch events for something of interest, or control elements on the screen. Here is another example of using Javascript to control something dynamically.
Basic Page Structure
Overview
The essential nature of a Web page is that it is a rectangular box. That outermost box may be the same size as the browser window through which you are viewing the page, but it may not—that’s when the scrollbars appear. The visual layout of a Web page consists of a collection of rectangular boxes. An effective way to design a page is to think in terms of filling a grid with boxes that may or may not overlap. Everything is a rectangular box, from the browser window to the smallest HTML element inside the browser window.
- Boxes may contain other boxes may contain other boxes may contain…. You get the idea. This is an important concept: elements have a parent/child relationship when they contain other elements. You can take advantage of these relationships to target styling to specific elements.
- Boxes can be positioned on the screen in different ways:
- static positioning, the default where blocks line up one after another down the page
- fixed in place, even when you scroll
- positioned relative to another box
- positioned in an absolute location, which may be a percentage: left:15%;
- floating to the left or right side of other elements.
- Boxes may overlap other boxes partially or completely. You can even specify a stacking order (z-index) if you plan on overlapping your page elements. You can also reduce the opacity of boxes to make things show through from underneath.
- Boxes can be any size, and the size can be fixed or fluid.
- Things may not look like boxes. Clever designers can use all sorts of techniques (usually image backgrounds with transparency) to reduce the apparent blockiness.
- You can read a lot more about this on the Layouts with CSS page.
ME!
FIXED
Position
What Does a Web Page Look Like?
Since an HTML page is just a text file, you can look at it in any program that opens up simple text files. As soon as you open up such a file, you will immediately see things that don’t look like regular text. These are HTML tags, which are surrounded by angle brackets, as in <h1> or <ul class="biglist">. You might also find style declarations and Javascript code, but we’ll leave that for later.
What are the Basic Components of Web Pages?
An HTML page is structured like an outline (or a tree diagram). There are only a few top-level elements in the outline, but every element is a container for more elements, each of which may contain yet more elements. A well-formed page has these top-level elements:
- <DOCTYPE>: a single declaration that is always the first line of an HTML file. There are 4 valid doctypes, depending on how stringently valid your HTML code is expected to be. By default, we’ll be using the XHTML 1.0 Strict doctype. If omitted, however, most browsers will assume the file uses the oldest, weakest form of HTML, which gives the most room for errors. There are additional doctypes for pages that use frames, but their use is discouraged by most Web cognoscenti.
- <HTML>: this declaration wraps around everything else in the file after DOCTYPE.
- <HEAD> and </HEAD>: the HEAD section contains information about the page, as well as external files that are required (Javascript, CSS).
- <BODY> and </BODY>: the BODY section wraps around the content of the Web page that is actually available to viewers.
- </HTML>: this declaration at the end wraps around everything else in the HTML file.
I have created sample HTML, CSS, and Javascript files that you can use as a starting point for your own pages. I also created a simpler version that does not load any CSS or Javascript files.
Outline of Basic Web Page
<html>
. . . the HEAD content describes the page and its components, but says nothing about the content. . .
</head>
. . . the BODY section contains the actual visible content of the page . . .
</body>
Simple Web page with Common Elements (in XHTML)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!– this is an HTML COMMENT, which is completely ignored –>
<title>Canonical Page v1</title>
<meta name="description" content="This is the class Web site for CIS86 in Spring 2009." />
<meta name="keywords" content="College of the Redwoods,CIS86,HTML,Web Page Design" />
<script type="text/JavaScript" language="javascript" src="CSS/CIS86.js"></script>
<link href="CSS/CIS86.css" rel="stylesheet" type="text/css" />
<link href="CSS/CIS86-Print.css" rel="stylesheet" type="text/css" media="print" />
<style type="text/css">
h2 { color:#0033ff; }
/* this is a comment inside CSS (either <style> or an external CSS file) */
.highlight { background-color:#ffff66; }
</style>
<body>
<h2>This is a header for a simple page.</h2>
<div class="highlight" >
<img src="images/example.jpg" alt="This is an example image." />
<p style="font-weight:bold;" >This is a very Simple Page.</p>
</div>
</body>
</html>
Another View of the Same Thing
This tree-oriented view of an HTML page is a representation of the example page’s underlying structure, which uses the Document Object Model (DOM). When the browser reads an HTML page, it creates this tree structure that corresponds to the elements in your HTML page. One key property of a tree is that you can tell which element is inside another element—pivotal to being able to properly apply CSS to the elements.
HTML Syntax
HTML Syntax
HTML files are just text files, and they can be edited with any text editor. This is deceptively simple, because your results will be unpredictable unless you actually have some idea of what you are doing. Armed with some knowledge, however, you can effectively create and maintain Web sites with free software.
I cannot emphasize enough the importance of syntax and good typing. Even though HTML tags appear in plain text, they use a very specific syntax to accomplish their functions. 90% of the errors that beginners make are either from typos or misapplication of the rules of HTML syntax. These are both alien concepts to non-programmers: (1) that you must type accurately at all times, and (2) that all of the picky details of syntax must be correct, especially including commas, semicolons, colons, and quotes. Browsers will ignore anything they don’t understand and keep going when they try to display a page (here is a ridiculous one-liner). A typing or syntax error could negate an entire section of your page, which rarely turns out well. Validate your HTML and CSS!
All tags must be closed, and in the right order. Most tags are closed by repeating the tag with a slash in front of it, as in: <strong> and </strong>.
Paired tags always appear like this: <table> will eventually be followed by </table>, although you may find many other tags between the starting tag and the ending tag for any given pair. Tags that appear within the scope of another tag have a parent-child relationship that can be exploited in CSS. Not only can you apply styling to a DIV (box) and to a paragraph, you can also apply styling to paragraphs that occur inside DIVs – this is a very powerful technique.
These HTML tags do not require a separate ending tag: br, img, input, link, doctype, and meta. Instead, these tags are self-closing: they include the slash just inside the closing angle bracket of the HTML tag, as in
<img src="whatever.jpg" title="An Example." />
Tags are hierarchically nested. You can easily chart out a page to discover problems with nesting – draw arcs on the printed page to connect pairs of tags. If your arcs overlap, then you have a problem. This is correct:
<strong><em>Example</em></strong>
whereas this is not correctly nested:
<strong><em>Example</strong></em>
An HTML tag can be applied in several ways:
- As the beginning and ending tags completely wrap around something, the tag’s effects are directly applied to the enclosed elements. Make some words <strong>boldface using the STRONG tag</strong> in this sentence.
- The opening tag may also include attributes that apply CSS styling to the enclosed content. The tag itself may have effects, but most of the CSS will come from these attributes:
- style: directly apply the embedded CSS to the enclosed elements.
- class: associate one or more CSS class names with the outermost element, allowing you to apply CSS to all elements with that class name.
- id: associate a unique ID with a single element on the page, allowing you to add CSS specifically for the element.
Certain other tags have additional attributes:
- alt: supply alternate text for a screen reader
- title: browsers use this text for a tooltip when you hover over the element
- name: the name of a link anchor point within a page, allowing you to jump directly to the spot
- href: the URL or filename target for a link
- src: the URL or filename to be linked in
- onmousedown, onhover, etc: link anchor attributes for mouse events
Common HTML Tags
Top-Level Tags | Head Elements | |
doctype : defines the language and HTML dialect | meta : additional info about the page, site, including description and keywords. | |
html : surrounds the HTML for a page | title : appears in the browser titlebar | |
head : surrounds the header info section | link : loads a style sheet in an HTML page | |
body : the actual page content. You can also apply properties to the entire page, and execute Javascript when the page is loaded. | style : embedded style declarations script : embedded Javascript |
|
Block Elements: always begin on new line; width, height, line-height, margins can be set; default width is 100% of containing element | Inline Elements: always begin on same line; can’t change heights or margins; width is only as long as the element, and can’t be changed | |
div : creates a box (container) that can be sized, styled, and positioned. | a : creates a hypertext link, and is also used to define a location within a page for linking | |
h1,h2,h3,h4,h5,h6 : headers of varying sizes (h1 is largest and most important) | br : forces the next HTML element to start on a new line | |
p : defines a paragraph of text | img : inserts an image into the page | |
table {tr, td} : creates a table (like this one) | span: used to apply formatting to a limited span of text or other elements | |
form {input, select, textarea} : creates a form for accepting user input | strong, em : makes text boldfaced or italic; avoid use of obsolete <b> and <i> tags. | |
blockquote, pre : different kinds of nonformatted inclusions | iframe (obsolete): an inline frame that displays an entirely different HTML page; use object to embed other types of objects (Flash, Java, etc) | |
Lists: block elements that provide support for lists of things | Attributes: both inline properties and mechanisms for applying CSS styling | |
ul {li} : an unordered list | style : for applying inline CSS directly to an HTML element | |
ol {li} : an ordered list | class : for assigning a CSS class to an element | |
dl {dt, dd} : creates a definition list | id : uniquely identifies an element for CSS or DOM manipulation | |
Remember: Every HTML tag has default values that are assigned by the browser: sizes, heights, margins,padding, and more. These defaults vary from browser to browser. If you want to be sure how your HTML pages will look, then specify everything that affects your layout using CSS styling. You can also use a CSS Reset to reset all these defaults to zero or neutral values.
Canonical Web Page (and CSS and Javascript)
I have prepared three files for student use, to provide a starting point for creating Web pages.
- Prototype HTML Page: this page has a lot of stuff that provides a solid foundation for your files. You can prune away irrelevant parts as you wish, but remember that things were initially placed in that file for a reason. Here is a short version that leaves out some less-necessary things, along with all the example stuff in the BODY.
- Prototype CSS file: this file has a so-called "CSS reset" at the start, which resets all values to known values. Different browsers provide different default values for all these settings, so resetting them to clear those defaults is a good approach. You simply add back the styling that is needed, and you don’t have to worry as much about cross-browser appearance.
- Prototype Javascript file
To use these files, simply download them to your computer, and save them in a place where you can find them. These three files consist of a simple HTML file that includes CSS and Javascript files. After you copy them, simply delete the unwanted material in the BODY tag, and morph the page into whatever you want it to be.
Examples of the Most Common HTML Tags
Common HEAD Elements
- head: <head> and </head>
- meta tags:
- description: <meta name="description" content="This is the student Web site for CIS86.">
- keywords: <meta name="keywords" content="CIS86, College of the Redwoods,Web Site Design">
- charset: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- author: <meta name="author" content="Site by Monolith Design, www.MonolithDesign.com" />
- title: <title>CIS86 2009 HTML Examples</title>
- link: <link href="CSS/CIS86.css" rel="stylesheet" type="text/css"> and
<link href="CSS/CIS86-Print.css" rel="stylesheet" type="text/css" media="print"> and
<link rel="shortcut icon" href="../Monolith.ico" > - style:
<style type="text/css">
.explain {color: #990099}
</style> - script:
<script type="text/JavaScript" language="javascript" src="CSS/CIS86.js"></script> and<script type="text/JavaScript">
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} }
</script>
Common BODY Elements
<div id="One" style="background-color: #990099;"><p>This is DIV One. </p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh eusmod tincidunt ut laoreet dolore magna aliquam erat volputate. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait facilisi.</p>
<p>Here is the third sentence and paragraph.</p>
</div>
This is DIV One.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh eusmod tincidunt ut laoreet dolore magna aliquam erat volputate. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait facilisi.
Here is the third sentence and paragraph.
BLOCK ELEMENTS
<h1>This is Header 1.</h1>
<h2>This is Header 2.</h2>
<h3>This is Header 3.</h3>
<h4>This is Header 4.</h4>
<h5>This is Header 5.</h5>
<h6>This is Header 6.</h6>
<hr>
<p>This defines a paragraph of text. It can be as
long as you want. It can include images, lists, etc.</p>
<table border="4" cellpadding="4" cellspacing="4" bgcolor="#99FFFF">
<caption>This is the table caption.</caption>
<tr>
<td>This is column 1 of row 1.</td>
<td>This is column 2 of row 1.</td>
</tr>
</table>
This is column 1 of row 1. | This is column 2 of row 1. |
Lists are commonly used in HTML. Here is a great article about modern trends in styling and using lists.
<ul> <li>List Item 1 <ul> <li>Nested Item 1</li>
<li>Nested Item 2</li> </ul></li> <li>List Item 2</li> </ul>
- List Item 1
- Nested Item 1
- Nested Item 2
- List Item 2
<dl>
<dt>Phrenology</dt>
<dd>Mapping bumps on the head to personality characteristics.</dd>
<dt>Politics</dt>
<dd>A strife of interests masquerading as a contest of principles. The conduct of public affairs for private advantage.</dd>
</dl>
- Phrenology
- Mapping bumps on the head to personality characteristics.
- Politics
- A strife of interests masquerading as a contest of principles. The conduct of public affairs for private advantage.
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
- Item 1
- Item 2
- Item 3
<hr />
<div style="width:250px;background-color:#ddeeff"> This is a BOX. </div>
<a href="CIS86-Books.html" title="Book Reviews">CIS86 Book Reviews</a>
CIS86 Book Reviews
<img src="images/Star.gif" alt="Little Star" width="15" height="14" />
<p>Note that images are inline elements, <img src="images/Star.gif" alt="Little Star" width="15" height="14" /> so they do not start on a new line.</p>
Note that images are inline elements, so they do not start on a new line.
<p>I am <span style="font-weight:bold">going to turn some of it bold</span> using the SPAN tag and CSS styling.</p>
I am going to turn some of it bold using the SPAN tag and CSS styling.
<p>I am <strong>going to turn some of it bold</strong> using the STRONG tag.</p>
I am going to turn some of it bold using the STRONG tag.
.CIS86Advisory {font-style: italic; color:#336699; } <div class="CIS86Advisory">This is controlled by the definition in the CSS file.</div>
HTML Reference
This page has a bunch of reference articles about HTML.
Color
Colors are represented in a number of ways in Web pages, but these are notational differences that describe the same thing. Color on computer monitors is represented with varying amounts of 3 fundamental colors: Red, Green, and Blue (also called RGB). By varying the amount of each of the 3 components, it is possible to produce the appearance of a vast array of colors. Each of the 3 components has a value from 0 to 255 (the range that can be represented in one byte = 8 bits = 2^8). The larger the number, the lighter the color (255 is the brightest for any of the 3 basic colors, while 0 is the darkest.)
To further complicate matters, decimal numbers are rarely used to describe colors. Instead, the RGB components are usually represented in hexadecimal (usually just called “hex”), or base-16 arithmetic. Here is a handy decimal-to-hexadecimal chart from Elizabeth Castro’s site. This is a more compact notation, but using base 16 requires that you have a single digit for everything from 0 to 15 (just like base 10 requires single digits from 0 to 9). The answer was to use the letter ‘a’ to represent 10, ‘b’ for 11, ‘c’ for 12, ‘d’ for 13, ‘e’ for 14, and ‘f’ for 15. Accordingly, the maximum value for a color component is written as #ff, where the pound sign denotes a hexadecimal number. Remember: bigger = brighter.
Different Ways to Refer to Colors
- #RRGGBB, where RR is the red component (0-FF, which is 255 in base 10), GG is green, and BB is blue. If all three colors are at maximum (#FF), then the resulting color is White. This is the preferred way to represent colors.
- #RGB is the shorthand version of the previous entry, for the case where digits are doubled: #F8C == #FF88CC. Avoid this unless you are obsessed with making your code as tiny as possible.
- rgb(rrr.rr%, ggg.gg%, bbb.bb%), where the RGB values are specified as percentages like 72.5%. No one does it this way; use hexadecimal.
- rgb(rrr,ggg,bbb), where the RGB values are decimal numbers in the range 0-255. No one does it this way; use hexadecimal.
- keyword, where keyword is one of these predefined colors: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow. No one does it this way, since your color choices can change constantly over the life of a project.
Examples of Color Notations
- An RGB combination of (0, 0, 0) is black. Hexadecimal: #000000
- RGB (255, 255, 255) is white. Hexadecimal: #ffffff
- RGB (255, 0, 0) is bright red.
- RGB (127, 0, 0) is a medium red. Hexadecimal: #7f0000
- RGB (0, 255, 0) is bright green. Hexadecimal: #00ff00
- RGB (0, 0, 255) is bright blue. Hexadecimal: #0000ff
- RGB (255, 255, 0) is yellow. Hexadecimal: #ffff00
- RGB (255, 0, 255) is purple. Hexadecimal: #ff00ff
There is also a completely stupid rule for specifying colors: if all 3 color components have pairs of the same numbers, you can represent the hex number as a 3-digit number instead of using 6 digits. Examples: #ff6633 can be written as #f63, #003300 as #030, and #336699 as #369. This saves 3 characters, while introducing a special-case syntax for colors. In a world of broadband, there is no need to do this! If you are obsessed with reducing the size of your CSS file, then use a “tidy” program to squeeze out the extra space. I am only mentioning this because you may see it when examining other sites.
Handy Color Resources
- Web Developer Toolbar: select Information > View Color Info to get a palette of defined colors used on the current HTML page.
- Colorzilla: a Firefox add-on that lets you sample colors from any point in the Firefox window. It displays the color values in both decimal and hexadecimal, as well as the location of the cursor, and information about the HTML element under the cursor. It also provides miscellaneous functions like: a color picker; zooming the browser contents; analysis of colors in the DOM (very useful!), and a color palette browser. I use this one a lot because it is very quick and easy, even though the functionality is basically duplicated in the Web Developer Toolbar.
- Chart of Named Colors
- Interactive Color Chart
- CMYK-to-RGB Translations
- Hexadecimal-to-Decimal Conversion Chart
- Color Palette Creator that also shows what your palette looks like to people with different kinds of color-blindness.
- Simulate Color Blindness
- Color Charts
- Excellent Color Chart
- 25 Color Palette Tools : you will surely find one you like here!
About Fonts
Proper and effective use of fonts is one of the more problematic areas of Web design. Since fonts are not embedded in pages, it is always possible that some users’ computers will not have the font chosen by the designer. In HTML, you can specify a list of fonts to try, and the Web browser will choose the first one that is found on the computer. There is little commonality in fonts available across PCs, Macs, and Unix boxes. Accordingly, the Web designer must take care to specify a comprehensive list of fonts that will achieve the desired look on each platform. The apparent size of the same font will vary across platforms, as well. Web browsers often allow users to scale the size of fonts up or down, and some people do. Finally, the art of typography is thousands of years old, and the introduction of the printing press 5 centuries ago led to significant standardization of typographical rules, guidelines, and artfulness. Bringhurt’s book on typography is outstanding but incredibly dense; you can find an easier Web-based version here. Here is an outstanding guide to Beautiful Web Typography. Here is another excellent article about beautiful Web typography.
Given these factors, it takes some care to achieve a cross-browser, cross-platform look that is also attractive. Here are some guidelines:
- The most widespread Sans Serif fonts on the Web are Arial, Verdana (for Windows), and Helvetica for Mac OS. Ideally, you should choose one of these 3 for your primary font, and specify the other two as backup choices.
- Times New Roman is the most used Serif font on the Web. It is compatible for both Macs and PCs, and should be your primary Serif backup choice.
- Courier is a widely-available monospaced font, but it’s ugly.
- Common Mac Fonts are Serif: Times, New Century Schoolbook, Palatino; Sans Serif: Helvetica, Arial, Verdana (only installed by IE); Monospace: Courier.
- Common PC Fonts are Serif: Times New Roman, Georgia; Sans Serif: Arial, Tahoma, Verdana; Monospace: Courier New.
- All that being said, there’s a lot to be said for using nicer fonts than the lowest common denominator. Fortunately, whenever you specify a font in CSS, you can actually give a list of fonts to try. Simply put the nicer fonts at the beginning of your font list, and then make sure that the end of the list contains at least one font guaranteed to work on each platform.
- Example: font-family: Palatino, Georgia, "Times New Roman", Times, serif : a Mac user will see Palatino, a Windows user will see Georgia, and you’ll always have Times (New Roman) just in case, with serif as the ultimate fallback position.
- It’s always a good idea to test each of the fonts in your list, to make sure that you don’t get unexpected overflows because the text expands from a font choice to a larger than expected size.
- Here is an interesting article that proposes a variety of font stacks for use in Web pages, with a focus on providing more obscure fonts first for people who have them, followed by more sure alternatives.
- Here are some common font combinations:
- Arial, Helvetica, sans-serif
- Times New Roman, Times, serif
- Courier New, Courier, mono
- Georgia, Times New Roman, Times, serif
- Verdana, Arial, Helvetica, sans-serif
- Geneva, Arial, Helvetica, sans-serif
Here are some possible ways to specify the size of fonts:
- keywords: a good method for screen use, using relative sizes. One of the most versatile schemes for managing font size for a site calls for setting a single font-size keyword in CSS for the BODY tag, and then specify all other fonts in terms of percentages relative to the base size.
body { font-size:large; }
h1 {font-size: 150%; }
- percentages: another good way to specify fonts relatively for the screen (larger or smaller, not large or small).
Example: h3 {font-size: 125%; } - em: comes from the width of the capital "M". Changes to the base font size affect all others relatively, so this is also a convenient way to handle fonts for the screen.
- pixels: another natural way to specify fonts for the screen. This does not scale, though, so it removes flexibility from the user who needs larger text.
- ex: comes from the height of the letter "x". I have never seen this in use.
- inches: print-oriented.
- centimeters: print-oriented.
- picas: print-oriented.
- points: print-oriented.
If you absolutely must use that one particular font that nobody else has, there are 2 main ways to go about it:
- Create a graphic using your font, and then insert the image where you want that font to appear. The disadvantages are that by turning the font into a graphic, it is no longer editable or selectable, and it is opaque to the search engines. It also increases page load time slightly, although these kinds of graphics are typically pretty small.
- Use a technique called Inman Flash Replacement, which relies on both Flash and Javascript to do its work. You must have a tool that turns your font into Flash, and then Javascript is used to position the Flash bit at the right spot. The text is selectable this way, and it degrades gracefully if Flash or Javascript are unavailable (it just displays the actual text, instead of covering it with the Flash object). There is a nice open-source implementation of this called “sIFR”, which includes the tool to create the Flash from your font.
About Images
The most common media type other than text is the image. Currently, the two most common image types used on the Web are GIF and JPEG. (A third image type, PNG, is a superior format to GIF, but has yet to achieve widespread usage because of poor support in Internet Explorer.)
- GIF images are small, support transparency, and have a limited palette of colors. This makes them ideal for menus and buttons and other line art (like the CIS86 header) – especially where things need to overlap without obscuring. The limited palette of colors (only 256 maximum) makes GIF a bad choice for displaying a photographic image. The other attractive feature of the GIF format is animation. You can embed frames in a single GIF, and specify how quickly to cycle between the frames. This requires no additional browser plugins—all browsers will display this correctly.
- JPEG images excel at displaying continuous-tone images, so they are ideal for displaying photographs. JPEG images use compression to
hold down on the file size, but you can choose the desired level of compression, trading off file size for detail in the image.
- More Compression = Smaller File Size = Less Detail in Photo.
- Less Compression = Larger File Size = More Detail in Photo.
- PNG was intended to be a successor to GIF files, but adoption has been slowed by Internet Explorer’s inexplicable lack of support for PNG transparency. PNG has a much larger palette of colors than GIF, but its biggest lack is animation.You can use a PNG wherever you would use a GIF, but do not expect Internet Explorer to render transparency properly.
There are 2 ways to use an image on a Web page: you can place the image in the flow on the page like any other HTML element, or you can use an image as the background for an element that is already on the page. It depends on what you need:
- Use the img tag to place an element in the normal flow on the page. The image takes up space, and the other content flows around it in one way or another. An image placed this way can be floated to the left or right, and the surrounding text will gracefully flow around it as with any other floated element. You can float an image in 2 ways: with "float:right" in CSS, or with "align=right" as an HTML property. The latter approach is deprecated, so use the CSS method. An image can also be the anchor for a link. You can even use an image map to link specific rectangles (coordinates for the top-left and bottom-right corners) in an image to different URLs or actions.
- Use the image as a background-image for some element on the page. The image is not in the flow, and it only extends to the bounds of the object for which it is a background. These images are not clickable—they are just decoration. One disadvantage of these is that the default setting in most Web browsers for printing Web pages is to suppress background images and colors. If your logo is in the background of a header element, a printed Web page could completely drop the graphic. A common use for background images is styling navigation elements, where the :hover pseudo class is used to replace the background image with a different image. An even newer technique called "CSS sprites" embeds the different states in a single graphic, reducing the number of HTTP transactions. The tabs interface on this page uses a CSS sprite to change the background behind the selected tab.
Deprecated (Obsolete) HTML Tags
Since HTML has advanced since the early years, new features have been added, and old features have become obsolete. Tags which are considered obsolete are labeled as deprecated, and these tags should be avoided because modern browsers are no longer required to support their use. Of course, the programming language called COBOL was invented in 1957, and was obsolete by 1970. It is still the preferred language for business software! Ugh.
At any rate, avoid use of these deprecated HTML tags:
- <font> : this is nasty old "stone knives and bearskins" HTML. Do not use this, lest you provoke an unpleasant response from me! Use stylesheets to define font properties. The same holds for <basefont>, although this is rarely seen in the wild.
- <center>: use stylesheets to center elements.
- <strike>, <s>, <u>: strike-through text and underline text.
If your doctype is a flavor of XHTML, validation will flag deprecated tags as either warnings or errors (depending on whether your doctype is strict or transitional).
About Doctypes and Dialects
Comparing XHTML and HTML, Strict and Transitional
Since HTML was created in the early 1990s, the language has evolved steadily. With the addition of style sheets (CSS), some older HTML constructs were phased out ("deprecated"). This leaves us with a situation where there are multiple dialects of HTML supported by various Web browsers. In fact, all Web browsers are capable of handling different dialects of HTML and CSS. The main branch in the evolution of HTML came with the introduction of XHTML. This refactoring of HTML cleaned up the syntax in ways that allow for easier interpretation of the code, but it has more stringent requirements for allowable code. There are 2 main choices that must be made when setting up a project: whether to use HTML or XHTML, and whether to use a strict doctype or a transitional doctype. XHTML was created as a more structured form of HTML that lends itself to interpretation by various kinds of devices (like cell phones), not just Web browsers.
The difference between strict and transitional XHTML: Transitional is a forgiving form of doctype. While you must code cleanly—properly nested lowercase tags—transitional allows deprecated elements and attributes to pass validation. The strict doctype is strict: deprecated elements and attributes will fail to validate under a strict doctype and may well display incorrectly as well. For example, <p align=”left”> and <center> will validate in transitional, but not in strict mode since the align attribute and the <center> element are both deprecated.
Similarities in HTML 4.01 strict and XHTML Strict
HTML 4.01 strict will also fail to validate if you include deprecated elements and attributes. HTML 4.01 will fail to validate if you include XML style closing syntax on empty elements.
Differences between HTML and XHTML
The primary benefit is that XHTML is more portable in non-computer devices like cell phones, Palm devices and other scaled down browsers. XHTML is also said to be extensible: new tags can be added. XHTML, due to it’s stricter nature, forces developers to write cleaner code. Here are the “official” differences between XHTML and HTML:
- In XHTML the element tags must all be in lower case, as must all the attribute names. In HTML, you can code willy-nilly. Nothing in the W3C states that attribute values need to be lowercase, but some, like ID, are case sensitive. Note: Even if you have declared a HTML doctype, all lowercase, while not required, is recommended.
- In XHTML all attribute values must be encased in single or double quotes. In HTML, only attribute values with spaces or special characters were required to be in quotes.
- In XHTML, every opening tag must have a closing tag. Empty elements such as img and br must be self-closing. In HTML tags can be left unclosed. So, while this reduces the number of characters on a page, it also allows for sloppy code. Note: Self closing tags, such as <br />, will cause strict HTML to not validate.
- In XHTML, all tags must be properly nested: If you start tag <a> and then start tag <strong>, you must close tag </strong> before you close the </a>.
- In XHTML, all attributes must be coded as attribute/value pairs. The default selected option in XHTML should be written selected="selected". In HTML, the same would simply be coded as selected.
- In XHTML, the elements need to be coded in a semantic manner. Tables and forms can not be included in paragraphs, but form elements, being inline elements, need to be contained within a semantic block level element, such as a paragraph or table cell.
CSS Syntax
Overview of Cascading Style Sheets
Cascading Style Sheets (CSS) is the W3C standard for the visual presentation of Web pages. The basic idea is that CSS provides a mechanism to specify the appearance, position, and behavior of all elements on an HTML page. Furthermore, these definitions can be selectively applied to elements in a group of pages, allowing you to change the appearance of all those elements in a single place—the style sheet. This also reduces the size of your HTML pages, since you’re able to drop a lot of redundant markup.
In the olden days, page layouts were created by forcing elements into cells of tables, usually nested in intricate ways. Table-based layouts add a large amount of markup HTML to your pages, and can easily obscure the underlying structure of the page. Worst of all, table-based layouts are notoriously brittle—moving an element from one side to the other can involve moving tables-inside-tables-inside-tables or worse, the equivalent of major surgery. We won’t be using tables for layout in this class, but you will still see them in use as you look at Web pages!
If you want to explore what is possible with style sheets, check out the CSS Zen Garden, where there are dozens of pages with the exact same content but different style sheets. You will be amazed at the variety!
Three Ways to Define Styles
- External Style Sheet: style definitions can be listed in an external file, allowing those styles to be changed in one place for all files that use that style file. All production sites use external style sheets. You can use the <link> tag to load the CSS file, and it is exactly as if the contents of the CSS file were inserted into a <style> section in the HTML.
<link href="CSS/CIS86.css" rel="stylesheet" type="text/css" />
- Embedded Style Sheet: a style sheet can be embedded in the HEAD of a single HTML file using the style attribute. You can start development with an embedded style sheet, and then extract the style info into a separate file when the design stabilizes.
<style type="text/css">
/* This is a comment in a style sheet or <style> tag in the <head>. It can be multi-line, too. */
h1 { font-size:250%; color:#0066cc; background-color:#eeeeee; }
#topbox { border:3px solid #ffffcc; color:#0066cc; }
#toplist { list-style-type:none; }
.warning { background-color:#ffddee; font-weight:bold; }
.explain { padding: 0 20px; }
</style>
- Inline Styles: applied to an individual element via the style attribute. These are usually the most specific styling, but it is hard to modify this when it’s embedded directly into the code where it’s being applied. You should really avoid this as a matter of habit, but there are times when it makes sense.
<h2 style="margin-left:20px; font-size:150%;">An example header.</h2>
4 Ways to Attach Style Info to Elements
Once you have created your style info, whether linked in from another file or embedded in the <head> of your file, there are four ways you can associate the CSS with actual page elements. You can use any or all of these methods on each page element.
- Apply styling directly to HTML tags. You can define (and redefine) the behavior and appearance of HTML tags within your pages.
- Declare a class for an HTML element, which then receives all of the styling specified in that class. You can even apply more than one class to a given element. Each class can be applied to any element on the page, even to different kinds of elements.
- Declare an ID for a single HTML element on the page. Each ID uniquely identifies that element on the page, and the element receives all styling defined for that ID. You can have as many IDs as you want, but each one can only be applied to a single element per page. This is commonly used to identify the major "chunks" of the layout like the header and footer. If you put an ID on the body tag, you can highlight the current page in navigation.
- Declare inline styling directly for page elements using the style property. This technique should be used sparingly because it reduces flexibility while introducing opportunities for errors.
Here are examples of applying styles in the body, using the style definitions just above:
<div id="topbox">Blah, blah, blah….</div>
<ul class="warning" id="toplist">…list contents…</ul>
<p class="explain">This is an explanation.</p>
<div class="explain warning">blah….</div>
<span style="font-weight:bold; color:#996633;">This is bold and red.</span>
Four things you will find in CSS files or embedded stylesheets
- Comments, as delimited by /* and */. These can be multi-line.
- HTML tags, followed by a declaration block.
- Class names (a dot followed by a label), followed by a declaration block.
- IDs (a ‘#’ followed by a label), followed by a declaration block.
Structure of Style Rules
- Every style rule has two parts: the selector(s) and the declaration block. A CSS rule contains at least one selector and at least one declaration within a declaration block.
- The selector specifies which parts of the document should have the style rule applied, by assigning style information to
specific elements or groups of elements. You can have multiple selectors listed, and the styling in the declaration block applies to everything that matches all selectors. You can also specify combinations of selectors with specific relationships. For example, "h1+p" targets the first paragraph following an h1 tag. There are 3 kinds of selectors:
- Generic selectors are HTML tags, allowing you to change the appearance of all instances of specific tags.
- Class applies style to all elements of that class.
- ID applies style to the single element defined with that ID (name).
- The declaration block contains one or more declarations, and is always enclosed in curly braces. A declaration consists of a property name, a colon, and a corresponding value. Declarations are separated by semicolons.
- Examples:
- body { color: #ffffff; background-color: #000000; }
- img { border: 3px solid #cccccc; }
- #menubar {position: absolute; top: 100px; left: 0px; width: 180px; }
- h1, h2, h3 { color:#cccccc; text-transform:capitalize;}
- .question, .explain {font-color: #ff0000; font-weight: bold; }
- .rightcolumn h2 { padding-left:56px; background: url(../images/small-sun-icon-sidebar.jpg) left no-repeat; }
- p.explain ol li { list-style-type: disc; }
- h1+p { font-variant:small-caps; }
Pseudo-Class Selectors
A pseudo-class selector is a predefined class-like selector. They are written with a colon, followed by the predefined pseudo-class name. Some of these allow dynamic behaviors, such as with link anchors. The W3C specification says that you can attach pseudo-classes to any element, but Internet Explorer only really supports them for link anchors. Here is how to use them:
- :link selects links that have not been visited. a:link { border-bottom: 2px solid #ff0000; }
- :visited selects links that have been visited. a:visited { border-bottom: 2px solid #0000ff; }
- :hover selects an element when the mouse hovers over it. a:hover { background-color:#cccc99; }
- :active selects a link that is being activated. a:active { color:#ffc600; }
- :focus selects the element that has the focus. a:focus { outline:0; }
If you use these selectors for links, specify them in this order ("LVHA" = "Love-Hate")! You can get unpredictable results in some browsers in some conditions if you do not follow the order.
Resolving Conflicts in Style Declarations (the Cascade)
The Cascade part of CSS is the mechanism by which conflicting style directives are sorted out. This can be a most complex subject, but the gist of it is that usually the definition that takes precedence is the closest definition to the place in the source file where it is being used.
Another thing to realize is that there is a default value for every possible HTML and CSS construct you may use. These default values vary slightly from one browser to the next, so you have to either compensate for the foibles of individual browsers, or reset all of those defaults to zero or equivalent (this is called a "CSS reset"—see the Canonical CSS file for an example).
Since style directives can be applied in many ways in a single file, CSS uses the cascade to resolve any conflicts between style definitions.
- The source of the style sheet determines its importance, in this order: the Web browser’s default style sheet is overridden by the Web designer’s style sheet, which is overridden by the user’s style sheet (in the unlikely event the user specifies a private style sheet). As a designer, you can add the "!important" declaration to a rule to give greater weight to a rule.
- Specific selectors are given greater weight than general selectors. Here are the types of selectors in order of weight (least to most): Universal (applies to all elements) > element identifiers (applies to all elements of a certain type, such as table) > class identifiers (all elements of class "foo") > ID identifiers (the element named "menubar") > inline styles (make this thing red right here). For example, setting the background color for a paragraph named "overview" will have greater weight than a general assignment of background color to the page.
- If selectors have identical characteristics, then the selector that appears last in the style sheet file will take precedence. Selectors defined in an external file are considered to come before any style defined within the page (whether embedded or inline).
Most Common CSS Properties
Here is a description of the most commonly-used CSS properties. In certain cases, you will also find so-called shorthand properties that let you combine related properties into a single property declaration. For example, you can say:
font: 1em/1.5em bold italic serif
instead of
font-size: 1em; line-height: 1.5em; font-weight: bold; font-style: italic; font-family: serif
When specifying padding, margins, and borders, you usually have to specify what you want to happen for different sides. A single value for any of those properties results in an identical value being applied to all four sides. If you want to specify all 4 sides differently, remember the acronym TRBL, which means Top-Right-Bottom-Left.
padding:4px; (applies 4px padding to all 4 sides of the element)
padding:4px 6px 12px 6px; (applies to top, right, bottom, and left sides)
padding:4px 12px; (applies 4px to top and bottom, and 12px to right and left sides)
Font Properties
- font (shorthand property)
- font-family
- font-style
- font-variant
- font-weight
- font-size
Text Properties
- word-spacing
- letter-spacing
- text-decoration
- text-transform
- text-align
- text-indent
- line-height
Colors & Background Properties
- color
- background-color
- background (shorthand property)
- background-image
- background-repeat
- background-attachment
- background-position
Box Properties
- height, min-height, max-height
- width, min-width, max-width
- float
- clear
- margin (shorthand)
- margin-top, margin-right, margin-bottom, margin-left
- padding (shorthand)
- padding-top, padding-right, padding-bottom, padding-left
- border (shorthand)
- border-top, border-right, border-bottom, border-left (shorthand)
- border-width (shorthand)
- border-top-width, border-right-width, border-bottom-width, border-left-width
- border-color
- border-style
Lists
- list-style (shorthand)
- list-style-type
- list-style-image
- list-style-position
Display, Position, & Visibility Properties
- position: discussed in section about Layout
- display: block, inline, none
- visibility
- overflow
- white-space
Miscellaneous Properties
- Certain properties need a URL for the background image:
background: url(images/stripe.gif) or background: url(http://www.htmlhelp.com/stripe.gif)
There are many CSS References online, including the table from Elizabeth Castro in the back of her book (and her Web site) and this one from htmlhelp.com.
Additional Topics
Here are some related topics about using CSS.
- How I center something? Where did that <center> tag go?
- For text, use the text-align property: <h2 style="text-align:center;">Headline will be centered!</h2>
- For block-level elements, use margins: <div style="margin:0 auto;">The box will be centered.</div>
- Unfortunately, some versions of IE mishandle this. This example of centering a fixed-width box in the browser window also employs the fix for IE (misuing text-align). You can see this in play in the class Web site’s style sheet.
body { text-align:center; } this will center everything in IE, not just text
#maincontent { width:80%; margin:0 auto; text-align:left;} auto margins = centered
- How can I make columns? Here are various approaches to making columns, depending on your exact needs.
- If you are presenting tabular data, use a <table>.
- Use a margin to free up a column alongside something, and then fill the empty column with an absolutely-positioned element.
- Create a container to wrap around the group of columns, then use float:left on the individual columns inside that container. The columns will stack up towards the left side of the containing box.
- Create a container to wrap the group of columns, and use position:relative to establish a positioning context. Use position:absolute to place the columns where you want within the containing box.
- The specification for CSS3 allows you to create columns, but we are years away from any kind of widespread acceptance by browser vendors.
- Overflow: what happens when the contents are larger than the box? You can override the default behavior using the overflow property:
- overflow:visible (the default) will expand the container to fit the contents as needed
- overflow:auto lets the browser add scrollbars only when needed
- overflow:hidden will truncate anything outside the container’s bounds
- overflow:scroll will always show scroll bars
Multiple Style Sheets per Page
You can specify more than one style sheet per page, and there are some good reasons for doing so. In the following example from the class Web site, I have added a media property that allows me to target printed versions of the pages.
<link href="CSS/CIS86-Print.css" rel="stylesheet" type="text/css" media="print" />
In this version, I have removed some navigational code and tweaked widths for better printing. CSS also provides attributes for specifying where page breaks can happen. This is also an opportunity to tweak your colors for better contrast when printing.
Other media types allow you to target mobile devices, an up-and-coming need for certain Web sites.
Another possible use of multiple stylesheets is to provide alternate choices to a person browsing your site. Most commonly, the user is allowed to select a smaller or larger base font size for the page. You can also make other adjustments for different sizes.
When using multiple stylesheets, pay attention to which sheets are actually being loaded. Use media="all" to target everything. When you use more restricted media, make sure you control which other style sheets are being loaded.
Layout with CSS
Layout Using CSS
Using CSS to position elements in HTML pages is the modern approach to layout. Widespread adoption of CSS positioning in Web design took longer than it should have because the concepts are not as simple as using tables. The best thing you can do is experiment with example layouts to get a feel for how things work. It’s like learning to ride a bike—you may skin your knees a few times in the learning process, but you don’t forget once you learn.
Block-Level Elements and the Box Model
Many elements in HTML create block-level elements—their presence defines a box. Boxes have specific properties relating to the rectangular box: borders, margins, padding. For cases where there isn’t a box defined by existing HTML elements, you can create boxes in CSS using the div tag. A div defines a box with no attributes initially, and you apply styling to the contents of the div box.
Normally, when you specify a width for a component, this does not include padding or borders. Some versions of Internet Explorer instead interpret the width as being the combination of the content, the padding, and the border.
An important distinction is often misunderstood by people: margins are not part of the element—they are assertions about the space around the element. Background colors and images only apply to the content, its padding, and its borders. Everything outside the border (i.e., the margin) is really more a property of the page than the element. If one element is placed above another, only the greater of the two touching margins is used—this is called a collapsing margin. Left and right margins do not collapse.
Block vs Inline Elements
When laying out a page, there are 2 kinds of HTML page elements.
- Block elements: these HTML tags define rectangular boxes (see the Box Model). A block element always starts on a new line, aligned to the left, unless you explicitly specify a position. You can set the width, height, line-height, margins and padding for block elements. The default width of a block element is 100% of the containing element. HTML tags that define blocks are: div, h1-h6, p, table, form, blockquote, pre, ul, ol, dl
- Inline elements: these always begin on the same line as the previous element, and wrap to the next line as they run out of room. You can’t change heights or margins for an inline element, and their width is only as long as the element (and can’t be changed). HTML tags that define inline elements are: a, br, img, span, iframe, strong, em.
- You can change the default behavior of elements with the display property:
- display:block will display that element as a block, even if it is considered inline
- display:inline will force the element to be treated as an inline element
- display:none will remove the element from the flow and the page, so the following items will collapse into the space
Normal Layout Flow
To lay out a page, the browser starts at the top of the HTML file, and starts flowing the block-level boxes down the left side of the page, starting from the top left corner. Every time a block-level element comes along, it starts on a new line. Unless you specifically say otherwise, this is the default rule for arranging boxes on a page. Only very simple layouts are feasible with the default model—a page is only a single stack of boxes. [figure 1] You can override the default behavior in several ways: by specifying the absolute position of elements, or by floating boxes to one side or the other. These are CSS properties, so they are applied to HTML elements in the same way as other CSS.
An important concept to understand is the flow for placing block elements on the page. In the normal flow, a new element is placed directly after the previous element. If the first element is 100 pixels tall, then the second block element will start 101 pixels down from the top, and along the left side. Block elements in the normal flow will never overlap.
Floating Elements
Floated elements are shifted within the normal flow (and are not in the flow), and the elements that follow it flow around the floated element, like water going around a rock in a river. The only choices are float:left and float:right. The floated element is shifted as far as possible in the specified direction—the side of the page if possible, or a previously-floated element if already there. Essentially, floats stack up towards the floated direction. If there isn’t room for a floated element on the line, then it "falls off" the line, and looks for the first available space in the flow. Floated elements must have a width specified (except images). Do not specify floating and positioning for the same object — use one method or the other, but not both. Floats make a handy way to create columnar designs. There are a number of bugs in Internet Explorer’s handling of floats, such as the infamous "peekaboo" disappearing text bug, finally fixed in IE7. The bugs are well-understood, though, and can be patched for IE. [diagram]
If you don’t want elements to stack up after floats, you can specify that the element must clear left, right, or both-side floats before it by using the clear property (.e.g., clear:left, clear:right, clear:both). This forces a line break between the element and the previous float. Here is a great article about difficulties in using floats, including clearing floated elements.
An alternative to inserting a clearing element in the container after the floated elements is to use overflow:auto on the containing box.
Example 1: no overflow specified
Next element continues on same line….
Example 2: with overflow:auto on the outer container
Overflow:auto forces a break after the container just like the clear property.
Example 3: Box Height Collapses with Float
This is the text.
Example 4: Box Height Collapse Fixed with Overflow:auto
This is the text.
The Position Attribute
The primary way to alter the normal layout flow is to use the position attribute on a block-level element.
- position:static: if you don’t otherwise specify a position, this is the default. The only time you might need to actually specify this is to override a different setting inherited from a parent; I have never actually used this in years of Web development. If all elements use the default static positioning, then the layout happens exactly as described above in the Normal Flow.
- position:fixed: Puts an element at a fixed location
in the browser viewport, regardless of scrolling. This allows you to keep your header or navbar at the same location on the screen, regardless of how the page gets scrolled. This completely removes the element from the flow, and it can overlap other items. This is poorly supported by Internet Explorer 6. I have avoided using this because of the poor browser support, although it can be hacked to work. IE before version 7 treats this like position:absolute, so the element will simply scroll with the page. All other modern browsers support this, so it is becoming feasible as a positioning technique.
- There are usually other ways to achieve this affect, such as forcing scrollbars on inner DIVs to prevent the page itself from scrolling (using overflow:scroll).
- You can also use frames to split the page, but this is universally frowned upon by the HTML community.
- I have seen a jQuery-based "follower", which obviously relies on Javascript to do its work.
- position:relative: there are 2 completely unrelated uses for position:relative, which is dumb.
Relatively-positioned elements remain in the normal flow.
- You can shift the position of the element relative to where it would have appeared in the normal flow (e.g., left:20px; top:20px; will shift the left edge 20px to the right, not place it at pixel 10; it will also shift the top down 20px) from where it would normally be positioned. This does not take the element out of the flow, but other boxes may overlap since they believe a relatively positioned box is at the unmodified position. This really isn’t used very much; the best use I’ve seen was to shift a drop shadow graphic from underneath the box it was embellishing.
- The primary usage of position:relative is to establish a positioning context, so that child elements (things inside that box) can be positioned at exact locations inside the relatively-positioned box. Using position:relative creates a new instance of normal flow within the box.
- You can use position:relative to both shift the box and establish a positioning context within it, but it’s unlikely.
- position:absolute: placed an element at fixed coordinates inside the containing box. Absolutely-positioned elements are taken out of the flow entirely, so normally-positioned boxes don’t even “see” the absolutely-positioned elements. Subsequent content will flow into the space, so elements will overlap the absolutely-positioned elements unless you use margins or a z-index value to control the stacking.
- Absolute positioning can be very beneficial inside other boxes, since absolute positioning is based on the containing element. For a top-level element, the containing element is the entire page. If you put an absolutely-positioned element inside any positioned element, however, the coordinates are based on the top-left corner of the container, starting at zero for the x- and y-values. Effectively, absolute coordinates are truly relative—another brain-dead use of nomenclature in CSS.
- Use the CSS properties top, bottom, left, and right to specify locations. These can even be stated as percentages, which means the "absolute" position changes depending on the width of the browser window. You normally specify one of top/bottom and one of left/right, but you can specify both top and bottom or left and right at the same time if needed.
- If your item is at the top level (not inside anything except the BODY tag), then you do not need to establish a positioning context of relative with the containing object. Absolutely-positioned elements at the top level are placed relative to the upper-left corner of the browser window.
- The biggest problem with absolutely-positioned elements is that they can overrun other elements easily, especially at the bottom. There is no way to position an element after an absolutely-positioned element, since it is out of the flow.
Stacking Order and Z-index
Sometimes, you want elements to overlap. The CSS property z-index applied to a block-level element determines the stacking order when elements overlap. A higher z-index is stacked on top of a lower z-index. This can be complicated by parent-child relationships: the parent’s z-index determines where the entire container is displayed, and a z-index applied to children just determine where they are layered inside the container. Effectively, a child cannot have a higher z-index than its parent container. Z-index only works on positioned elements, and you can use both positive and negative numbers for the value.
Examples of CSS-Based Layouts
- 1a: Example page before positioning applied: using 5 colored DIVs to demonstrate positioning in the Normal Flow. Because they are block-level elements, each successive box (div) starts on a new line after the previous box.
- 1b: Fixed-width page, centered in browser window:
- body {text-align:center}
- #content {text-align:left; width:600px; margin: 0 auto;} : this needs to wrap around everything inside the body tag. The standard way to center something is to set the left and right margins to auto. Internet Explorer misinterprets this, but you can center in IE with text-align:center in the body, something else it misinterprets. The side-effect is that all text is centered, so you must explicitly override this. The CIS86 Web site uses this technique to center the contents.
- 2a: Using position:relative to offset the position of a box. This is an uncommon usage because the rest of the page acts as if the box was at the unpositioned location.
- position:relative; left:20px; top:20px; is used to shift DIV Two, although the following boxes are placed as if DIV Two is in its normal location.
- 2b: Absolute Positions inside a Relatively placed DIV : by setting position:relative on a block element, you can then use absolute positioning within that block. Elements can overlap inside the box.
- 3a: Three Columns #1 (the so-called Holy Grail of HTML coding: robust 3-column layout)
- L is absolute positioning, fixed width, with left:0. This DIV is at the top level, so it does not need anything to establish a positioning context using position:relative.
- R is absolute positioning, fixed width, with right:0. Ditto.
- Center has fixed margins to clear left, right columns. I also gave the margins to the footer DIV 5, since it might overlap the left and right columns if the center content DIV is really short.
- Here is a variation using percentages (3a-percent) for the size and position of the right side of the page.
- This example shows in 2 steps how the three-column layout works (3a-step1 and 3a-step2).
- 3b: Three Columns #2
- L is float:left, width:10%;
- R is float:right; width:10%;
- Center is 100%.
- 3c: Three Columns #3 : floated interior columns.
- Outer DIV has fixed width.
- Each interior box is: float:left; width:33%.
- I used the first example, the centered 800-pixel wide layout, as the basis for this. I left DIV 1 as the header, and DIV 5 as the footer. I added a wrapper called "outerbox" around DIVs 2, 3, and 4, and then floated the 3 boxes inside outerbox.
- 4a: 2 Columns #1 : absolutely-positioned interior columns
- L,R are width:49%, absolutely positioned to Left:0 and Right:0.
- Problem with footer because of absolute positioning. Note that I told DIV 4 to not be displayed (with display:none;), I did not say that about DIV 5. It’s still there — behind DIVs 2 and 3.
- In this variation, 4a-alt: I wrapped the absolutely-positioned DIVs in a relatively-positioned container with a fixed height. Since it is still in the normal flow, the final DIV will follow it.
- 4b: 2 Columns #2 : interior columns are floated left and right.
- L,R are width:50%. Floated left and right instead of using absolute positions. This is very error-prone, since IE handles the "stepdown" effect differently than other browsers.
- 5: DFF’s ImageBox: this uses float:left for the boxes. Look at this with View Source Chart and View Source.
There are quite a few more complex examples of positioning in the Examples section of the class Web site.
Javascript
Javascript is a key technology to exploit in the development of Web pages, since it adds interactivity and responsiveness to a Web site. The combination of HTML, CSS, and Javascript provides everything needed by a Web browser to provide a great user experience, and all modern Web browsers have native support for Javascript.
Because Javascript runs on the client side (on the user’s computer rather than the Web server), it is used for interactive effects, on-the-fly validation of data in forms, and other applications. The most common usage of Javascript is to create menus (like with this site) and other navigational mechanisms. Another common use is creating image rollovers, where moving the mouse over the first image is detected by the browser, which uses Javascript code to replace the first image with another. When the mouse moves off the second image, Javascript code replaces the second image with the first.
What is Javascript? It’s a third language (we have already been learning 2 others, HTML and CSS); in this case, it’s a programming language rather than a markup language. Since Javascript in integrated with the browser, it can manipulate objects on a Web page, as well as interact with a Web server to modify an existing Web page. There are thousands of free Javascript modules that you can use on your site. Even if you do not know how to program, it is possible (but occasionally painful) to integrate Javascript programs into a site.
How do you use Javascript on your Web sites?
- Load it. You use the <script> tag to either define Javascript inside the HTML file, or to load the Javascript code from a file. Typically, you must load the code module and any libraries it requires (such as jQuery).
- Set it up. In the <head> section, you use the <script> tag to embed a small amount of Javascript code that sets up the code. You usually must make changes in your HTML code to accommodate the new functions, but that is not always the case. You will typically need to define or customize CSS settings for the module.
- Invoke it. You must either use Javascript statements in <script> to start the program going, or the code must automatically start running when certain events happen on the page (like mouseovers).
What can you actually do with Javascript?
- Javascript can watch specific events in the browser, and trigger code to run when conditions are met. Click here to turn the first paragraph of the page red. Click here to turn every other list item purple. Use View Source to see the Javascript code for these examples. Javascript can directly access the browser’s internal representation of a Web page (the DOM, or Document Object Model). This means that a Javascript program can pick out any element on your page for direct manipulation—deleting, adding, changing the style information, anything. The ability to change any element on the page programmatically opens the door to completely interactive pages.
- Javascript can be used to validate the data in form fields, select dates from popup calendars, etc.
- You can add entirely new applications, like charts and graphs, and image slideshows and content sliders.
- Javascript can detect which browser version you are using, which allows you to compensate for known browser bugs or inadequacies. Using a library like jQuery factors out a lot of browser-specific issues.
- In the last few years, a new technique called Ajax has been introduced—this is core to the whole Web 2.0 concept. Using the Ajax technique, Javascript in the user’s Web browser opens up an HTTP connection (the protocol whereby Web browsers and Web servers interact) to the server. The responses from this interaction can arrive asynchronously (at any time after the request, but not necessarily immediately), and the Ajax mechanism allows Javascript to insert the results directly into the page without a page reload. Ajax is commonly used to process form submissions without requiring a page refresh. Ajax is a straightforward and powerful technique that allows for greater interactivity in pages because the user does not have to wait for a page reload every time something happens.
From the beginning, Javascript was widely denigrated in the programming community for various shortcomings, both real and imaginary. The last couple of years has seen a huge change in this perception, since Javascript became core to creating interactive Web sites that today’s conditions demand. This resulted in a number of outstanding code libraries coming out: Prototype, MooTools, and Scriptaculous, more recently followed by jQuery. These are all excellent libraries, but jQuery is rapidly becoming the top library because of its ease-of-use, particularly when selecting page elements for manipulation.
The last roadblock in effective Javascript is about to fall: the performance hit from being interpreted instead of compiled. Several groups are currently testing so-called JIT compilers, for "just-in-time". These Web browsers will compile Javascript code as it is executed, saving it for reuse. This is resulting in order-of-magnitude speed increases, and opens up possibilities for greater client-side processing of information.
If you use Javascript, here are some useful tools:
- JSLint is an online code validator for Javascript. This is always a good idea!
- JSMin is a code compressor from Douglas Crockford. It is more conservative than others because it does not rewrite variable names. Here is what compressed code looks like.
- Yahoo also has a compressor in their Developer Tools.