HTML and CSS: Difference between revisions
(25 intermediate revisions by the same user not shown) | |||
Line 82: | Line 82: | ||
[http://genomewiki.ucsc.edu/genecats/index.php/Static_Page_Protocol#Template_for_new_static_pages Template for a basic static Genome Browser page]. | [http://genomewiki.ucsc.edu/genecats/index.php/Static_Page_Protocol#Template_for_new_static_pages Template for a basic static Genome Browser page]. | ||
'''Important points''' | |||
* Links to external style sheets should always be in the <head></head> | * Links to external style sheets should always be in the <head></head> | ||
* Use <nowiki><div></nowiki> tags to divide up the page into logical "divisions" | * Use [http://coding.smashingmagazine.com/2012/06/06/all-about-unicode-utf8-character-sets/ UTF-8] character encoding | ||
* Use <nowiki><div></nowiki> tags to divide up the page into logical "divisions" (for HTML 4 anyway ... there are some nice [http://coding.smashingmagazine.com/2011/11/18/html5-semantics/ new elements] in HTML 5) | |||
* Unless needed for the function of a page/application, JavaScripts should be included at the bottom of a page, just before the </body> tag. This is so the content of the page appears to the user as fast as possible. Once the content is loaded, by the time the user has scanned the page, the JavaScript will have loaded. This speeds up the whole process. | * Unless needed for the function of a page/application, JavaScripts should be included at the bottom of a page, just before the </body> tag. This is so the content of the page appears to the user as fast as possible. Once the content is loaded, by the time the user has scanned the page, the JavaScript will have loaded. This speeds up the whole process. | ||
* When closing tags that are opened much further up in a page, it's a good idea to comment them: | * When closing tags that are opened much further up in a page, it's a good idea to comment them: | ||
Line 103: | Line 104: | ||
* Examples: span, i, b, a ... | * Examples: span, i, b, a ... | ||
* Block level elements can not reside inside inline elements, e.g. <pre><span><p></p></span></pre> | * Block level elements can not reside inside inline elements, e.g. <pre><span><p></p></span></pre> | ||
====Example==== | |||
'''The HTML''' | |||
[[File:Inline_vs_block_example_HTML.png | 583px | border]] | |||
(Note: the 'outline' class is just there to highlight/"outline" the element in the output below.) | |||
'''The Output''' | |||
[[File:Inline_vs_block_example_OUTPUT.png | 583px | border]] | |||
Note that the HTML is identical apart from the two elements used: | |||
* <nowiki><div></nowiki> - block-level | |||
* <nowiki><span></nowiki> - inline | |||
The block level element automatically creates a line break before and after it and have a width off 100% (unless another width is specified in the css). Inline elements do not. | |||
===Which tags do/don’t require end tags=== | ===Which tags do/don’t require end tags=== | ||
* Required: most html elements require an end tag. | * Required: most html elements require an end tag. | ||
* No end tag allowed; Void Elements: <br>, <meta>, <input>, <link>, <img> …. | * No end tag allowed; Void Elements: <nowiki><br>, <meta>, <input>, <link>, <img></nowiki> …. | ||
** HTML 4 does ''not'' allow self-closing tags, e.g. <br /> or <img ….. />. Do not use them. | ** HTML 4 does ''not'' allow self-closing tags, e.g. <br /> or <img ….. />. Do not use them. | ||
* End tag optional: <nowiki><p>, <li>, <tbody>, <head>, <tr>, <td> …</nowiki> | * End tag optional: <nowiki><p>, <li>, <tbody>, <head>, <tr>, <td> …</nowiki> | ||
Line 145: | Line 164: | ||
* HTML is case insensitive, but it has become the universal standard to use lowercase tags and attributes (xhtml requires lowercase). | * HTML is case insensitive, but it has become the universal standard to use lowercase tags and attributes (xhtml requires lowercase). | ||
* All attribute | * All attribute values '''must''' be in quotes if they contain '''any''' non-numeric characters (it's part the W3C HTML spec) | ||
** <font color="green">OK</font>: class= | ** <font color="green">OK</font>: class="mainContent" | ||
** <font color="green">OK</font>: cellpadding=0 | ** <font color="green">OK</font>: cellpadding=0 | ||
** <font color="crimson">Not OK</font>: width=100% (correct: width= | ** <font color="crimson">Not OK</font>: width=100% (correct: width="100%") | ||
** <font color="crimson">Not OK</font>: target=_blank (correct: target= | ** <font color="crimson">Not OK</font>: target=_blank (correct: target="_blank") | ||
** <font color="crimson">Not OK</font>: border=1px (correct: border= | ** <font color="crimson">Not OK</font>: border=1px (correct: border="1px") | ||
** | ** '''However''', always using quotes is recommended for consistency and maintainability. | ||
* Indent code for easier reading | * Indent code for easier reading | ||
* Use comments, and properly format them | * Use comments, and properly format them | ||
Line 278: | Line 297: | ||
===Best Practice Tips=== | ===Best Practice Tips=== | ||
==== | ====Attributes with zero values==== | ||
When setting css values (width, size, etc), only specify the units for a value (i.e. px, em, %) for non-0 values. E.g., | When setting css values (width, size, etc), only specify the units for a value (i.e. px, em, %) for non-0 values. E.g., | ||
Line 301: | Line 320: | ||
===Text on the web=== | ===Text on the web=== | ||
Research shows that people generally do not read on the web (apart from reading news stories and blogs, etc). | [http://uxmyths.com/post/647473628/myth-people-read-on-the-web Research shows] that people generally do not read on the web (apart from reading news stories and blogs, etc). | ||
People scan web pages, they do not read them. So... '''Text instructions rarely help; a good, intuitive UI does.''' | People scan web pages, they do not read them. So... '''Text instructions rarely help; a good, intuitive UI does.''' | ||
Avoid large blocks of text at all costs, unless you're writing a story, blog, docs, or other type document. | |||
===Well written links=== | ===Well written links=== | ||
Line 338: | Line 359: | ||
Here's an example of a 3-column layout with header and footer sections using CSS: | Here's an example of a 3-column layout with header and footer sections using CSS: | ||
'''The HTML''' | '''The HTML (note, this example shows HTML 5)''' | ||
<pre> | <pre> | ||
Line 414: | Line 435: | ||
</pre> | </pre> | ||
'''View a [http://jsfiddle.net/ | '''View a [http://jsfiddle.net/GregR/DwcB7/ demo of this example] on JSFiddle.com.''' | ||
===Form design=== | ===Form design=== | ||
* Always use <label> tags! | * Always use [http://developer.mozilla.org/en-US/docs/HTML/Element/label <label> tags] to associate a form control with its label! | ||
* | * Give all form elements an id (name is being phased out for most purposes) | ||
* Align fields along a single vertical axis | * Align fields along a single vertical axis ([http://jsfiddle.net/GregR/ArjKx/1/ demo)] | ||
* Label position for fields depends on the context | * Label position for fields depends on the context | ||
* Do not show irrelevant fields | * Do not show irrelevant fields | ||
Line 433: | Line 454: | ||
==Further Reading== | ==Further Reading and Resources== | ||
===Online Magazines, Articles & Blogs=== | |||
[http://www.smashingmagazine.com/ Smashing Magazine] | |||
[http://www.alistapart.com/ A List Apart] | |||
[http://24ways.org/ 24 Ways (to impress your friends)] | |||
Font sizing: http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/ | Font sizing: http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/ | ||
[http://uxmyths.com/post/647473628/myth-people-read-on-the-web Myth #1: People read on the web] | |||
===References=== | |||
Special Character Encodings: http://www.degraeve.com/reference/specialcharacters.php | |||
CSS Selectors: http://www.w3.org/TR/CSS2/selector.html#pattern-matching | CSS Selectors: http://www.w3.org/TR/CSS2/selector.html#pattern-matching | ||
The [https://developer.mozilla.org/en-US/ Mozilla Developers Network] is probably the best reference for HTML, CSS and Javascript on the web. The site w3schools.com that often comes up in web searches isn't really that reliable. It is [http://w3fools.com/ not recommended]. | |||
[http://www.usability.gov/ Usability.gov] - US government's own web site concerning web usability and accessibility. |
Latest revision as of 00:04, 7 December 2012
Overview
This document covers HTML 4.01 and CSS 2.
General Rules for Web Development
Separate content (HTML), layout (CSS), and logic (javascript/php/etc)
- HTML is for content
- CSS is for layout
- Keep styles/CSS out of the HTML
- Keep javascript out of the HTML
Sticking to these rules will make code easier to read, easier to reuse, and easier to maintain.
HTML
The basic structure of an HTML 4.01 document
Example Basic Document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Title</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link href="mystyle.css" rel="stylesheet" type="text/css"> </head> <body> <div id="header"> This is my site! </div><!-- #header --> <div id="content"> <h1>Heading</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pellentesque, orci ultrices aliquam tempor, sapien leo dignissim ante, pharetra rutrum diam augue a mauris.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pellentesque, orci ultrices aliquam tempor, sapien leo dignissim ante, pharetra rutrum diam augue a mauris.</p> </div><!-- #content --> <h1>Another heading</h1> <table> <thead> <th> <td>r1c1</td> <td>r1c2</td> </th> </thead> <tbody> <tr> <td>r1c1</td> <td>r1c2</td> </tr> <tr> <td>r2c1</td> <td>r2c2</td> </tr> </tbody> </table> <div id="footer"> © 2012. Me. </div><!-- #footer --> <script type="txt/javascript"> // some javascript </script> </body> </html>
Template for a basic static Genome Browser page.
Important points
- Links to external style sheets should always be in the <head></head>
- Use UTF-8 character encoding
- Use <div> tags to divide up the page into logical "divisions" (for HTML 4 anyway ... there are some nice new elements in HTML 5)
- Unless needed for the function of a page/application, JavaScripts should be included at the bottom of a page, just before the </body> tag. This is so the content of the page appears to the user as fast as possible. Once the content is loaded, by the time the user has scanned the page, the JavaScript will have loaded. This speeds up the whole process.
- When closing tags that are opened much further up in a page, it's a good idea to comment them:
- Closing by id: </div><!-- #header -->
- Closing by class: </div><!-- .article -->
- Note the use of <thead> and <tbody> tags in the table.
Block level elements vs. inline
Block
- For blocks of content
- Automatically fill entire with of parent element
- Usually have default top and bottom margins
- Examples: p, div, table, ul, blockquote, fieldset, form ...
Inline
- For defining text or data
- Examples: span, i, b, a ...
- Block level elements can not reside inside inline elements, e.g.
<span><p></p></span>
Example
The HTML
(Note: the 'outline' class is just there to highlight/"outline" the element in the output below.)
The Output
Note that the HTML is identical apart from the two elements used:
- <div> - block-level
- <span> - inline
The block level element automatically creates a line break before and after it and have a width off 100% (unless another width is specified in the css). Inline elements do not.
Which tags do/don’t require end tags
- Required: most html elements require an end tag.
- No end tag allowed; Void Elements: <br>, <meta>, <input>, <link>, <img> ….
- HTML 4 does not allow self-closing tags, e.g.
or <img ….. />. Do not use them.
- HTML 4 does not allow self-closing tags, e.g.
- End tag optional: <p>, <li>, <tbody>, <head>, <tr>, <td> …
- HOWEVER! Including end tags on ALL elements:
- Is recommended by the W3C
- Makes for more readable, less error-prone markup
- In just good practice :)
- HOWEVER! Including end tags on ALL elements:
Special characters in HTML
Some characters should not be directly typed in HTML documents, but an ASCII character equivalent should be used.
- Examples: & • © ü < > (“&” is especially important in URLs)
- Reference for character equivalents: http://www.degraeve.com/reference/specialcharacters.php
Deprecated tags (HTML you shouldn’t use)
- Many tags that are deprecated are so because css does a better job
- <font>
- <center>
- CSS replacements: font-family:, align: center, etc.
The W3C has an Index of HTML Elements with deprecated tags marked.
TIP!
To horizontally center a block-level element inside another block give it the CSS attribute margin: 0 auto;:
.centerMe { margin: 0 auto; }
The 0 gives it no top or bottom margin, and the "auto" makes the browser put and even amount of margin on both the left and right side of the element, thus centering it.
Code style
- HTML is case insensitive, but it has become the universal standard to use lowercase tags and attributes (xhtml requires lowercase).
- All attribute values must be in quotes if they contain any non-numeric characters (it's part the W3C HTML spec)
- OK: class="mainContent"
- OK: cellpadding=0
- Not OK: width=100% (correct: width="100%")
- Not OK: target=_blank (correct: target="_blank")
- Not OK: border=1px (correct: border="1px")
- However, always using quotes is recommended for consistency and maintainability.
- Indent code for easier reading
- Use comments, and properly format them
- Two spaces not needed after a period, and in fact the second space will be ignored
- Code should not be wider than average screen size
- Easier to edit
- Easier to debug
Oh, bloody semantics! They may default to look the same, but they don’t mean the same
<em> vs. <i>
- <em> is for “emphasis”. E.g.,
- “No, my <em>name</em> is Paris! I live in <em>Troy</em>.”
- <i> is for writing things that require “italics” - so to speak... “[...] a span of text in an alternate voice or mood, or is otherwise offset from normal prose.” E.g.,
- The name of a ship (The <i>Titanic</i>), an idiomatic phrase from another language (<i lang=”fr”>ooh la la</i>) or a species’ names (<i>Homo erectus</i>).
<strong> vs. <b>
- <strong> represents strong importance for it’s content, but unlike <em>, does not change sentence meaning. E.g.,
- <strong>Warning! This banana is dangerous!</strong>
- <b> represents “a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance an with no implication of an alternate voice or mood.” …. sure..... E.g.,
- “....never forgot the joy of her fifth birthday - feasting on <b>powdered toast</p> and opening her gift: a <b>Log from Blammo!</b>.”
id vs. class attributes
class
- General, general rules for styling
- Use very generic, reusable names
id
- Unique to each page, for styling and scripting (and testing with Selenium)
- Use very specific, descriptive names
Give (almost) everything an id - anything that is a unique item:
- All <div>, <form>, <fieldset>, <input>, <textarea>, <table>, <img>, <ul>, <ol>
- Using only a name attribute won’t cut it
- If you don’t need it now, chances are, you will later
Common tag usage errors
<blockquote>
- Strictly for content that is quoted from another source.
- For an indent, best use
with style margin-left: 10px;
<table>
- Strictly to be used for displaying tabular data
- Not for layout
<br>
- To force a line break in a sentence or force proper formatting of things like mailing addresses
- Not for adding space between content (we have CSS for that)
Missing alt text in <img> tags
- Required as of HTML 4.01
- Helps disabled users, and this text appears if the link to the image breaks
CSS
CSS Best Practices
- Use a CSS reset for better cross-browser compatibility
- Condense verbose statements
- Use commas for redundant declarations, E.g.,
Before
.experiment a { text-decoration: none; } .axisType a { text-decoration: none; } .elementType a { text-decoration: none; }
After
.experiment a, .axisType a, .elementType a { text-decoration: none; }
- Declare font size for body in % (62.5%), then use em to set font sizes (font-size: 1.5em;). This is preferred over px or pt.
Cascading Order: the C in CSS
The order, starting with highest priority:
- User styles (styles set by the user in their browser)
- Inline styles (styles set in the HTML document - not recommended)
- Media type
- Importance (!important)
- Specificity
- Order within the style sheet (items lower in the sheet over ride styles higher up)
- Parent inherited styles
- Browser default styles
Inheritance
- The family tree: DOM
- Most tags inherit the styles of their parents
- Styles not inherited: margin, width, border, etc.
- It's usually logical which ones wouldn't be auto-inherited
Defining styles through context
Examples:
.copy h1 em {...} .copy * em {...} div.copy * {...}
So, for the first one, ".copy h1 em" means that each em element inside an h1 element that is inside and element with the class "copy" will get these styles. This is very useful and more flexible that styling everything using specific classes and ids.
Child and Sibling electors
- Child: .copy > em (styles children em of .copy class but not the grandchildren)
- Sibling selector reference
Pseudo-classes
Link and dynamic pseudo-classes, :link, :hover, :active, etc
Explanation of psuedo-classes on the Mozilla Developers Network.
Best Practice Tips
Attributes with zero values
When setting css values (width, size, etc), only specify the units for a value (i.e. px, em, %) for non-0 values. E.g.,
- margin: 0; (units are not needed)
- margin: 5px; (unit is needed, because value is non-zero)
Use selector lists
Combine rules into selector lists when ever possible:
.article, .footer, #title { font: ...; }
Favor specificity over classes and ids
Favor specificity over classes and ids for styling - E.g.,
.article p table {font: Arial;}
Some Basic UX (User Experience) Tips
Text on the web
Research shows that people generally do not read on the web (apart from reading news stories and blogs, etc).
People scan web pages, they do not read them. So... Text instructions rarely help; a good, intuitive UI does.
Avoid large blocks of text at all costs, unless you're writing a story, blog, docs, or other type document.
Well written links
- Do not use the old click “here” method. It provides the user no information.
- Links should describe where the user will be taken
- URLs generally do not make good links, they usually tell the user nothing
- Links going to a page should be labeled the name of the page they’re taking you to whenever possible
- Life is too short to click on an unknown. ;-) A link's text should provide predictive information.
Rounded corners are better
- Research shows that rectangles with rounded corners are easier on the eyes because they take less cognitive effort to "visually" process.
- They make information easier to process.
Reference: Why Rounded Corners are Easier on the Eyes
Colors should accommodate color blind
Testing You Page for Colorblindness
Putting it all together
Page layout: <div> vs. <table>
Why you should not use tables for layout
- Requires more tags (i.e. more DOM nodes)
- More complicated to edit / harder to maintain
- This is especially true when you start nesting tables!
- Takes longer to load in a browser (though marginal these days)
Here's an example of a 3-column layout with header and footer sections using CSS:
The HTML (note, this example shows HTML 5)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>3 Column Layout</title> </head> <body> <div id="container"> <header> <p>Header</p> </header> <section id="column-a"> <p>Primary Sidebar</p> </section> <section id="column-b"> <p>Main content</p> </section> <section id="column-c"> <p>Secondary Sidebar</p> </section> <footer> <p>Footer</p> </footer> </div> </body> </html>
The CSS
#container { width: 960px; margin: 0 auto; } header { background-color: rgb(145,160,175); height: 40px; } #column-a { float: left; background-color: rgb(175,145,145); width: 20%; height: 100px; } #column-b { float: left; background-color: rgb(200,200,200); width: 60%; height: 100px; } #column-c { float: left; background-color: rgb(145,175,145); width: 20%; height: 100px; } footer { clear: both; background-color: rgb(175,175,145); height: 40px; }
View a demo of this example on JSFiddle.com.
Form design
- Always use <label> tags to associate a form control with its label!
- Give all form elements an id (name is being phased out for most purposes)
- Align fields along a single vertical axis (demo)
- Label position for fields depends on the context
- Do not show irrelevant fields
- Use javascipt to dynamically show fields only when relevant
TIP! Luke Wroblewski's Web Application Form Design is a great read.
Navigation links on a web page, are a type of list. Therefore use a HTML list to create navigation; <ul>. The menu for the CGIs in the Genome Browser are an example of this.
Further Reading and Resources
Online Magazines, Articles & Blogs
24 Ways (to impress your friends)
Font sizing: http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/
Myth #1: People read on the web
References
Special Character Encodings: http://www.degraeve.com/reference/specialcharacters.php
CSS Selectors: http://www.w3.org/TR/CSS2/selector.html#pattern-matching
The Mozilla Developers Network is probably the best reference for HTML, CSS and Javascript on the web. The site w3schools.com that often comes up in web searches isn't really that reliable. It is not recommended.
Usability.gov - US government's own web site concerning web usability and accessibility.