You are on page 1of 97

1/15/13

Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

Info

PR: error

I: error

L: 1

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 103

Tw: 74

l: 33

+1: 57

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 1

Terminology, Syntax, & Introduction


In this Lesson 1
HTML

Common Terms
Structure & Syntax
Referencing CSS
CSS

Common Terms
Structure & Syntax
Selectors
Reset
learn.shay howe.com/html-css/terminology -sy ntax-intro

1/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

Before beginning our journey to learn HTML and CSS it is important to understand the differences between the
two languages, their syntax, and some common terminology.
As an overview, HTML is a hyper text markup language created to give content structure and meaning. CSS,
also known as cascading style sheets, is a presentation language created to give content style and appearance.
To put this into laymen terms, HTML determines the structure and meaning of content on a web page while CSS
determines the style and appearance of this content. The two languages are independent of one another. CSS
should not reside within an HTML document and vice versa.
Taking this concept a bit further, the HTML p element is used to display a paragraph of text on a web page. The
p element is specifically used here as it is provides the most value for the content, thus being the most semantic
element. CSS then uses a type selector of p which can determine the color, font size, font weight, and other
stylistic properties of the paragraph. More on this to come.

Common HTML Terms


When getting started with HTML you are likely to hear new, and often strange, terms. Over time you will
become more and more familiar with all of them but three terms you should learn today include tags, elements,
and attributes.

Elements
Elements are designators that define objects within a page, including structure and content. Some of the more
popular elements include h1 through h6, p, a, div, span, strong, and em.
<a>

Tags
Elements are often made of multiple sets of tags, identified as opening and closing tags. Opening tags mark the
beginning of an element, such as <div>. Closing tags mark the end of an element and begin with a forward
slash, such as </div>.
<a>...</a>

Attributes
Attributes are properties used to provide additional instruction to given elements. More commonly, attributes are
used to assign an id, class, or title to an element, to give media elements a source (src), or to provide a
hyperlink reference (href).
<a href="http://www.shayhowe.com/" title="Shay Howe">Shay Howe</a>

Common HTML Terms Example


Shay Howe
learn.shay howe.com/html-css/terminology -sy ntax-intro

2/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

HTML Document Structure & Syntax


All HTML documents have a required structure that includes the following declaration and tags: doctype, html,
head, and body.
The doctype declaration is used to instruct web browsers which version of HTML is being used and is placed
at the very beginning of the HTML document. Following the doctype declaration, html tags signify the
beginning and end of the document.
The head of the document is used to outline any meta data, the document title, and links to any external files.
Any context included within the head tags is not visible within the actual web page itself. All of the content
visible within the web page will fall within the body tags.
A general HTML document structure looks like the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
<p>This is a website.</p>
</body>
</html>

Common CSS Terms


In addition to HTML terms, there are some common CSS terms you will want to familiarize yourself with. The
more you work with HTML and CSS the more these terms will become second nature.

Selectors
A selector determines exactly which element, or elements, the corresponding styles will be applied. Selectors can
include a combination of different IDs, classes, types, and other attributes all depending on how specific you
wish to be. Selectors can be identified as everything that comes before the first curly brace, {.
p { ... }

Properties
A property determines the style that will be applied to an element. Properties can be identified as the text coming
immediately before a colon. There are an abundance number of properties you can use, and new ones are
continually being added.
p {
color: #ff0;
font-size: 16px;
learn.shay howe.com/html-css/terminology -sy ntax-intro

3/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

Values
A value determines the behavior of a property. Values can be identified as the text in-between the colon and
semicolon.
p {
color: #ff0;
font-size: 16px;
}

CSS Structure & Syntax


CSS works by using selectors to apply styles to HTML elements. All CSS styles cascade, allowing different
styles to be inherited by multiple elements.
As an example, it is possible to set one style for all of the text on a page to be of a specific color, size, and
weight. Then by using a more targeted selector that style can be overwritten for a unique element.

Fig. 1.01 CSS syntax outline.


The following syntax demonstrates how styles would be applied to every paragraph.
p {
color: #ff0;
font-size: 16px;
}

Long vs. Short Hand


In CSS there are multiple different ways to declare values for a property. With long hand CSS you stack multiple
declarations, one after the other for each property and value. With short hand CSS you use one property and list
multiple values. It is best to use short hand CSS as it requires less code. Not all properties support short hand
CSS so make sure you are using the correct property and value structure.
/* Long Hand */
p {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
}
/* Short Hand */
learn.shay howe.com/html-css/terminology -sy ntax-intro

4/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

p {
padding: 10px 20px;
}
/* Short Hand */
p {
padding: 10px;
}

Comments within HTML & CSS


HTML and CSS give you the ability to leave comments within the code. These comments can be used to help
with organization, set reminders, and manage code more effectively. Comments become especially useful when
there are multiple people working on the same code. Any content wrapped within comments will not be
rendered on the page.
HTML comments wrap the content starting with <!-- and end with -->. CSS comments wrap the content
starting with /* and end with */.

Selectors
Selectors, as mentioned earlier, are the determining factor as to which elements are to be stylized. In so, it is
important to fully understand how to use selectors and how they can be leveraged. Some of the most common
selectors include elements, IDs, and classes, or some combination of the three.

Type Selectors
Type selectors are the most basic selector. Simply enough, elements without any necessary attributes are
targeted to apply styles. Type selectors are preferred whenever possible as they require less code and are easy
to manage.
HTML

<p>...</p>
CSS

p { ... }

Class Selectors
Class selectors allow you to apply the same style to an array of elements by giving them all the same class
attribute. Classes are denoted in CSS by identifying the class with a leading period. It is permissible to use the
same class attribute on multiple elements on a page.
HTML

learn.shay howe.com/html-css/terminology -sy ntax-intro

5/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

<div class="awesome">...</div>
CSS

.awesome { ... }

ID Selectors
ID selectors are similar to class selectors however they are used to target only one unique element at a time.
Instead of using the class attribute, IDs naturally use the ID attribute. In place of a period, as with classes, IDs
are denoted by identifying the ID with a leading hash sign. IDs are only allowed to be used once per page and
should ideally be reserved for significant elements.
HTML

<div id="shayhowe">...</div>
CSS

#shayhowe { ... }

Combining Selectors
A beauty of CSS is the ability to combine selectors and inherit styles. This allows you to start with a more
generic selector and work your way to being more specific as necessary. In addition, you can combine different
selectors to be as specific as you wish.
ul#social li {
padding: 0 3px;
}
ul#social li a {
height: 17px;
width: 16px;
}
ul#social li.tumblr a {
background: url('tumblr.png') 0 0 no-repeat;
}

Additional Selectors
Selectors can be extremely powerful and the selectors outlined above are only the beginning. Many more
advanced selectors exist and are readily available. Before dropping classes or IDs on random elements check
and see if there might be a better selector to do the job for you. It is also worth mentioning that not all advance
selectors work in every browser, particularly with new selectors introduced in CSS3. If a selector doesnt seem
to be working properly check its browser support.

learn.shay howe.com/html-css/terminology -sy ntax-intro

6/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

Referencing CSS
Once content is in place you may begin to style the HTML with CSS. There are a handful of different ways to
reference CSS, some of which are better than others.
The best practice for referencing CSS is to include all of your styles within a single external stylesheet, referenced
within the heading of a page. Using an external stylesheet allows you to use the same styles across an entire
website and quickly make changes site wide.
Other options include internal and inline styles. These options are generally frowned upon as they make updating
websites cumbersome and unwieldy.
<!-- External CSS File -->
<link rel="stylesheet" href="file.css">
<!-- Internal CSS -->
<style type="text/css">
p {
color: #f60;
font-size: 16px;
}
</style>
<!-- Inline CSS -->
<p style="color: #f60; font-size: 16px;">Lorem ipsum dolor sit amet...</p>

Using External CSS Stylesheets


As mentioned above, the best way to reference CSS is with an extrenal stylesheet. Doing so allows you to use
one set of styles across an entire website. Making changes to the style of a website becomes painless, and users
download less data overall to properly render the styles.
Within the head of the HTML document, the link element is used to define the relationship between the HTML
file and the CSS file. Since you are linking to CSS the rel attribute with a value of stylesheet is used to
specify the relationship. Furthermore, the href attribute is used to identify the location, or path, of the CSS file.
In order for the CSS to render, the path of the href attribute value must directly correlate to where the CSS file
is stored. In the example above the file.css is stored within the root directory, the same location as the
HTML file.
Should the CSS be within a subdirectory, the href attribute value would need to correlate this path accordingly.
For example, if the file.css is stored within a subdirectory call styles the href attribute value would be
styles/file.css, using a forward shash to indicate different directories.
<head>
<link rel="stylesheet" href="styles/file.css">
</head>

Reset
learn.shay howe.com/html-css/terminology -sy ntax-intro

7/9

1/15/13
Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS

By default every web browser has its own interpretation on how different elements are to be stylized. How
Chrome decides to render an input field is likely going to be much different than how Internet Explorer renders
an input field. To combat for cross browser compatibility CSS resets have become widely used.
Cross Browser Compatibility & Testing
As mentioned, different browsers render pages in different ways. Its important to recognize the value in cross
browser compatibility and testing. Websites dont need to look the same in every browser but they should be
close. What browsers you wish to support and to what degree is a decisions you will need to make in
accordance with what is best for your website.
CSS resets include a handful of rule sets that take every common HTML element and scale them down to one
unified style. These resets involve removing any sizing, margins, paddings, or additional styles. Resets need to be
the very first CSS styles to be rendered to ensure that all the styles there after are being applied to the skeleton
of a page.
There are a ton of different resets available to use, all of which have their own forte. My personal favorite is Eric
Meyers reset, which has been adapted to include a reset for the new HTML5 elements. Erics reset is short and
to the point, but feel free to research your own resets and find what youre comfortable using.
Code Validation
As proficient as we all are, we do make mistakes. Thankfully when writing HTML and CSS we have a validator
that can check our work. The W3C has built both HTML and CSS validators that will scan your code looking
for mistakes. Validating your code not only helps it render properly across all browsers, it also teaches you the
best practices for writing code.

Resources & Links


Common HTML Terms via Scripting Master
CSS Glossary via Code Style
Taming Advanced CSS Selectors via Smashing Magazine
CSS Tools: Reset CSS via Eric Meyer
An Intro to HTML & CSS via Shay Howe

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share
it with your friends.
learn.shay howe.com/html-css/terminology -sy ntax-intro

8/9

1/15/13

Lesson 2 Elements & Semantics

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the
latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shay howe.com/html-css/terminology -sy ntax-intro

9/9

1/15/13

Elements & Semantics - A Beginner's Guide to HTML & CSS


Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 20

Tw: 74

l: 33

+1: 1

whois

source

Rank: 177977

Density

Diagnosis

Links: 13(1) | 9(8)

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 2

Elements & Semantics


In this Lesson 2
HTML

Semantics Overview
Divisions & Spans
Typography
Hyperlinks
HTML5 Structural Elements
CSS

D.R.Y.
With a basic understanding of HTML and CSS in hand it is time to dig a little deeper and see what actually assembles these two languages.
In order to start building web pages you need to learn a little about which HTML elements are used to display different types of content. You will also want to know how these
different elements behave, to help ensure you achieve your desired outcome.
Additionally, once you begin writing code you want to make sure that you are doing so semantically. Writing semantic code includes keeping your code organized and making well
informed decisions.

Semantics Overview
Semantics have been mentioned a number of times thus far, so exactly what are semantics? Semantics within HTML is the practice of giving content on the page meaning and
structure. These semantics portray the value of content on a page, and are not solely used for styling purposes. Using semantic code provides a handful of benefits, including giving
computers, screen readers, search engines, and other devices the ability to adequately read and understand web pages. Additionaly, semantic code is easier to manage and work
with, knowing clearly what each piece of content is about.

Divisions & Spans


Divisions, or divs, and spans are HTML elements that act as a container for different content. As a generic container they do not come with any overarching meaning or semantic
value. Paragraphs are semantic in that when content is wrapped within a p element it is known as a paragraph. Divs and spans do not hold such meaning and are simply containers.
Both divs and spans, however, are extremely valuable when building a website in that they give you the ability to apply targeted CSS styles.
A div is a block level element commonly used to identify large sections of a website, helping build the layout and design. A span on the other hand, is an inline element commonly
used to identify smaller sections of text within a block level element, such as a paragraph.
Block vs. Inline Elements
All elements are either block or inline level elements. Whats the difference?
Block level elements begin on a new line on a page and occupy the full available width. Block level elements may be nested inside one another, as well as wrap inline level elements.
learn.shayhowe.com/html-css/elements-semantics

1/6

1/15/13

Elements & Semantics - A Beginner's Guide to HTML & CSS

Inline level elements do not begin on a new line and fall into the normal flow of a document, maintaining their necessary width. Inline level elements cannot nest a block level element,
however they can nest another inline level element.
Divs and spans can have added value when given a class or id. A class or id is typically added for styling purposes and to signify the difference between another div or span.
Choosing a class or id name is where semantics can come into play. When choosing a class or id attribute value it is important to choose something that has value to the actual context
of that element.
For example, if you have a div with an orange background that contains social media links your first inclination might be to give the div a class of orange. What happens if that
orange background is later changed to blue? Having a class of orange no longer makes sense. A better, more semantic, choice for a class would be social as it pertains to the
contents of the div not the style.
Divs & Spans<!-- div -->
<div class="social">
<p>Lorem ipsum dolor sit amet...</p>
<p>Lorem ipsum dolor sit amet...</p>
</div>
<!-- span -->
<p>Lorem ipsum dolor sit amet, <span class="tooltip">consectetur</span> elit.</p>

Typography
A large amount of content online is strictly text based. Many different forms of media and context exist online, however text rules the majority. There are a number of different
elements to display text on a web page within HTML. We will focus on the most popular, and more semantic, elements within this lesson. For a broader overview please see the
Typography lesson.

Headings
Headings are block level elements that come in six different rankings, h1 through h6, and are key identifiers for users reading a page. Headings help to quickly break up content and
provide hierarchy. They are also used to help search engines index and determine the value of content on a page.
Headings should be used in the order relevant to the content. The primary heading of a page or section should be coded with h1 and subsequent headings should use h2 on as
necessary. Headings should be reserved for true classification and not used to make text bold or big.
<h1>This is a Level 1 Heading</h1>
<h2>This is a Level 2 Heading</h2>
<h3>This is a Level 3 Heading</h3>

Headings Demo

This is a Level 1 Heading


This is a Level 2 Heading
This is a Level 3 Heading
Paragraphs
Headings are often followed with supporting paragraphs. Paragraphs are defined by using the p block level element. Numerous paragraphs can appear one after the other, adding
information to a page.
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p>

<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non p

Paragraphs Demo
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut enim ad minim veniam, quis nostrud exercitation ullamco.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.

Bold Text with Strong


To make text bold, and to note it as important, the strong inline level element is used. It is important to understand the semantic difference between strong and b, both of which will
make text bold. strong is semantically used to denote text with a strong importance, as is mostly the case when wanting to bold text. b on the other hand semantically means
stylistically offset, which isnt always the best case for text deserving prominent attention. Gauge the significance of the text you are looking to set as bold and choose an element
accordingly.
<p>Duis in <strong>voluptate</strong> velit esse cillum.</p>

Bold Text Demo


Duis in voluptate velit esse cillum.

Italicize Text with Emphasis


learn.shayhowe.com/html-css/elements-semantics

2/6

1/15/13

Elements & Semantics - A Beginner's Guide to HTML & CSS

To italicize text and place a stressed emphasis on it the em inline level element is used. As with strong, there are two different tags used to italicize text, each with a slightly different
semantic meaning. em semantically means to place a stressed emphasis on text and thus is the most popular option for italicizing text. The other option is i, which semantically values
text to be rendered in an alternate voice. Again, you will need to gauge the significance of the text you want to italicize and choose an element accordingly.
<p>Quae ars <em>putanda</em> est, expeteretur si nih.</p>

Italicize Text Demo


Quae ars putanda est, expeteretur si nih.

Hyperlinks
One of the core elements of the internet is the hyperlink, established by using an anchor. Hyperlinks are defined using the a inline element however they require a source to direct the
link. The href attribute, known as hyperlink reference, is used to set the destination of a link.
To accompany the href attribute it is always good practice to include the title attribute as well. The title attribute is used to help browsers, screen readers, search engines, and
other devices obtain a little more context to what the link is about. Generally speaking, the title shouldnt mimic that of the anchor text, it should provide additional support.
By nature the a element is an inline element, however with the introduction of HTML5, a elements now have the ability to wrap block or inline level elements. This is a break from the
standard convention yet permissible to turn entire blocks of content on a page into a link.
<a href="http://shayhowe.com" title="Shay's Website">Shay</a>

Hyperlinks Demo
Shay

Relative & Absolute Paths


The two most common types of links include links to other pages within a website and links to other websites. How these links are identified is by their path, also known as the value
of their href attribute.
Links pointing to other pages within the same website should have a relative path, in which the domain is not in the href attribute value. Since the link is pointing to another page on
the same website the href attribute value only needs to include the page being linked to, /about.html for example. Should the page being linked to reside within a subdirectory the
href attribute value needs to reflect this as well. Say the about.html page resides within the pages directory, the relative path would then be /pages/about.html.
Linking to other websites outside of the current one requires an absolute path, where the href attribute value must include the full domain. A link to Google would need the href
attribute value of http://google.com, starting with http and including the domain, .com in this case.
<!-- Relative Path -->
<a href="/about.html" title="About The Starter League">About</a>
<!-- Absolute Path -->
<a href="http://www.google.com/" title="Google Search Engine">Google</a>

Linking to an Email Address


Occasionally you will encounter a link to an email address. When clicked, this link opens the default email client and populates some information. At a minimum the email address
where the message is being sent is populated, however other information such as a subject and body text may also be populated.
To create an email link the href attribute value needs to start with mailto: followed by the email address to where the email should be sent. To create an email link to
shay@awesome.com the href attribute value would be mailto:shay@awesome.com.
Additionally, a subject and body text for the email can also be populated. To add a subject line include the subject= parameter following the email address. Multiple words within a
subject line require spaces to be encode using %20. Adding body text works very similar to that of the subject, using the body= parameter in the href attribute value. Again, spaces
must be encoded using %20 and line breaks must be encoded using %0A.
Altogether, a link to shay@awesome.com with the subject of Still Awesome and body text of This is awesome would look like mailto:shay@awesome.com?
Please notice, the first parameter requires a ? to bind it to the email address and additional parameters require a & to bind
them the previous parameter.

subject=Still%20Awesome&This%20is%20awesome.

For more information on building email links, including how to add multiple email addresses, cc, and bcc parameters, please see Joost de Valk guide, The Full mailto Link Syntax.
<a href="mailto:shay@awesome.com?subject=Still%20Awesome&body=This%20is%20awesome" title="shay@awesome.com">Email Me</a>

Email Link Demo


Email Me

Opening Links in a New Window


One feature available with hyperlinks is the ability to determine where the link is opened once clicked. Typically links open in the same window from which they are clicked, however
links may open in a new window. To trigger the action of opening a link in a new window the target attribute is used with a value of _blank. The target attribute determines
where the link is displayed, and the _blank value specifies a new window.
<a href="http://shayhowe.com/" title="Shay Howe's Website" target="_blank">Shay Howe</a>

learn.shayhowe.com/html-css/elements-semantics

3/6

1/15/13

Elements & Semantics - A Beginner's Guide to HTML & CSS

Opening Links in a New Window Demo


Shay Howe

Linking to Elements within the Same Page


Periodically you will see links that simply link to another portion of the same page. In the case of this guide, links found within the In this Lesson section link down the page to the
appropriate section. Perhaps more commonly found online are Back to Top links that return users to the top of a page.
Creating an on page link is accomplished by specifying an ID on the element you wish to link to. Then, using the ID of that element in a links href attribute value. As an example,
putting the main ID on the body element allows you to link to the top of a page using the href value of #main.
<a href="#awesome" title="Awesome Section of Page">Awesome</a>
<div id="awesome">Awesome Section</div>

On Page Links Demo


Awesome
Awesome Section

HTML5 Structural Elements


HTML5 provides a handful of new elements, all of which are focused around improving semantics. Before, if you wanted to declare a block level section of a page you were likely to
use a div. With HTML5 you have a handful of new block level elements that allow you to write more semantic code.

Fig. 2.01 The new HTML5 structural elements outline.

Header
The header, just as it sounds, is used to identify the heading of a page, article, section, or other segment of a page. In general, a header may include a heading, introduction text, or
navigation. You can use more than one header on a page. Depending on the website, you will ideally include a header at the beginning of the page. Additionally, a header may
reappear as the header of an article or section as necessary.
<header>...</header>

Clarification on the header Element


The header element should not be confused with the head or headings, h1 through h6.
The header element is a structural element that outlines a heading on a page, of which falls within the body element on a page. The head element is not displayed on the page and is
used to outline meta data, the document title, and links to external files.
Headings, h1 through h6, are used to represent multiple levels of text headings throughout a page.

Navigation
The nav is a block level element used to denote a section of major navigational links on a page. Not all links should be wrapped within a nav element. The nav should be reserved
for primary navigation sections including universal navigation, a table of contents, breadcrumbs, previous/next links, or other noteworthy groups of links.
Most commonly links included within the nav element will link to other parts of the same website or web page. Miscellaneous one off links should not be wrapped within the nav
element, and should only use the a element.
<nav>
<ul>
<li><a href="#" title="Link">...</a></li>
<li><a href="#" title="Link">...</a></li>
</ul>
</nav>

Article
learn.shayhowe.com/html-css/elements-semantics

4/6

1/15/13

Elements & Semantics - A Beginner's Guide to HTML & CSS

The article block level element is very similar to that of a div or section however it is specifically defined as an element which should include independent, self-contained content
that may be independently distributable or reusable. Most often article will fall within blogs and other publishing websites as a block of published content. When deciding to use the
article element determine if the content within the element could be replicated elsewhere without any confusion. The content within the article alone must make sense, and be
able to be distrbuted elsewhere, such as within an RSS feed.
<article>...</article>

Section
A section is more likely to get confused with a div than an article. As a block level element, section is defined to represent a generic document or application section. Where
a section differentiates itself from a div is that a section is not to be used as a convenience for styling or scripting purposes.
That said you can apply styles to a section however you shouldnt be using a section aimlessly with the sole purpose of adding styles. Reserve the section element for large
parts of a page worthy of the element.
<section>...</section>

Deciding When to Use a section or div


The best way to determine when to use a section versus a div is to look at the actual content at hand. If the block of content could exist as a record within a database and isnt
explicitly needed as a CSS styling hook then the section element is most applicable. Sections should be used to break a page up, providing a natural hierarchy, and most commonly
will have a proper heading.
A div on the other hand may be used to specifically tie styles to a block of content. As an example, if a couple paragraphs need to stand out above the rest of the content on on a
page they should be wrapped in a div. That div then may have the proper styles applied to it, perhaps a background, border, or the alike.

Aside
To accompany the header and footer elements there is also the aside block level element. An aside defines content related to the document or section surrounding it. As with
header and footer elements, the aside can be used multiple times per page, so long as each use is practical.
Please keep in mind that the aside is a block level element, in which it will appear on a new line and occupy the full width of the page or any container. If you would like to get the
aside to appear to the right or left of a block of content you will need to float the aside element. Dont worry about floats right now, we will learn about floating and positioning
content in an upcoming lesson.
<aside>...</aside>

Footer
The footer is identical to that of the header however for the bottom of a page, article, section, or other segment of a page. A footer should not stem away from the document or
section at hand and its context should include relative information.
<footer>...</footer>

D.R.Y. Dont Repeat Yourself


One principle of development is D.R.Y., also known as dont repeat yourself. Within CSS this principle can speak volumes as it is easy to continually write the same styles over and
over again. Dont. CSS was designed in a way to allow you to cascade styles and use classes so that you easily apply and inherent styles. The end goal is to write clean and light
code, of which is semantic and easily managed.

Resources & Links


Semantic code: What? Why? How? via Boagworld
HTML5 Doctor
The i, b, em, & strong Elements via HTML5 Doctor
The Full mailto Link Syntax via Joost de Valk
New Structural Elements in HTML5 via Dev.Opera

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your friends.

Lesson 1 Terminology, Syntax, & Introduction

Lesson 3 Box Model & Positioning

learn.shayhowe.com/html-css/elements-semantics

5/6

1/15/13

Elements & Semantics - A Beginner's Guide to HTML & CSS

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shayhowe.com/html-css/elements-semantics

6/6

1/15/13

Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 14

Tw: 74

l: 33

+1: 2

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 3

Box Model & Positioning


In this Lesson 3
HTML

Box Sizing
CSS

The Box Model


Height & Width
Margin & Padding
Borders
Floating Elements
Positioning Elements
learn.shay howe.com/html-css/box-model

1/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

One principle necessary to fully understand HTML and CSS is the box model. The box model concept states
that every element on a page is a rectangular box, and may include margins, padding, and borders.
Thats worth repeating. Every element on a page is a rectangular box.
Having a general understanding of the box model is crucial as websites are primarily built around it. Gaining an
understanding of the box mode can be frustrating and difficult, but necessary in order to build prevalent websites.
Additionally, knowing how to position elements on a page to build a layout is equally important. There are a few
different ways to position elements, each of which depend on the content and circumstance.

Box Sizing
By now you are fully aware that every element on a page, displayed block or inline, is a rectangular box. These
boxes can come in different sizes and may have margins, padding, and borders to alter their size. The formation
of all of these properties together is referred to as the box model. Lets take a look at the box model, along with
these CSS properties to better understand what we are working with.

Fig. 3.01 Looking at each element individual you can see how they are rectangular, reguardless of
their actual presented shape.

The Box Model


As we know, every element is a rectangular box, of which includes a height and width, and may consist of
different margins, padding, and borders. All of these values put together build what is known as the box model.
The box starts with the height and width of an element, which may be determined by the type of element, the
contents of the element, or by specified height and width properties. The height and width is then followed
by the padding and border. The margin follows the border, however it is not technically included within the
actual size of the box. Although its not included within the size of the box, the margin does help define the box
model.
learn.shay howe.com/html-css/box-model

2/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

div {
background: #fff;
border: 6px solid #ccc;
height: 100px;
margin: 20px;
padding: 20px;
width: 400px;
}

To break down the total width of an element, including the box model, use the formula:
margin-right + border-right + padding-right + width + padding-left + border-left +

margin-left

In comparison, the total height of an element, including the box model, can be found using the formula:
margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-

bottom

Fig. 3.02 The box model broken down.


Using the formulas and box context above we can find the total height and width of our example.
Width: 492px = 20px + 6px + 20px + 400px + 20px + 6px + 20px
Height: 192px = 20px + 6px + 20px + 100px + 20px + 6px + 20px
Lets take a close look at all of the properties that go into forming the box model.

Height & Width


Every element has an inherited height and width. Depending on the purpose of the element the default height
and width may be adequate. If an element is key to the layout and design of a page it may require a specified
height and width. In this case the default values for block level elements may be overridden.

CSS Height Property


learn.shay howe.com/html-css/box-model

3/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

The default height of an element is determined by its content. An element will expand and contract vertically as
necessary to accommodate its content. To set a specific height for a block level element the height property is
used.
div {
height: 100px;
}

CSS Width Property


The default width of an element depends on its display type. Block level elements have a default width of
100%, consuming the entire horizontal space available. Inline elements expand and contract horizontally to
occupy their content then stop. Since inline level elements cannot have a fixed size, the width property, as with
the height property, is only relevant to block level elements.
div {
width: 400px;
}

Margin & Padding


Every browser applies a general margin and padding to elements to help with legibility and discourse. The
default values for these properties differ from browser to browser and element to element. In lesson one we
discussed using a CSS reset to tune all of these default values down to zero. Using a reset allows us to work
from a common ground and allows us to specify our own values.

CSS Margin Property


The margin property allows us to set the length of space surrounding an element. Margins fall outside of any
border and are completely transparent. Margins can be used to help position elements within a particular place
on a page or to simply provide breathing room, keeping all other elements a safe distance away.
div {
margin: 20px;
}

CSS Padding Property


The padding property is very similar to that of the margin property, however it falls within any elements
border. Paddings will also inherit any backgrounds of an element. Padding is used to provide spacing within an
element, not for positioning an element like the margin property.
div {
padding: 20px;
}

learn.shay howe.com/html-css/box-model

4/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

Fig. 3.03 A box model breakdown using margins for spacing between elements and padding for
spacing inside of an element.

Margin & Padding Declarations


The values for margin and padding come in both long and short hand form. To set one value for all four sides
of an element simply specify one value.
div {
margin: 20px;
}

To set one value for the top and bottom and another value for the left and right of an element specify two values,
top and bottom first then left and right.
Top & Bottom Left & Rightdiv {
margin: 10px 20px;
}

To set unique values for all four sides specify them in the order of top, right, bottom, and left
Top, Right, Bottom, & Leftdiv {
margin: 10px 20px 0 15px;
}

Additionally, you can set the value for one side at a time using a unique property. Each property starts with
margin or padding respectfully and is then followed with a dash and the side of the box to which the value is to
be applied, top, right, bottom, or left. As an example, the padding-left property takes one value and
will set the left padding for that element.
div {
margin-top: 10px;
padding-left: 6px;
}

Borders
Borders fall between the padding and margin and provide an outline around an element. Every border needs
three values, a size, style, and color. Shorthand values fall in the order of size, style and color. Longhand, these
three values can be broken up into border-size, border-type, and border-color.
Most commonly you will see one sized, solid, single colored borders. Borders do however have the capability to
come
in numerous sizes, shapes, and colors.
learn.shay
howe.com/html-css/box-model
5/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

come in numerous sizes, shapes, and colors.


div {
border: 6px solid #ccc;
}

Length Values
There are a handful of length values available to use with margins, padding, and borders, including relative and
absolute values.
Relative values are correlative to the element of which the value is being applied. These values may include em
and percentages.
Absolute values are fixed units of measurement regardless of the element. These values may include pixels,
points, inches, centimeters, and more.

Floating Elements
Outlining elements within the box model is only half the battle to coding a page layout. The other half involves
knowing how to properly align all of the different elements on the page. One way to position elements along side
one another is to use the float property. The float property allows you to take elements and float them right
or left, positioning them directly next to or opposite each other.
Take the common page layout with a section and an aside. The section and aside, as block level
elements, will be stacked on top of one another by default. However, we want them to sit side by side. By giving
each element a specific width and floating one of them left and the other to the right we can position them
correctly.

Fig. 3.04 A common page layout including floats and clears.


There are a few important things to note when floating elements. The first being, when floating an element it is
going to float all the way to the edge of its parent container. If there isnt a parent element it will float all the way
to the edge of the page. Additionally, when floating an element without setting a specific width, other elements
will begin to line up around it within the natural flow of the page.
6/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

section {
float: left;
margin: 10px;
width: 600px;
}
aside {
float: right;
margin: 10px;
width: 320px;
}

Clearing Floated Elements


Whenever an element is floated, it breaks the normal flow of a page and other elements will wrap around the
floated one as necessary. Sometimes this is good, such as when floating an image to the side of a block of
content, and sometimes this is bad.
To float an element, or handful of elements, and then return the document to its normal flow you use the clear
property. The clear property acts on the element it is applied to and returns the document back to its normal
flow, clearing every floated element up to that point.
In the example above, with the section and aside floated, we want to apply a clear to the footer to force it
to fall below the two floated elements.
footer {
clear: both;
}

Positioning Elements
Apart from floating elements you can also use the position property to align elements. The position property
comes with a couple of different values, all of which have different functionalities behind them.
The default position value is static, which keeps elements within their normal flow. The relative value
allows you to use box offset properties such as top, right, bottom and left. The absolute and fixed
values work with box offset properties too, but break the element from the normal flow of a document. These
values, absolute and fixed, correspond directly with an elements parent who has a position value of
relative.

Fig. 3.05 Absolutely positioning an unordered list within a header.


Taking the example above, the header element has been assigned a position of relative making it function
learn.shay howe.com/html-css/box-model

7/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

as a static element yet act as the primary container to any absolutely positioned element within it. The ul is then
absolutely positioned 10px way from the top right of the header element.
Altogether the code for this example would look as follows.
HTML

<header>
<ul>...</ul>
</header>
CSS

header {
position: relative;
}
ul {
position: absolute;
right: 10px;
top: 10px;
}

Box Offset Properties


So long as an elements position is not set to static the box offset properties may be used. These offset
properties include top, right, bottom and left. Depending on the property, they position an element in the
direction specified, top, right, bottom or left.
For example, bottom: 32px; will position an element 32 pixels from the bottom of its parent element with a
position value of relative. In contrast, bottom: -32px; will position an element 32 pixels below its parent
element with a position value of relative.
Box offset properties may be used in pairs, top or bottom and left or right. CSS will cascade these
properties accordingly and implement the last two valid declarations.
Grids & Frameworks
There are numerous tools and practices to consider when building the layout of a site. Grids and frameworks
have risen to the forefront.
Grids, both vertical and baseline, provide a great way to add cadence to your website and keep everything
aligned. There are a handful of different recommended grids that have become popular over the years. You can
pick from one of them or implement your own, whatever works best for your project.
Frameworks provide a way to rapidly build a website based on a set of predetermined standards. Depending
on the project, frameworks can provide a great starting point or even a complete solution. They can also cause
more trouble than theyre worth. Before getting too far over your head, research the framework and make sure
you are comfortable working with it and editing it.
learn.shay howe.com/html-css/box-model

8/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

Resources & Links


CSS Length Values via Mozilla Developer Network
HTML Borders via Quackit.com
The CSS Box Model via CSS-Tricks
CSS Float Theory via Smashing Magazine
CSS Positioning 101 via A List Apart
Resources for Grid-Based Design via Vandelay Design

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share
it with your friends.

Lesson 2 Elements & Semantics

Lesson 4 Typography

An Advanced Guide to HTML & CSS

learn.shay howe.com/html-css/box-model

9/10

1/15/13

Box Model & Positioning - A Beginner's Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the
latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

learn.shay howe.com/html-css/box-model

Get Updates

10/10

1/15/13

Typography - A Beginner's Guide to HTML & CSS


Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 1

Tw: 74

l: 33

+1: 0

whois

source

Rank: 177977

Density

Diagnosis

Links: 14(1) | 19(18)

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 4

Typography
In this Lesson 4
HTML

Formatting Content
Citations & Quotes
CSS

Text Color
Font Properties
Text Properties
Web Safe Fonts
Embedding Web Fonts
Typography on the web has grown substantially over the last few years. There are a couple of different reasons for this rise in popularity, however none more recognized than the
ability to embed your own web fonts on a website.
In the past designers were limited to a small number of typefaces they could use on a website. These typefaces were based off what were the most commonly installed fonts on a
computer, thus most likely to render properly on screen. Now with the ability to embed fonts designers have a much larger palette of typefaces to choose from.
While the ability to embed fonts opens up a door to all new typefaces it also requires designers to know the basic principles of typography. Translating these basic principles of
typography into HTML and CSS helped build the core of online typography and text styling.
Typeface vs. Font
The terms typeface and font are often interchanged, causing confusion. Below is a breakdown of exactly what each term stands for, hopefully adding context to how the two terms
should be used.
A typeface is what you see. It is the artistic impression of how text looks, feels, and reads.
A font is a file that includes a typeface. Using a font on a computer allows that computer to access the typeface.
One way to help distinguish the difference between a typeface and font is to compare them to a song and MP3. A typeface is very similar to a song in that it is a work of art. It is
created by an artist, or artists, and is open to interpretation. A font on the other hand is very similar to an MP3 in that it is not the artistic impression, only a method of delivering the
artistic value.

Formatting Content
Within the previous lesson, Elements & Semantics, we talked about how to semantically add content to a page. This lesson is worth reviewing as it will play a part in our discussion on
typography. As a brief review lets recap headings, paragraphs, and how to bold or italicize text.

Headings
learn.shayhowe.com/html-css/typography

1/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

Heading elements come in six different levels, h1 through h6, each of which act as a supplementary heading to the one above it. The h1 heading should be reserved for larger, more
important headings while the other headings should support the h1 above it. Using the HTML5 document structure elements we have the ability to reuse these headings, however we
must use proper judgement in doing so.
<h1>Lorem ipsum dolor sit amet...</h1>
<h2>Pellentesque habitant morb...</h2>

Paragraphs
The paragraph element, simply put, is the preferred way to add paragraphs of content to a page. Each individual paragraph should be wrapped with an opening and a closing p tag.
<p>Id quil una virtute ponunt...</p>

Bolding Text
To bold text the strong element is used. The strong element not only makes text bold but it also semantically notes it as important text on a page.
<p>Duis in <strong>voluptate</strong> velit cillum.</p>

Italicizing Text
Italicizing text is accomplished using the em element. The em element is also known to semantically mean that the text should include a stressed emphasis.
<p>Quae vivendi <em>putanda</em> est, expeteretur nih.</p>

Text Color
Typically one of the first things a designer or developer will do when building a website is choose the text color and typeface. While there are a number of other properties that could
be changed, these two have the largest impact on the look of a page in the smallest amount of time. Getting rid of the browser defaults and using your own text color and typeface
immediately begins setting the tone of the page.
The only item needed to set the color of text is the color property. The color property accepts one value, however in many different formats. You can use keywords, hexadecimal
values, RGB, RGBa, HSL, and HSLa. Most commonly seen are hexadecimal values as they provide the most control with the least amount of effort. RGBa values are on the rise with
CSS3 to provide transparent colors, however they are not fully supported within all browsers and should be used with a hexadecimal fallback accordingly.
body {
color: #555;
}

Shorthand Hexadecimal Color Values


Hexadecimal color values, like many other property values, allow us to use shorthand values. Hexadecimal colors are declared using the pound sign (#) followed by six characters.
These characters identify the specific color to be used and often come in patterns of pairs, the first two characters, the middle two characters, and the last two characters. These
patterns can then be compressed down from six numbers into three for the color value. For example, the color value #555555 can be shortened to #555, #ff6600 can be shortened
to #f60, #ffff00 can be shortened to #ff0, and so on.

Font Properties
CSS provides a lot of different properties to edit the look and feel of text on a page. The properties to do so are broken down into two categories, font based properties and text
based properties. Most properties corresponding to these categories will be prefaced with either font-* or text-*. To begin well discuss the font based properties.

Font Family
The font-family property is used to declare which font, and fallback fonts, should be used to display text. The value of the font-family property contains multiple font names, all
comma separated. The first font declared, all the way to the left, is the primary font choice. Should the first font not be available alternative fallback fonts are declared from left to
right. Font names including two or more words need to be wrapped in quotation marks. Additionally, the last font should be a keyword value, which will pick the system default font
in the specified type.
p {
font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif;
}

Font Size
Using the font-size property provides the ability to set the size of text using common length values, including pixels, em, percents, points, and font-size keywords. More and
more often the pixel value is used as it provides the most control over a fonts size. Previously, em and percentage values used to be fairly popular because they allow the text to scale
relatively when a user would zoom in on a page within the browser. Now most browsers are able to scale pixels as well, eliminating a large need for em and percentage values.
p {
font-size: 13px;
}

Font Style
To change text to italicized and vice versa the font-style property is utilized. The font-style property accepts four keyword values, including normal, italic, oblique, and
inherit. Of these four, most commonly used are normal and italic. italic being used to set text to italic and normal being used to return text to its normal style.
learn.shayhowe.com/html-css/typography

2/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

p {
font-style: italic;
}

Font Variant
It isnt often but occasionally text will need to be set in small capitals, or small caps. For this specific case the font-variant property has been created. The font-variant
property accepts three values, including normal, small-caps, and inherit. The most typically seen values are normal and small-caps to switch between normal and smallcaps, and vice versa. If the typeface being used does not support small caps the variant of the font will not change. Always double check support for a typeface before using this
property.
p {
font-variant: small-caps;
}

Font Weight
Ever so often the need to set text as bold or set the specific weight of bold text appears, for this case we can use the font-weight property. Generally speaking, the font-weight
property is used with the keyword values normal, bold, bolder, lighter, and inherit. Of these keyword values, it is recommended to primarly use normal and bold to
change text from normal to bold, and vice versa.
On top of keywords the numeral values 100, 200, 300, 400, 500, 600, 700, 800, and 900 exist. The order of these weights start with the thinnest weight, 100, and scale up to the
thickest weight, 900. These values pertain specifically to typefaces that have multiple weights, more than normal (keyword for 400) and bold (keyword for 700). Before using numeral
values check to see exactly what weights the typeface you are using comes in. Attempting to use thin weight of 100 might sound like a good idea, however that weight might not exist
within your typeface, thus it will not work.
p {
font-weight: bold;
}

Line Height
Line height, the distance between two lines of text known as leading, is declared using the line-height property. The line-height takes all general length and numeral values, as
mentioned above within font-size. The best practice for legibility is to set the line-height to around one and half times that of your font-size. This could be quickly
accomplished by setting the line-height to 150%. However, if you are working with a baseline grid having a little more control over your line-height using pixels may be
preferred.
Line height may also be used to vertical center single lines of text within an element. Setting an elements line-height to the same value as the elements height will vertically
center the text. This technique is commonly seen within buttons, alert messages, and other single line text blocks.
p {
line-height: 20px;
}

Shorthand Font Properties


All of the font based properties listed above may be combined and rolled into one font property and shorthand value. The order of these properties should fall as follows from left to
right: font-style, font-variant, font-weight, font-size, line-height, and font-family. As a shorthand value these property values can be stacked from left to right
without the use of a comma, except for font names. A forward slash, /, separator is needed between the font-size and line-height property values.
It is also worth noting that every property value is optional except the font-size and font-family property values. That said, you can often find the font property and shorthand
value to include only the font-size and font-family values.
p {
font: italic small-caps bold 13px/20px 'Helvetica Neue',
Arial, Helvetica, sans-serif;
}

Font Properties Example


HTML

<h2><a href="#" title="Sample Blog Post Title">Sample Blog Post Title</a></h2>


<p class="byline">Posted by Shay Howe on February 5th, 2012</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla fringilla vehicula nisi vitae rutrum. Donec laoreet, arcu in elementum, dui mi
CSS

h2, p {
color: #555;
font: 13px/20px Arial, 'Helvetica Neue', 'Lucida Grande', sans-serif;
}
a {
color: #8ec63f;
}
a:hover {
color: #f7941d;
}
h2 {

learn.shayhowe.com/html-css/typography

3/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

h2 {
font-size: 22px;
font-weight: bold;
margin-bottom: 6px;
}
.byline {
color: #8c8c8c;
font-family: Georgia, Times, 'Times New Roman', serif;
font-style: italic;
}

Demo

Sample Blog Post Title


Posted by Shay Howe on February 5th, 2012
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla fringilla vehicula nisi vitae rutrum. Donec laoreet, arcu in elementum, dui mi auctor tortor, et lorem massa orci
Continue reading

Text Properties
Knowing how to set the family, size, style, variant, weight, and line height of a font is only half the battle. Additionally you can decide how to align, decorate, indent, transform, and
space text.

Text Align
Aligning text is an important part of building a rhythm and flow to a page, using the text-align property such alignment can be set. The text-align property has five values,
comprising of left, right, center, justify, and inherit. All of these values are fairly straightforward and behave as expected. The text-align property, however should not
be confused with the float property. The text-align values left and right will align text within an element, where the float values left and right will move the entire
element. More information on the float property can be found in the Box Model & Positioning lesson.
p {
text-align: center;
}

Text Decoration
The text-decoration property provides a handful of ways to spruce up text, accepting the following keyword values: none, underline, overline, line-through, blink, and
inherit. Use of the text-decoration property varies but the most popular use case is to underline links. The blink value exists, however is not recommended to be used as it
can be extremely distracting. Depending on the semantic state, the line-though value may be substituted with the del element (used to note text to be removed from a document)
or the s element (used to note text no longer accurate or relevant). All other values can be utilized accordingly.
p {
text-decoration: underline;
}

Text Indent
The text-indent property can be used to indent text like seen within printed books. The text-indent property can be used to indent text both inward and outward, all depending
on the set value. The values available for this property are the common length values used within other properties, including pixels, points, percentages, and so forth.
p {
text-indent: 20px;
}

Text Shadow
The text-shadow property allows you to add a shadow, or multiple shadows, to text. The property requires four values all listed one after the other from left to right. The first three
values are all lengths while the last value is a color. Within the three length values the first value determines the shadows horizontal offset, the second value determines the shadows
vertical offset, and the third value determines the shadows blur radius. The fourth, and last, value is the shadows color, which can be any of the color values used within the color
property.
Text shadows can also be chained together using comma separated values, adding more than one shadow to the text. Adding numerous shadows allows you to place them above and
below the text, or in whatever variation you desire.
p {
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
}

Text Transform
Similar to the font-variant property is the text-transform property. While the font-variant property looks for an alternate variant of small capitals within a typeface the
text-transform property will change the text inline. The text-transform property accepts five values: none, capitalize, uppercase, lowercase, and inherit.
The capitalize value will capitalize the first letter of each word, the uppercase value will capitalize all letters, and the lowercase property will make every letter lowercase. Using
will take any of these inherited values and roll them back to the text default.

none

learn.shayhowe.com/html-css/typography

4/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

p {
text-transform: uppercase;
}

Letter Spacing
Using the letter-spacing property you can adjust the tracking between letters on a page. Using positive or negative length values you can adjust the spacing between letters,
pushing them further apart or pulling them closer together. Using the keyword value none will return the space between letters back to their normal distance. Using relative length
values with letter-spacing will help ensure you are obtaining the correct amount of spacing, however it is recommended to always double check the text.
p {
letter-spacing: -.5em;
}

Word Spacing
Much like the letter-spacing property you can also adjust the spacing between words using the word-spacing property. The word-spacing property accepts the same length
values and keywords and applies those values to spacing apart words, not letters.
p {
word-spacing: .25em;
}

Text Properties Example


HTML

<h2><a href="#" title="Sample Blog Post Title">Sample Blog Post Title</a></h2>


<p class="byline">Posted by Shay Howe on February 5th, 2012</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla fringilla vehicula nisi vitae rutrum. Donec laoreet, arcu in elementum, dui mi
CSS

h2, p {
color: #555;
font: 13px/20px Arial, 'Helvetica Neue', 'Lucida Grande', sans-serif;
}
a {
color: #8ec63f;
}
a:hover {
color: #f7941d;
}
h2 {
font-size: 22px;
font-weight: bold;
letter-spacing: -.9px;
margin-bottom: 6px;
}
h2 a {
text-shadow: 1px 1px 0 #75a334;
}
h2 a:hover {
text-shadow: 1px 1px 0 #d48019;
}
p {
text-indent: 15px;
}
.byline {
color: #8c8c8c;
font-family: Georgia, Times, 'Times New Roman', serif;
font-style: italic;
text-indent: 0;
}
p a {
font-size: 11px;
font-weight: bold;
text-decoration: underline;
text-transform: uppercase;
}

Demo

Sample Blog Post Title


Posted by Shay Howe on February 5th, 2012
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla fringilla vehicula nisi vitae rutrum. Donec laoreet, arcu in elementum, dui mi auctor tortor, et lorem massa orci
Continue reading

learn.shayhowe.com/html-css/typography

5/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

Web Safe Fonts


By default there a few specific fonts that are pre-installed on every computer, tablet, cell phone, or other browsing capable device. Being installed on every device allows these fonts
to be used freely online knowing that no matter what device is browsing the site, the font will render properly. These fonts have become known as web safe fonts. There are only a
handful of web safe fonts, of which the safest ones to use are listed below.
Arial
Courier New, Courier
Garamond
Georgia
Lucida Sans, Lucida Grande, Lucida
Palatino Linotype
Tahoma
Times New Roman ,Times
Trebuchet
Verdana

Embedding Web Fonts


In recent years an alternative to web safe fonts has arisen. Now the ability exists to upload fonts to a server and include them on a website via the CSS @font-face property. This
ability has done wonders to online typography. Now, more than ever, type is coming to life online.
@font-face {
font-family: 'Bryant Normal';
src: url('bryant-normal.eot');
src: url('bryant-normal.eot') format('embedded-opentype'),
url('bryant-normal.woff') format('woff'),
url('bryant-normal.ttf') format('truetype'),
url('bryant-normal.svg') format('svg');
}
body {
font-family: 'Bryant Normal', 'Helvetica Neue', Arial, Helvetica, sans-serif;
}

There are, however, some minor pitfalls. Having the ability to use any typefaces on a website does not mean you legally have the authority to do so. Typefaces are a work of art and
posting them on your server may allow free reign for others to steal them. The authority to use a typeface all depends on the licensing you have been warranted.
Fortunately, the value for new typefaces has been recognized and companies have begun developing ways to license and include new fonts on websites. Some of these companies,
Typekit and Fontdeck, work off a subscription model for licensing fonts, while others, Google Fonts, license the fonts for free. Before uploading any fonts make sure you have the
correct permission to do so. If not, look into one of the companies mentioned to see if they might be able to help you find the same font or a suitable alternative.
Another minor pitfall is browser support. Although the @font-face property has been around for a while its support within older browsers is nothing to cheer about. Recent
browsers will handle these fonts without any issues while some of the older browsers will not. Luckily, we are able to use these new fonts and specify other fonts to fall back on.
These fallbacks come in the way of the font-family property discussed above.

Citations & Quotes


Writing online may lead to citing different titles of work or quotations. Additional quotations, including dialog, prose, and quotations from external sources may also exist within a
page. There are a mix of different citation and quotation cases, all of which can be covered semantically with HTML using the cite, q, and blockquote elements.
Knowing when to use which elements and attributes to properly markup citations and quotes takes a bit of practice. In general remember, the cite element is used to reference a title
of work, the q element is used for short, inline quotations, and the blockquote is used for longer, external quotations.

Citing a Title of Work


The cite element is used within HTML to specifically cite a title of work. The cite element should not be confused with the cite attribute. The element provides semantic context
to the title of work, where the attribute has a URI value that serves as a reference source. The cite element should be specifically reserved for a title of work and shouldnt include
any other context about the source. A title of work may include a book, movie, song, or so forth. For additional reference, it helps to include a hyperlink to the original source if
relevant.
<p><cite><a href="http://www.amazon.com/Steve-Jobs-Walter-Isaacson/dp/1451648537" title="Steve Jobs">Steve Jobs</a></cite> by Walter Isaacson is

Citing a Title of Work Demo


Steve Jobs by Walter Isaacson is truly inspirational.

Dialog & Prose Quotation


Quoting dialog or prose happens quite often inline amongst other text. For this particular case the q inline element, better known as quote, should be applied. The q element is used to
semantically note dialog or prose and shouldnt be used for any other quotation purposes.
Dialog & Prose Quotation<p>Steve Jobs once said, <q>One home run is much better than two doubles.</q></p>

Dialog & Prose Citation


An optional attribute to include on the q element is the cite attribute. The cite attribute acts as a citation to the quote in the form of a URI. This attribute doesnt alter the
appearance of the element, it simply adds value to screen readers and other devices. Since the attribute isnt viewable within the browser it is recommended to provide a hyperlink

learn.shayhowe.com/html-css/typography

6/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

appearance of the element, it simply adds value to screen readers and other devices. Since the attribute isnt viewable within the browser it is recommended to provide a hyperlink
including this source next to the actual quotation if available.

Dialog & Prose Citation<p><a href="http://www.businessweek.com/magazine/content/06_06/b3970001.htm" title="Steve Jobs' Magic Kingdom">Steve Jobs<

Dialog & Prose Demo


Steve Jobs once said, One home run is much better than two doubles.

External Quotation
To quote a large block of text, most commonly from an external source and spanning several lines, the blockquote element is used. The blockquote is a block level element that
may include other block level elements nested inside of it including headings and paragraphs.

<blockquote>
<p>In most peoples vocabularies, design is a veneer. Its interior decorating. Its the fabric of the curtains, of the sofa. But to me, nothi
<p> Steve Jobs in Fortune Magazine</p>
</blockquote>

External Citation
Longer quotes used within the blockquote element should always include a citation. This citation may be extremely simple, such as an author or source, however there may also be
fairly more information including multiple citations and links to additional references.
A longer quotation may include a mix of both the cite attribute and cite element. The cite attribute can be included within the blockquote element the same as used within the q
element above. The cite element can fall after the actual quote itself and help specify the title of work from which the quote comes from if relevant.
Since the cite attribute and cite element are purely semantic and dont add any visual reference for users hyperlinks are also preferred when available. These hyperlinks should
highlight both the origin of the quote (author, artist, etcetera) and the title of work in which it first appeared.

<blockquote cite="http://money.cnn.com/magazines/fortune/
fortune_archive/2000/01/24/272277/index.htm">
<p>In most peoples vocabularies, design is a veneer. Its interior decorating. Its the fabric of the curtains, of the sofa. But to me, nothi
<p> <a href="http://en.wikipedia.org/wiki/Steve_Jobs" title="Steve Jobs">Steve Jobs</a> in <cite><a href="http://money.cnn.com/magazines/fortu
</blockquote>

External Demo
In most peoples vocabularies, design is a veneer. Its interior decorating. Its the fabric of the curtains, of the sofa. But to me, nothing could be further from the meaning
of design. Design is the fundamental soul of a human-made creation that ends up expressing itself in successive outer layers of the product.
Steve Jobs in Fortune Magazine
Automating Quotation Marks with CSS
Rather than adding in your own quotation marks in HTML there is the ability to add them in automatically with CSS. In the past support to get quotation marks to display properly
with CSS has been weak, due to browser language support, however with more modern browsers language support is getting better.
To automatically add quotation marks within CSS the before and after pseudo-elements are used. These pseudo-elements use the quotes and content properties to
dynamically add quotation marks as necessary.
Below is an example how these pseudo-elements and properties work to add quotation marks to the q element. For more information please take a deeper look into both pseudoelements and how to use quotation marks.
q {
quotes: '' '' '' '';
}
q:before {
content: '';
content: open-quote;
}
q:after {
content: '';
content: close-quote;
}

Resources & Links


Text styling with CSS via Dev.Opera
Quoting and citing with blockquote, q, cite, and the cite attribute via HTML5 Doctor
CSS Font Shorthand Property Cheat Sheet via Impressive Webs
The Elements of Typographic Style by Robert Bringhurst

Complete! Any questions?


Share
Tweet
learn.shayhowe.com/html-css/typography

7/8

1/15/13

Typography - A Beginner's Guide to HTML & CSS

Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your friends.

Lesson 3 Box Model & Positioning

Lesson 5 Backgrounds & Gradients

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shayhowe.com/html-css/typography

8/8

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 8

Tw: 74

l: 33

+1: wait...

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 5

Backgrounds & Gradients


In this Lesson 5
CSS

Background Color
Background Image
Gradient Backgrounds
Multiple Backgrounds
CSS3 Background Properties
Backgrounds are an important part to CSS as they allow you to easily change the composition of an element.
They can be used for decoration while setting the scene within an element. They can provide visual context for an
elements content, enhancing usability. With use cases large and small, backgrounds have a significant impact on
the overall design of a website.
Adding a background to an element can be accomplished in a few different ways, most often in the form of a
learn.shay howe.com/html-css/backgrounds-gradients

1/11

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

solid color, an image, or a combination of the two. The ability to control exactly how a background is
implemented on an element provides greater direction to the overall appearance.
With CSS3, new backgrounds and capabilities were introduced, including the ability to include gradient
backgrounds and multiple background images on a single element. These progressions are becoming widely
supported within all browsers and expand the possibilities of modern web design.

Adding a Background Color


The quickest way to add a background to an element is to add a single color background using the background
or background-color property. The background property accepts colors and images, while the
background-color property is used strictly for background colors. Either property will work, which one you
decide to use depends on your preference and the case in which it is being used.
div {
background: #f60;
background-color: #f60;
}

When declaring a background color you have a few different options as far as what value to use. As with other
color values, you can pick from keywords, hexadecimals, RGB, RGBa, HSL, and HLSa. Most commonly seen
are hexadecimal values, however it is important to note RGBa and HLSa. These color spectrums allow us to use
opacity within our background via an alpha channel. If we are looking to use a 30% opaque black we can use
rgba(0, 0, 0, 0.3). These opaque backgrounds open a whole new level of control. As a word of caution,
RGBa and HLSa are not supported by every browser so it is important to provide a fall back CSS declaration
above the declaration using an opaque value.
div {
background: #b2b2b2;
background: rgba(0, 0, 0, 0.3);
}

Adding a Background Image


On top of adding a background color to an element you can also add a background image. Background images
work similarly to background color, however they also offer a few additional properties to finesse the images. As
before, you can use the background property or the background-image property. No matter which property
you use there must be an image source identified using the url value. The url value should be the background
images path.
div {
background: url('alert.png');
background-image: url('alert.png');
}

Marking up an image solely using the url value could provide undesirable results as it will repeat horizontally and
vertically from the top left of the containing element. Thankfully we can use the background-repeat and
background-position properties to straighten things out.
learn.shay howe.com/html-css/backgrounds-gradients

2/11

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

Background Repeat
By default, a background image will repeat indefinitely, both vertically and horizontally, unless specified.
Specifying a background repeat value can be done by adding it in after the url value on the background
property or by using the background-repeat property itself.
div {
background: url('alert.png') no-repeat;
background-image: url('alert.png');
background-repeat: no-repeat;
}

The background repeat takes four different values repeat, repeat-x, repeat-y, and no-repeat. The
repeat value is set by default and will repeat an image both vertically and horizontally. repeat-x will repeat the
image horizontally and repeat-y will repeat the image vertically. no-repeat simply means: display the
background image once and do not repeat at all.

Background Position
Using the background-position property you can control exactly where the background image is placed or
repeated from. As with the other background properties, a background position may be added using the
background property after the url value: or with the background-position property itself.
div {
background: url('alert.png') 10px 10px no-repeat;
background-image: url('alert.png');
background-position: 10px 10px;
background-repeat: no-repeat;
}

The background position requires two values, a horizontal offset (first) and a vertical offset (last). To set a
background position value you can use the top, right, bottom, left keywords, pixels, percentages, and
other length measurements. Keywords and percentages work very similarly. The keywords top left are
identical to the percentages 0 0, and the keywords right bottom are identical to the percentages 100% 100%.
One added value of percentages over keywords is the ability to center a background image by using 50% as a
value. To center the background image at the top of an element you could use the value 50% 0. Using pixels for
a background position is also popular, as pixels give you exact control of where your background will be
positioned.

Fig. 4.01 Using percentages and keywords to position a background image.

learn.shay howe.com/html-css/backgrounds-gradients

3/11

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

Alert Message Background Example


HTML

<p><strong>Warning!</strong> You are walking on thin ice.</p>


CSS

p {
background: #fff6cc url('warning.png') 15px 50% no-repeat;
border-radius: 6px;
border: 1px solid #ffd100;
color: #000;
padding: 10px 10px 10px 38px;
}

Demo
Warning! You are walking on thin ice.

Gradient Backgrounds with CSS3


Gradient backgrounds were introduced with CSS3, and praise rang out among designers and developers.
Although gradient backgrounds do not work in every browser, they are currently supported by all modern
browsers.
Gradient backgrounds are treated as a background image. You can create a gradient using the background or
background-image properties just like you would a regular background image. The value for these properties
vary a little depending on what type of gradient you are looking for: linear or radial.
Browser Specific Property Values
As CSS3 was introduced browsers began to slowly support different features, each browser maker
implementing new properties in a slightly different way. In doing so browsers used vendor prefixes to establish
exactly how their features should look and perform. Gradient backgrounds took the brunt of this as each
browser had its own preferred method for gradient values. Fortunately, most browsers have settled on a
standard, however it is still worth outlining support for all of them as a fall back.
While vendor prefixes are becoming less relevant it still doesnt hurt to use them for older browsers.
Mozilla Firefox: -mozMicrosoft Internet Explorer: -msOpera: -oWebkit (Chrome & Safari): -webkit-

Linear Gradient Background


learn.shay howe.com/html-css/backgrounds-gradients

4/11

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

For years designers and developers have been cutting up image files and using them as linear gradient
backgrounds. The process worked, but took a while to implement and was difficult to change. Fortunately, those
days are gone and linear gradient backgrounds can now be specified within CSS. If a color needs changed, there
is no need to recut an image and upload it to the server. Now all that is needed is a quick fix within CSS.
Beautiful.
div {
background:
background:
background:
background:
background:
background:
background:
}

#70bf32;
url('linear-gradient.png') 0 0 repeat-x;
-moz-linear-gradient(top, #a1e048, #6a942f);
-ms-linear-gradient(top, #a1e048, #6a942f);
-o-linear-gradient(top, #a1e048, #6a942f);
-webkit-linear-gradient(top, #a1e048, #6a942f);
linear-gradient(top, #a1e048, #6a942f);

Linear Gradient Background


Above is a breakdown of all of the different vendor prefixes and how linear gradient backgrounds are supported.
As you could guess the linear-gradient(top, #8ec63f, #45611f) value has become the most
supported and thus the standard. Moving forward, including radial gradients, well use this formatting but dont
forget the other values.
Taking a closer look at the value you will notice the keyword top declared. The keyword value states where the
background gradient will start and then move in the opposite direction. All top, right, bottom, and left
keywords are available to use. Combinations, right top and so on, are also available.
On top of keywords, degrees are also an acceptable value. If you want your gradient to start from the left
top you can use a the degree value 315deg.

Radial Gradient Background


While the linear gradient is perfect for building a gradient propagating in one direction, often the need for a radial
gradient arises. Radial background gradients work just like linear gradients and share a lot of the same values.
However, radial gradients can be quite complex with values for location, size, radius, and more. Well cover the
basics, but please feel free to take a deeper dive into radial gradients.
div {
background: #70bf32;
background: url('radial-gradient.png') 50% 50% no-repeat;
background: radial-gradient(circle, #a1e048, #6a942f);
}

Radial Gradient Background


CSS3 Gradient Background Generator
Programming CSS3 gradients from hand can be quite a task, especially if you are not all that familiar with them.
Fortunately, quite a few CSS3 gradient generators have popped up. Each generator works a little differently,
learn.shay howe.com/html-css/backgrounds-gradients

5/11

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

some coming with presets and examples and some having an expansive list of options. If interested, I recommend
doing some research to find the right generator for your needs.

Gradient Background Stops


So far we have discussed transitioning a gradient from one color to another, however if you want to transition
more than two colors you can use color stops. Instead of declaring two color values, you can declare numerous
values. The browser will transition from one to the next accordingly. Adding a length value to these color stops
determines at what position and distance the transition will take place. If no length value is declared the gradient
will transition evenly between all colors declared.
div {
background: #6c9730;
background: url('linear-gradient-stops.png') 0 0 repeat-y;
background: linear-gradient(left, #8dc63f, #d8ad45, #3b4b94);
}

Gradient Background Stops

Navigation Background Example


HTML

<ul>
<li
<li
<li
<li
</ul>

class="play"><a href="#" title="Play">Play</a></li>


class="back"><a href="#" title="Skip Backward">Skip Backward</a></li>
class="stop"><a href="#" title="Pause/Stop">Pause/Stop</a></li>
class="forward"><a href="#" title="Skip Forward">Skip Forward</a></li>

CSS

ul {
background: #f4f4f4;
background: linear-gradient(top, #fff, #eee);
border: 1px solid #ccc;
border-radius: 6px;
display: inline-block;
height: 22px;
list-style: none;
margin: 0 0 20px 0;
padding: 0 4px 0 0;
}
ul li {
height: 16px;
float: left;
padding: 3px;
text-indent: -9999px;
width: 16px;
}
ul li.play {
background: #f4f4f4;
learn.shay howe.com/html-css/backgrounds-gradients

6/11

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

background: linear-gradient(top, #fff, #eee);


border: 1px solid #ccc;
border-radius: 30px;
left: -4px;
padding: 7px;
position: relative;
top: -5px;

}
ul li a {
background: url('controls.png') 0 0 no-repeat;
display: block;
height: 16px;
width: 16px;
}
ul li.play a:hover {
background-position: 0 -16px;
}
ul li.back a {
background-position: -16px 0;
}
ul li.back a:hover {
background-position: -16px -16px;
}
ul li.stop a {
background-position: -32px 0;
}
ul li.stop a:hover {
background-position: -32px -16px;
}
ul li.forward a {
background-position: -48px 0;
}
ul li.forward a:hover {
background-position: -48px -16px;
}

Demo
Play
Skip Backward
Pause/Stop
Skip Forward

Multiple Background Images with CSS3


It used to be if you wanted an element to have more than one background you would have to wrap it with
another element and assign a background to the wrapping element. This created bloated code for the simple use
of adding additional backgrounds. Now with CSS3 we can use multiple background images on a single element
by chaining these background values together.
div {
background:
url('foreground.png') no-repeat 0 0,
url('middle-ground.png') no-repeat 0 0,
learn.shay howe.com/html-css/backgrounds-gradients

7/11

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

url('middle-ground.png') no-repeat 0 0,
url('background.png') no-repeat 0 0;

Not only can you chain background property values, you can also chain together background-repeat,
background-position, and other background related properties.

Multiple Background Images Example


HTML

<div>Dinosaur with Grass and Clouds</div>


CSS

div {
background:
url('dyno.png') no-repeat 380px 18px,
url('grass.png') no-repeat 0 100%,
url('sky.jpg') no-repeat 0 0;
border-radius: 6px;
height: 200px;
margin: 0 0 20px 0;
text-indent: -9999px;
}

Demo
Dinosaur with Grass and Clouds

New CSS3 Background Properties


Along with gradient backgrounds and multiple background images, CSS3 also introduces three new CSS
properties, background-size, background-clip, and background-origin.

CSS3 Background Size


The background-size property allows you to specify a specific size for your background image. The first
value declared is the width of the image and the second value is the height. These values may include any length
measurement or keyword, most notably pixels and percentages. If only one value is declared, the auto keyword
may be used to keep the proper image proportions.
div {
background: url('shay.jpg') 0 0 no-repeat;
background-size: 85% auto;
border: 1px dashed #8c9198;
height: 240px;
text-indent: -9999px;
width: 200px;
learn.shay howe.com/html-css/backgrounds-gradients

8/11

Cover & Contain Values


The cover keyword value specifies that the background image should be resized proportionally to completely
cover an element. How the background will be resized depends on the dimensions of the background and
element. While the background will hold its dimensions proportionally, the quality of the image may be resized in
a way that it distorts the image. Always make sure to check your work.
The contain keyword value will resize a background image proportionally to keep it within the confines of the
element. This may mean that there are parts of the element without a background, however the entire
background image will be visible. As with the cover keyword value, the resizing of the background image will
be proportional to the images dimensions, however it may result in a distorted image.
Shay Howe
Fig. 4.02 Using percentages and keywords to position a background image.

CSS3 Background Clip & Background Origin


The background-clip property specifies the area a background image will cover and the backgroundorigin property specifies where the background-position should originate. The introduction of these two
new properties also includes three new values: border-box, padding-box, and content-box. Each of these
three values may be used to set a value for the background-clip and background-origin properties.
Background Clip & Origindiv {
background: url('shay.jpg') 0 0 no-repeat;
background-clip: padding-box;
background-origin: border-box;
}

Fig. 4.03 The border-box value extends into the border of an element.

Fig. 4.04 The padding-box value extends into the padding of an element, but is contained within

1/15/13

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

any border.

Fig. 4.05 The content-box value is contained within the border and padding of an element.

Resources & Links


CSS3 Background via Russ Weakley
CSS3 Linear Gradients via Dev.Opera
CSS3 Radial Gradients via Dev.Opera
CSS Gradient Background Maker

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share
it with your friends.

Lesson 4 Typography

Lesson 6 Unordered, Ordered, & Definition Lists

An Advanced Guide to HTML & CSS

learn.shay howe.com/html-css/backgrounds-gradients

10/11

Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the
latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shay howe.com/html-css/backgrounds-gradients

11/11

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS
Info

PR: error

I: error

L: wait...

LD: 36

I: n/a

Rank: 238450

Age: wait...

I: 8

Tw: 74

l: 33

+1: 0

whois

source

Rank: 177977

Density

Diagnosis

Links: 13(1) |

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 6

Unordered, Ordered, & Definition Lists


In this Lesson 6
HTML

Unordered List
Ordered List
Definition List
Nested Lists
CSS

List Item Stylization


Horizontally Displaying List
Lists are an everyday part of life. To-do lists determine what to get done. Navigational routes provide a turn by turn list of directions. Recipes provide both a list of ingredients and a
list of instructions. With a list for nearly everything, its easy to see how they have become popular online.
HTML provides three different types of lists to choose from when building a page, including unordered, ordered, and definition lists. Unordered lists are for lists of items where order
isnt of important. While ordered lists place strong importance on the order of items. In the case where there is a list of terms and descriptions, perhaps for a glossary, definition lists
are available. Choosing what type of list to use, or to use a list at all, comes down to the content at hand and what is the most semantic choice for displaying the content in HTML.
With three different types of lists to use within HTML there are multiple ways to stylize them using CSS. Some of these options include deciding what type of bullet to use on a list.
Maybe the bullet should be square, round, numeral, alphabetical, or perhaps not even exist at all. Also, deciding if a list should be displayed vertically or horizontally plays a hand in
stylization.

Unordered List
Unordered lists are purely a list of related items, in which their order does not matter nor do they have a numbered or alphabetical list element. Creating an unordered list in HTML is
accomplished using the unordered list, ul, block level element. Each list item within an unordered list is individually marked up using the list item, li, block level element.
By default most browsers represent each list item with a solid dot. This solid dot is referred to as the list item element and can be changed using CSS.
<ul>
<li>iPad</li>
<li>iPhone</li>
<li>MacBook Air</li>
</ul>

Unordered List Demo


iPad
iPhone
MacBook Air

learn.shayhowe.com/html-css/ordered-unordered-definition-lists

1/7

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

Ordered List
The ordered list element, ol, works just like the unordered list element, including how each individual list item is created. The main difference between an ordered list and an
unordered list is that with an ordered list the order of which items are represented is important. Instead of showing a dot as the default list item element, an ordered list uses numbers.
Using CSS, these numbers can then be changed to letters, Roman numerals, and so on.
<ol>
<li>iPad</li>
<li>iPhone</li>
<li>MacBook Air</li>
</ol>

Ordered List Demo


1. iPad
2. iPhone
3. MacBook Air
With the introduction of HTML5 also came the introduction of two new attributes for ordered lists. These new attributes include start and reversed. The start attribute
determines from where an ordered lists should start. By default, ordered list start at 1. However, there may be a case where a list should start at 5. To do so simply set a start
attribute value of 5. Even though a list might not be ordered using numbers, the start attribute only accepts integer values.
<ol start="30">
<li>iPad</li>
<li>iPhone</li>
<li>MacBook Air</li>
</ol>

Start Attribute Demo


30. iPad
31. iPhone
32. MacBook Air
The reversed attribute allows a list to appear in a reversed order. A list of 5 items ordered 1 to 5 may be reversed and ordered from 5 to 1. The reversed attribute is a Boolean
attribute so it doesnt accept any values. Including it within the opening ol will reverse the list. As part of the HTML5 specification, not all browsers currently support the start and
reversed attributes.
Additionally, the value attribute may be used on an individual list item within an ordered list to change its value within the list. Any list item appearing below an item with an updated
attribute will then be recalculated accordingly. As an example, if the second item in a list has a value attribute of 9, the number of that list item will appear as the ninth item. All
other items below this one will be calculated as necessary, starting at ten.

value

<ol>
<li>iPad</li>
<li value="9">iPhone</li>
<li>MacBook Air</li>
</ol>

Value Attribute Demo


1. iPad
9. iPhone
10. MacBook Air

Definition List
Another type of list often seen online, yet quite different than that of an unordered or ordered list, is the definition list. Definition lists are used to outline multiple terms and descriptions,
often in the case of a glossary. Creating a definition list in HTML is accomplished using the dl element. Instead of using the li element to mark up list items, the definition list actually
requires two elements: the definition term element, dt, and the definition description element, dd.
A definition lists may contain numerous terms and descriptions, one after the other. Additionally, a definition lists may have multiple terms per description as well as multiple
descriptions per term. A single term may have multiple meanings and warrant multiple definitions. In comparison, a single description may be suitable for multiple terms.
In adding a definition term and description, the term must come before the description. Subsequently, the term and the following description will correspond to one another.
Definition lists do not have any list item elements, however the default styling of definition list does indent any descriptions. To adjust this indention you may use the margin and
properties within CSS.

padding

<dl>
<dt>study</dt>
<dd>the devotion of time and attention to acquiring knowledge on an academic subject, esp. by means of books</dd>
<dt>design</dt>
<dd>a plan or drawing produced to show the look and function or workings of a building, garment, or other object before it is built or made</dd
<dd>purpose, planning, or intention that exists or is thought to exist behind an action, fact, or material object</dd>
<dt>business</dt>
<dt>work</dt>
<dd>a persons regular occupation, profession, or trade</dd>
</dl>

learn.shayhowe.com/html-css/ordered-unordered-definition-lists

2/7

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

Definition List Demo


study
design

the devotion of time and attention to acquiring knowledge on an academic subject, esp. by means of books

a plan or drawing produced to show the look and function or workings of a building, garment, or other object before it is built or made
purpose, planning, or intention that exists or is thought to exist behind an action, fact, or material object
business
work
a persons regular occupation, profession, or trade

Nested Lists
One reason lists are extremely powerful within HTML is the ability to nest lists inside one another. Unordered lists can live within ordered or definition lists, definition lists can live
within unordered and ordered lists, and vice versa. Every list has the ability to be placed within another list, nesting them continually. The potential to do so doesnt provide free reign
to build pages completely out of lists. Lists should still be reserved specifically for where they hold the most semantic value.
Building a nested list is fairly simple. Determine where a nested list should appear, and rather than closing a list item, begin a new list. Once the nested list is complete, close the
wrapping list item and continue on with the original list.
<ol>
<li>Walk the dog</li>
<li>Fold laundry</li>
<li>Go to the grocery and buy:
<ul>
<li>Milk</li>
<li>Bread</li>
<li>Cheese</li>
</ul>
</li>
<li>Mow the lawn</li>
<li>Make dinner</li>
</ol>

Nested Lists Demo


1. Walk the dog
2. Fold laundry
3. Go to the grocery and buy:
Milk
Bread
Cheese
4. Mow the lawn
5. Make dinner

List Item Stylization


Unordered and ordered lists come with a list item element by default. For unordered lists this is typically a solid dot while ordered lists typically use numbers. Using CSS the content
and position of this element may be adjusted.

List Style Type Property


The list style type, list-style-type, property may be used to set the content and style of a list item. The available values range from squares, decimal numbers, all the way to
Armenian numbering. Any list style value can be added to either unordered or ordered list. In this sense it is possible to number an unordered list and vice versa. Doing so is not
recommended as it defeats the purpose of the chosen element and works against semantics.
A list style may be applied to an entire list or single list items, all depending on how the CSS is structured. Its rare that a single list item would need to be stylized differently than the
rest, however it is possible.
List Style Type Values
No list item
A filled circle
circle A hollow circle
square A filled square
decimal Decimal numbers
decimal-leading-zero Decimal numbers padded by initial zeros
lower-roman Lowercase roman numerals
upper-roman Uppercase roman numerals
lower-greek Lowercase classical Greek
lower-alpha / lower-latin Lowercase ASCII letters
upper-alpha / upper-latin Uppercase ASCII letters
armenian Traditional Armenian numbering
georgian Traditional Georgian numbering
none
disc

learn.shayhowe.com/html-css/ordered-unordered-definition-lists

3/7

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

ul {
list-style-type: circle;
}

List Style Type Demo


iPad
iPhone
MacBook Air

Using an Image as a List Item


There may come a time when the default list style type values are not enough, or you simply want to customize your own list item element. Changing the list item element is completely
possible. There are a few different ways to do so.
The original way is to use the list style image, list-style-image, property and pass it a URL value of an image to be used as the list item. While this works, it may not be
considered the best solution. A better way to use an image as a list item would be to use a background image in combination with some padding.
Setting a background image on the list item element, removing any default list-style, and then adding in some padding on the left hand side provides a list item a new element
style. Using a background image, as opposed to the list style image property, provides more control over positioning, allows the use of sprites, and offers other advantages.
li {
background: url('tick.png') 0 0 no-repeat;
list-style: none;
padding-left: 20px;
}

Using an Image as a List Item Demo


iPad
iPhone
MacBook Air

Using Characters as List Item Elements


For browsers that support the :before pseudo-element, the content property can be used to pass any HEX-escaped character encoding as the list item element. To start, the
default list item element needs to be removed by setting the list-style property to none. Next, the :before pseudo-element needs to be used in conjunction with the content
property. The value for the content property can be any HEX escaped character encoding. Lastly, a right margin is added to provide spacing between the character and the list item
content.
Mark Newhouse wrote an article for A List Apart a while back outlining this technique as well as many other different ways of taming lists.
li {
list-style: none;
}
li:before {
content: "\2708";
margin-right: 6px;
}

Demo
iPad
iPhone
MacBook Air

List Style Position Property


By default the list item element is to the left of the content within the list element. This list style positioning is described as outside, meaning that all of the content will appear directly
to the right of the list item element. Using the list-style-position property we can change the default value of outside to inside or inherit.
The main difference between the outside and inside values is that the outside property places the list item element to the left of the list item and doesnt allow any content to
wrap around it. Using the inside value places the list item element inline with the first line of text of the list item and allows other lines of text to wrap below it as needed.
ul {
list-style-position: inside;
}

List Style Position Demo


iPad iPad is a magical window where nothing comes between you and what you love. Now that experience is even more incredible with the new iPad.
iPhone The faster dual-core A5 chip. The 8MP camera with all-new optics also shoots 1080p HD video. And introducing Siri. Its the most amazing iPhone yet.
MacBook Air The new MacBook Air is faster and more powerful than before, yet its still incredibly thin and light. Its everything a notebook should be. And more.

Shorthand List Style Property


All of the list style properties discussed thus far can be combined into one short hand list-style property. In using the list-style property, you can pass one or all three list
learn.shayhowe.com/html-css/ordered-unordered-definition-lists

4/7

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

style values. The order of these values should be presented as list-style-type, list-style-position, and list-style-image.
ul {
list-style: circle inside;
}
ol {
list-style: outside;
}

Horizontally Displaying List


Occasionally lists may need to be displayed horizontally rather than vertically. Perhaps you want to structure a list into multiple columns, build a navigational list, or simply have a few
list items in a single row. Depending on the content and desired outcome, there are a few different ways to display lists as a single line, including inline display list items and floating list
items.

Inline Display List


The quickest way to display a list within a single line is to set the list item to have a display property of inline. Doing so turns the list item into an inline level element rather than a
default block level. Changing this display level allows the list items to stack up next to each other horizontally.
When changing the display value to inline, the list item element, bullet or number, is removed. Additionally, the list items will sit right next to each other with a single space
between them. Ideally margins or padding should be added to better space these elements apart.
li {
display: inline;
margin: 0 10px;
}

Inline Display List Demo


iPad
iPhone
MacBook Air

Floating List
Changing the display property to inline is quick, however it doesnt provide much control over how to stylize the list items and removes the list item element. In the case where a
list item element is needed, a specific width should be set. Or if greater control is desired, floating the list items will work better than changing the display property.
Setting the list item float property to left will stack all of the list items directly next to each other without any space in-between them. Additionally the list item element is still
displayed by default. To clean up the list, and to prevent the list item element from being displayed on top of other list items, margins or padding need to be set.
Floating list items leave them as block level elements, allowing greater control over styling, however it also breaks the flow of the page. Always remember to clear the floats after the
list to return the page back to its intended flow.
li {
float: left;
margin: 0 20px;
}

Floating List Demo


iPad
iPhone
MacBook Air

Navigational List Example


HTML

<ul>
<li><a
<li><a
<li><a
<li><a
</ul>

href="#"
href="#"
href="#"
href="#"

title="Profile">Profile</a></li>
title="Settings">Settings</a></li>
title="Notifications">Notifications</a></li>
title="Logout">Logout</a></li>

CSS

ul {
list-style: none;
margin: 0;
}
li {
float: left;
}
a {
background: #404853;
background: linear-gradient(#687587, #404853);
border-left: 1px solid rgba(0, 0, 0, 0.2);

learn.shayhowe.com/html-css/ordered-unordered-definition-lists

5/7

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS
border-left: 1px solid rgba(0, 0, 0, 0.2);
border-right: 1px solid rgba(255, 255, 255, 0.1);
color: #fff;
display: block;
font-size: 11px;
font-weight: bold;
padding: 0 20px;
line-height: 38px;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.6);
text-transform: uppercase;

}
a:hover {
background: #454d59;
box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.4);
border-right: 1px solid rgba(0, 0, 0, 0.2);
color: #d0d2d5;
}
li:first-child a {
border-left: none;
border-radius: 4px 0 0 4px;
}
li:last-child a {
border-right: none;
border-radius: 0 4px 4px 0;
}

Demo
Profile
Settings
Notifications
Logout

Resources & Links


HTML List via Dev.Opera
Styling HTML Lists with CSS via Smashing Magazine
List Style Type via Mozilla Developer Network
CSS Design: Taming Lists via A List Apart

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your friends.

Lesson 5 Backgrounds & Gradients

Lesson 7 Images, Audio, & Video

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any designer looking to round out their skills.

learn.shayhowe.com/html-css/ordered-unordered-definition-lists

6/7

1/15/13

Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shayhowe.com/html-css/ordered-unordered-definition-lists

7/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS


Info

PR: error

I: error

L: wait...

LD: 36

I: wait...

Rank: 238450

Age: n/a

I: 2

Tw: 74

l: 33

+1: 0

whois

source

Rank: 177977

Density

Diagnosis

Links: 13(1) |

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 7

Images, Audio, & Video


In this Lesson 7
HTML

Adding Images
Adding Audio
Adding Video
Figure & Caption
CSS

Sizing Images
Positioning Images
Users browse the internet in search of interesting and informational content, commonly found in the form of plain text. To accompany this plain text, HTML provides a way to give
users rich media in the form of images, audio tracks, and videos.
The ability to include images, audio tracks, and videos within websites has been around for some time. Browser support for images has generally been pretty good, while audio and
video support has left something to be desired. With the help of new technology, and the push of social media, more and more audio tracks and video clips have made their way
online.
Today, we can freely use images, audio, and video knowing that support is widely accepted across all major browsers with the addition of HTML5 and the help of Flash alternatives.

Adding Images
To begin adding images to a page the img inline element is used. The img element is self containing, in that it doesnt wrap any other content and exists as a single tag. For the img
element to work, a src attribute value must be included to specify the source of the requested image. The src attribute value comes in way of a URL, most often relative to the
server upon which the website is hosted.
In conjunction with the src attribute the alt attribute, known as alternative text, should be applied. The alt attribute value is displayed in place of the image should the image not be
available. Also, the alt text is the cursor tooltip text that may be shown when hovering over the image.
<img src="cows.jpg" alt="Brown and white cows in a field">

Adding an Image Demo

learn.shayhowe.com/html-css/images-audio-video

1/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS

Supported Image Formats


Images come in a variety of different file formats, and each browser may choose to support a given file format or not. By and large, the most commonly supported file formats online
include bmp, gif, jpg, and png. Of these, the most widely used formats today include jpg and png. jpg formatted images offer a quality looking image with high color counts while
still being able to scale the file size for faster load times. png formatted images are great for images with transparencies or low color counts.

Sizing Images
There are a couple of different ways to size images so that they work well on a page. One option is to use the height and width attributes directly within the img tag in HTML.
While this works, it also puts styles in the HTML. Since styles should specifically be reserved for CSS, lets use the CSS height and width properties instead.
Specifying either a height or width will automatically adjust the other dimension to maintain the aspect ratio of the image. As an example, if I wanted an image to be 200 pixels tall,
but didn't mind how wide it was, I could set the height to 200px and the width of the image would automatically adjust accordingly. Setting both a height and width will work as
well, however doing so may also break the aspect ratio of an image causing it to appear contorted.
Before getting too excited about resizing images with HTML or CSS it is worth noting that images should be resized to their desired height and width outside of the browser if
possible. Taking a 1,000 pixel wide image and dropping it down to 100 pixels wide in the browser still means the original image, all 1,000 pixels, will need to be loaded and then
scaled down. This is a less than ideal solution and can cause a large load time, especially on mobile devices.
img {
height: 200px;
width: 200px;
}

Sizing an Image Demo

Positioning Images
Images can be positioned in quite a few different ways, including inline, block, flush left, flush right, and so on. All of these positions are obtained using the CSS float property, along
with other box model properties including margin, padding, border, and display.

Inline Positioning Images


The img element by default is an inline level element. Adding an image to a page without any styles will position that image directly in place while all the other content will fall inline with
it as necessary, as seen below.
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim

Inline Positioning an Image Demo


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation

learn.shayhowe.com/html-css/images-audio-video

2/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS

ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute


irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Leaving images in their default positioning isnt very common. Most often images are set to be displayed as block level elements or floated flush to one side. Using a small image inline
with text should only be done when the image holds actual value to the page and has an appropriate alternative text. If an image, or icon, is used as part of the user interface or for
decoration, it should be added to the page as a CSS background image.

Block Positioning Images


Adding the CSS property display and setting its value to block forces the image to be a block level element. Doing so makes the image appear on its own line, leaving the
surrounding content to be positioned above and below the image.
img {
display: block;
}

Block Positioning an Image Demo


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation

ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute


irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Positioning Images Flush Left or Right


Sometimes displaying an image as inline or block isnt the ideal usage. You may want the image to appear flush to the left or right while letting all of the other content surround the
image as necessary. To do this the CSS float property is used with the value of either left or right.
Floating an image is a start, but all of the other content will align directly up against it. To provide an adequate amount of spacing around an image the margin property is used.
Additionally, we can use the padding, border, and background properties to build a frame for the image if desired.
img {
background: #e8eae9;
border: 1px solid #c6c9cc;
float: right;
margin: 8px 0 0 20px;
padding: 4px;
}

Floating & Framing an Image Demo


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation

learn.shayhowe.com/html-css/images-audio-video

3/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS

ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute


irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Mauris ut lectus quis mauris ornare iaculis a vel ligula. Quisque sed est sed arcu tincidunt aliquet. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Nam posuere accumsan mauris, nec lacinia risus pretium et. Suspendisse eget nisi facilisis nisl tristique consequat. Vivamus scelerisque accumsan vulputate. Sed bibendum felis id dui
ornare tincidunt. Sed a pretium nisl.

Adding Audio
HTML5 provides a quick and easy way to add audio and video files to be played on a website. Using the audio element an audio clip can be added to a page. Just as with the img
element, an audio element also needs a source URL specified via the src attribute.
<audio src="images-audio-video/jazz.ogg"></audio>

To accompany the src attribute on the audio element there are a handful of other attributes that may be used, the most popular of which include autoplay, controls, loop, and
preload.
By default the audio element doesnt show up on the page. If the Boolean attribute autoplay were passed in, nothing would be shown on the page, however the audio clip would
automatically start playing upon loading the page. As a Boolean, the autoplay attribute serves as a toggle function. It will toggle the audio on or off when the page loads.
To actually show the audio element on the page, use the Boolean attribute controls. The controls attribute will show the default browser controls including play and pause,
seeking, and volume.
<audio src="images-audio-video/jazz.ogg" controls></audio>

Adding Audio Demo


0:26

The loop attribute is also a Boolean attribute available to the audio element. Adding the loop attribute will repeat the audio clip endlessly, from beginning to end.
Lastly, the preload attribute has three different values, including none, auto, and metadata. The none value will not preload any information or data regarding the audio clip, while
the auto value will preload all information and data. The metadata value will preload media information about the clip, such as the length. The preload attribute is useful in the case
that users might not actually need or want to listen to an audio clip. It helps save on bandwidth and allows the page to load faster for non-essential audio clips.

Audio Fallbacks
Different browsers may support different audio formats and some may not support audio at all. In this case we can list multiple audio fallbacks including different audio file formats, a
Flash alternative, or the option to directly download the audio clip.
To start, using the HTML5 audio element we can specify different file formats using multiple sources via the source element. The source element works in conjunction with the
and type attributes. The src attribute specifies the source URL while the type attribute specifies the MIME-type of the audio clip, helping browsers better understand the audio
clip format.

src

Some browsers will not support the HTML5 audio element at all, in which case a Flash player fallback may be used. There are many different Flash players out there so you will
need to research which one will work best for you. Two popular available options include SWFObject and Flowplayer.
<audio controls>
<source src="jazz.ogg" type="audio/ogg">
<source src="jazz.mp3" type="audio/mpeg">
<object type="application/x-shockwave-flash" data="player.swf?audio=jazz.mp3">
<param name="movie" value="player.swf?audio=jazz.mp3">
<p>This browser does not support the audio format. Please <a href="jazz.mp3" title="Jazz song">download</a> the audio clip.</p>
</object>
</audio>

To cover every browser, including the ones that do not support ogg or mp3 audio formats and do not have a Flash plug-in installed, a link to simply download the audio clip is
included. This link is placed within the Flash player code as a last case scenario should Flash not be available.

Adding Video
Adding in HTML5 videos is very similar to that of adding in audio. In this case however, we use the video element in place of the audio element. All of the same attributes (source,
and preload) and fallbacks apply here too.

autoplay, controls, loop,

learn.shayhowe.com/html-css/images-audio-video

4/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS

With audio, if the controls Boolean attribute wasnt specified the audio clip wouldnt be shown. With videos, not specifying the controls attribute shows the video, however
doesnt provide any way to play it unless the autoplay Boolean attribute is also applied. Best practice here would be to include the controls attribute unless there is good a reason
not to allow users to start, stop, or replay the video.
Since videos will be displayed on the page it doesnt hurt to specify dimensions, most commonly with a fixed height or width in CSS. This helps ensure that the video isnt too large
and stays within the implied layout of a page. Additionally, specifying a size helps browsers render the videos faster and allows them to allocate the proper space needed for the video
to be shown.
<video src="earth.ogv" controls></video>

Adding Video Demo

0:00

Customizing Audio & Video Controls


By default audio and video controls are determined by each browser independently. Depending on the website more control over the look and feel of the media player may be
needed. In this case a customized player can be built, but requires a little bit of JavaScript to get the player working.

Poster Attribute
One additional attribute available on the video element is the poster attribute. The poster attribute allows you to specify an image, in the form of a URL, to be shown before video
is played. A poster image could be a still frame from the video or any other desired image. While not practical, the example below uses the picture of cows as the poster for the
Earth video.
<video src="earth.ogv" controls poster="cows.jpg"></video>

Poster Demo

0:00

Video Fallbacks
As with the audio element, video fallbacks are also necessary and come in the same markup format with multiple source elements. One option that could be used in place of
building your own Flash player is YouTube or Vimeo. These video hosting websites make it dead simple to upload your own videos, then embed them onto a page.
<video controls>
<source src="earth.ogv" type="video/ogg">
<source src="earth.mp4" type="video/mp4">
<object type="application/x-shockwave-flash" data="player.swf?video=earth.mp4">
<param name="movie" value="player.swf?video=earth.mp4">
<p>This browser does not support the video format. Please <a href="earth.mp4" title="Earth video">download</a> the video.</p>
</object>
</video>

HTML5 Audio & Video File Formats


Browser support for the audio and video elements vary as does the file formats required with these elements. Each browser has their own interpretation of which audio and video
file formats should be used.
To convert files into different formats there are a few tools to help out, both online and desktop based. To convert audio files the web application media.io does wonders. For video
files the desktop application Miro Video Converter looks to do the trick.

Figure & Caption


With HTML5 also came the introduction of the figure and figcaption elements. These elements were created to semantically markup self-contained content or media, commonly
learn.shayhowe.com/html-css/images-audio-video

5/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS

with a caption. Before HTML5 this was frequently accomplished using ordered list. While ordered list worked, it was not semantically correct markup.

Figure
The figure block level element is used to wrap around different forms of media. It can surround images, audio clips, videos, blocks of code, diagrams, illustrations, or forms of
media. More than one form of media may be contained within a figure at a time, such as multiple images or videos. Overall, the figure element should not disrupt the content or
legibility of a page should it be moved to the bottom of a page or to an appendix.
<figure>
<img src="images-audio-video/cows.jpg" alt="Brown and white cows in a field">
</figure>

Figure Demo

Figure Caption
To add a caption, or legend, to a figure element the figcaption element is used. The figcaption may appear at the top, bottom, or anywhere within the figure element,
however it may only appear once.
Figure & Caption<figure>
<img src="images-audio-video/cows.jpg" alt="Brown and white cows in a field">
<figcaption>A couple of brown and white cows hanging out in a grass field.</figcaption>
</figure>

Figure & Caption Demo

A couple of brown and white cows hanging out in a grass field.

Resources & Links


Images in HTML via Dev.Opera
HTML5 audio & video via Mozilla Developer Network
audio HTML5 Element via Mozilla Developer Network
Introduction to HTML5 Video via Dev.Opera
The figure & figcaption Elements via HTML5 Doctor

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your friends.
learn.shayhowe.com/html-css/images-audio-video

6/7

1/15/13

Images, Audio, & Video - A Beginner's Guide to HTML & CSS

Lesson 6 Unordered, Ordered, & Definition Lists

Lesson 8 Building Forms

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shayhowe.com/html-css/images-audio-video

7/7

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS


Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 2

Tw: 74

l: 33

+1: 1

whois

source

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 8

Building Forms
In this Lesson 8
HTML

Initializing a Form
Text Fields & Textareas
Multiple Choice Inputs & Menus
Form Buttons
Organizing Form Elements
Form & Input Attributes
Forms are an essential part of the internet as they provide a way for websites to capture information about users, process requests,
and give controls for nearly every use of an application imagined. By providing controls, or fields, forms can request a small
amount of information, often a search query or username and password, or a large amount of information, perhaps shipping and
billing information or a job application.
Knowing how to build forms is necessary to acquire user input. In this lesson well discuss how to use HTML to markup a form,
which elements are available to capture different types of data, and how to style forms with CSS. We wont get too deep into how
information from a form is processed and handled on the backend of a website. Form processing is a deeper topic, outside the
realm of this lesson.

Initializing a Form
learn.shayhow e.com/html-css/building-forms

Rank:

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

To begin a form on a page the form element must be used. The form element signifies where on the page control elements will
appear. Additionally, the form element will wrap all of the elements included within the form, much like that of a div element.
<form action="#" method="foo">
...
</form>

A handful of different attributes can be applied to the form element, two of which, action and method, are most often seen. The
action attribute is the URI where information included within the form will be sent to be processed by the server. The method
attribute is the HTTP method browsers use to submit the form data. Both of these form attributes revolve around submitting and
processing data.

Text Fields & Textareas


When it comes to text controls within forms there are a few different elements available to obtain data. Text fields and textareas are
specifically used to gather text or string based data. This may include data containing passages of text content, passwords,
telephone numbers, and so forth.

Text Fields
One of the primary elements used to obtain text from users is the input element. The input element uses the type attribute to
determine what type of information is to be captured within the specific control. The most popular type attribute value is text,
which denotes a single line text input.
Along with setting a type attribute it is also best practice to give an input a name attribute as well. The name attribute is used as
the name of the control and is submitted along with the inputs data to the server.
<input type="text" name="sample_text_field">

Text Input Demo

Please note the input element is self enclosed, meaning there is only one tag and it does not wrap any other content.
Originally, the only two text based type attribute values were text and password, for password inputs, however HTML5 has
brought along a handful of new type attribute values and form updates. These values were added to provide better semantical
context around an input as well as help provide better controls for users. Should a browser not understand one of these HTML5
type attribute values, it will automatically fall back to the text attribute value. Below is a list of the new HTML5 input types.
color
date

datetime

datetime-local
email
month

number
range

search
tel

time
url

week
learn.shayhow e.com/html-css/building-forms

2/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

Fig. 6.01 The date input type within iOS.

Fig. 6.02 The time input type within iOS.

learn.shayhow e.com/html-css/building-forms

3/14

1/15/13

Fig. 6.03 The email input type within iOS.

Fig. 6.04 The url input type within iOS.

learn.shayhow e.com/html-css/building-forms

4/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

Fig. 6.05 The number input type within iOS.

Fig. 6.06 The tel input type within iOS.

Textarea
Another element used to capture text based data is the textarea element. The textarea element differs from the text input in
that it is for larger passages of text spanning multiple columns. The textarea also has start and end tags which can wrap plain
text. Since the textarea element only accepts one type of value the type attribute doesnt apply here, however the name
attribute is still in effect.
<textarea name="sample_textarea">Sample textarea</textarea>

Textarea Demo
Sample textarea

The textarea element does have two sizing attributes, cols for width and rows for height. These, however, are pretty old school
attributes, and in their place the width and height properties within CSS should be used.
learn.shayhow e.com/html-css/building-forms

5/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

Multiple Choice Inputs & Menus


Apart from text based input controls HTML also allows users to select data using multiple choice and drop down lists. These form
controls come in a few different options and elements, each of which have their own benefits.

Radio Buttons
Radio buttons are a quick and easy way to show a small list of options and allow users to make a quick decision. Radio buttons
only allow users to select one option, as opposed to selecting multiple options.
To build a radio button the input element is used with a type attribute value of radio. Each radio button option should have the
same name attribute value so that all of the buttons correspond to one another. With text inputs the value of the input was
determined by what a user typed in, with radio buttons a user is simply making a selection so we have to define the input value.
Using the value attribute we can set specific values for each input.
Additionally, to preselect a radio button for users the Boolean attribute checked may be used.
<input type="radio" name="day" value="Friday" checked> Friday
<input type="radio" name="day" value="Saturday"> Saturday
<input type="radio" name="day" value="Sunday"> Sunday

Radio Buttons Demo


Friday

Saturday

Sunday

Checkboxes
Checkboxes are very similar to that of radio buttons. They use the same attributes and patterns, with the exception of checkbox
as the type attribute value. The difference between the two is that a checkbox allows you to select multiple values and tie them all
to one control name, while radio buttons limit you to one value.
<input type="checkbox" name="day" value="Friday" checked> Friday
<input type="checkbox" name="day" value="Saturday"> Saturday
<input type="checkbox" name="day" value="Sunday"> Sunday

Checkboxes Demo
Friday

Saturday

Sunday

Drop Down Lists


Drop down lists are a perfect way to provide users with a long list of options in a usable manner. Outputting every state within the
country on a page with radio buttons would create a rather cluttered and daunting list. Drop down menus provide the perfect
venue for a long list of options.
To create a drop down menu the select and option elements are used. The select element will wrap all of the different menu
options marked up using the option element. Then you can apply the name attribute to the select element.
Each individual option within the menu needs to be coded using the option element. The option element will wrap the text to be
included within the menu. Additionally, the option element will include the value attribute, specific to each individual option.
As with the checked Boolean attribute with radio buttons and checkboxes, drop down menus can use the selected Boolean
attribute to preselect an option for users.
<select name="day">

<option
value="Friday" selected>Friday</option>
learn.shayhow
e.com/html-css/building-forms

6/14

1/15/13

<option value="Friday" selected>Friday</option>


<option value="Saturday">Saturday</option>
<option value="Sunday">Saturday</option>
</select>

Drop Down Lists Demo


Friday

Multiple Selections
Using the standard drop down list and adding the Boolean attribute multiple to the select element allows a user to choose
more than one option from the menu. Additionally, using the selected Boolean attribute on more than one option element within
the menu will preselect multiple options.
The height and width of the select element can be controlled using CSS and should be adjusted appropriately to allow for
multiple selections. It may also be worth mentioning to users that to choose multiple options they will need to hold down the shift
key while clicking to make their selections.
<select name="day" multiple>
<option value="Friday" selected>Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Saturday</option>
</select>

Multiple Selections Demo


Friday
Saturday
Saturday

Form Buttons
After a user inputs the requested information, buttons allow them to put that information into action. Most commonly, a submit
button is used to process the data. A reset button is often used to clear data.

Submit Button
Users click the submit button to process data after filling out a form. The submit button uses the input element with a type
attribute of either submit or image. The submit attribute value the most common as it is simple to use and provides the most
control. The image attribute value is used specifically to set an image as a submit button, however with the use of CSS the need to
use an image has greatly diminished.
To determine the verbiage to be used within the button, the value attribute is used. Using CSS properties such as background,
border-radius, box-shadow, and others, the button can then be styled to any specific desire.
<input type="submit" name="submit" value="Submit Form">

Submit Button Demo


Submit Form

Reset Button
learn.shayhow e.com/html-css/building-forms

7/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

To take the complete opposite action from submitting a form, users may also reset a form using the reset button. The reset button
code works just like that of the submit button, however it uses the reset value for the type attribute.
Reset buttons are becoming less and less popular because they offer a very strong action, often undesired by both websites and
users. Users may spend quite a bit of time filling out a form only to click the reset button accidentally thinking it was the submit
button. Chances of a user filling out the form again thereafter are small. Before using a reset button think of any potential
consequences.
<input type="reset" name="reset" value="Reset Form">

Reset Button Demo


Reset Form

Other Inputs
Outside all other previously stated choices the input element does have a few other use cases. Two of which include passing
hidden data and attaching filings during form processing.

Hidden Input
Hidden inputs provide a way to pass data to the server without displaying it to users. Hidden inputs are typically used for tracking
codes, keys, or other information not pertinent to the users but helpful to the website overall. This information is not displayed on
the page, however it could be seen by viewing the source code of a page. That said, it should not be used for sensitive or secure
information.
To create a hidden input you use the hidden value for the type attribute. Additionally, you pass along the appropriate name and
value.
<input type="hidden" name="tracking_code" value="abc_123">

File Input
To allow users to add a file to a form, much like that of attaching a file to an email, the file value for the type attribute is used.
The file input is most commonly seen to upload pictures or files to social networks or applications.
Unfortunately, stylizing the file input is a tough task with CSS. Each browser has its own default rendering of how the input should
look and doesnt provide much control to override the default styling. JavaScript and other solutions can be built to allow for file
input, but they are slightly more difficult to construct.
<input type="file" name="file">

File Input Demo


Choose File No file chosen

Organizing Form Elements


Knowing how to capture data with inputs is half the battle. Organizing form elements and controls into a usable manner is the other
half. Forms are not worth much unless users understand what is asked of them and how to provide the requested information.
Using labels, fieldsets, and legends we can better organize forms and guide users to completing the end task.

Label
learn.shayhow e.com/html-css/building-forms

8/14

Building Forms - A Beginner's Guide to HTML & CSS

Labels provide captions, or headings, for form elements. Created using the label element, labels should include descriptive text,
of which describes the input or control it pertains to. Labels should include a for attribute. The value of the for attribute should be
the same as the value of the id attribute included within the form element the label corresponds to. Matching up the for and id
values ties the two elements together, allowing users to click on the label to get focused within the proper form element.
<label for="username">Username</label>
<input type="text" name="username" id="username">

Label Demo
Username
When using labels with radio buttons or checkboxes the input element can be wrapped within the label element. Doing so
allows omission of the for and id attributes.
<label><input type="radio" name="day" value="Friday" checked> Friday</label>
<label><input type="radio" name="day" value="Saturday"> Saturday</label>
<label><input type="radio" name="day" value="Sunday"> Sunday</label>

Label Radio Button & Checkbox Demo


Friday

Saturday

Sunday

Fieldset
Fieldsets group form controls and labels into organized sections. Much like a div or other structural element, the fieldset is a
block level element that wraps related elements, however specifically within a form for better organization. Fieldsets by default
also include a border outline that can be modified using CSS.
<fieldset>
<label for="username">Username</label>
<input type="text" name="username" id="username">
<label for="password">Password</label>
<input type="text" name="password" id="password">
</fieldset>

Fieldset Demo
Username

Password

Legend
A legend provides a caption, or heading, for a fieldset. The legend element wraps text describing the controls that fall within
the fieldset. The HTML code should include the legend directly after the opening fieldset tag. The legend itself will
appear on the page within the top left part of the fieldset border. The appearance of the legend on a page may be changed
with CSS.
<fieldset>
<legend>Login</legend>
<label for="username">Username</label>
<input type="text" name="username" id="username">
<label for="password">Password</label>
<input type="text" name="password" id="password">
</fieldset>
learn.shayhow e.com/html-css/building-forms

9/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

Legend Demo
Login
Username

Password

Form & Input Attributes


To accommodate all of the different form, input, and control elements there are a number of attributes and corresponding values.
These attributes and values serve a lot of different functions including the ability to disable controls, add form validation, and so
forth. Below are some of the more popular and useful attributes.

Disabled
The disabled Boolean attribute turns off an element or control so that it is not available for interaction or input. Elements that are
disabled will not send any values to the server for form processing.
Applying the disabled Boolean attribute to a fieldset will disable all of the controls within the fieldset. If the type attribute
has a hidden value, the disabled Boolean attribute is disregarded.
<label for="username">Username</label>
<input type="text" name="username" id="username" disabled>

Disabled Demo
Username

Placeholder
The placeholder HTML5 attribute provides a tip within the control of an input and disappears once the control is clicked in,
or gains focus. The placeholder attribute only applies to inputs with a type attribute value of text, email, search, tel, or
url.
The main difference between the placeholder and value attributes is that the value text stays in place during focus unless
manually deleted by a user. This is great for pre-populating data, such as personal information for a user, but not for providing
suggestions. The difference between the two attributes can be seen below.
<label for="username">Username placeholder</label>
<input type="text" name="username" id="username" placeholder="Holder">

Placeholder Demo
Username placeholder Holder

Username value Value

Required
The required HTML5 attribute enforces that an element or control contain a value upon being submitted to the server. Should an
element or control not have a value an error message will be displayed requesting a user complete the required field. Currently
error message styles are controlled by the browser and are unable to be styled with CSS. Elements, on the other hand, can be
styled using the :optional and :required CSS pseudo-classes.
Validation also occurs specific to a controls type. For example, an input with a type attribute value of email will require that
not only a value exist within the input, but that it also includes a valid email format.
learn.shayhow e.com/html-css/building-forms

10/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

<label for="name">Name</label>
<input type="text" name="name" id="name" required>

Required Demo
Name

Email

Send

Additional Attributes
Other form and input attributes include, but are not limited to the following. Please feel free to research and look into these
attributes as necessary.
accept

autocomplete
autofocus

formaction

formenctype
formmethod

formnovalidate
formtarget
max

maxlength
min

pattern

readonly

selectionDirection
step

Login Form Example


HTML

<form>
<label for="login_username">Username</label>
<input type="text" name="login_username" id="login_username">
<label for="login_password">Password</label>
<input type="password" name="login_password" id="login_password">
<fieldset>
<input type="submit" name="login_submit" id="login_submit" value="Login">
<label><input type="checkbox" name="login_remember" id="login_remember"> Stay signed in</label>
</fieldset>
</form>
CSS

form {
background: linear-gradient(top, #fff, #f8f8f8);
border: 1px solid #d0d2d5;
border-bottom: 1px solid #bebfc2;
border-radius: 4px;
margin: 0 0 20px 0;
padding: 20px;
width: 212px;
}
label {
color: #404853;
display: block;
learn.shayhow e.com/html-css/building-forms

11/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

font-weight: bold;
}
input {
background: #fff;
border: 1px solid #c6c9cc;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1), 0 1px 0 #fff;
color: #555;
font: 13px/20px 'Droid Sans', Arial, 'Helvetica Neue', 'Lucida Grande', sans-serif;
margin: 0 0 20px 0;
padding: 5px;
width: 200px;
}
fieldset {
background: linear-gradient(top, #ebeced, #dedfe0);
border: none;
border-top: 1px solid #d0d2d5;
border-radius: 0 0 4px 4px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.75);
margin: 5px 0 -20px -20px;
padding: 18px 20px;
width: 212px
}
fieldset input {
margin: 0;
width: auto;
}
#login_submit {
background: linear-gradient(top, #687587, #404853);
border: none;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.3), 0 1px 0 rgba(255, 255, 255, 0.75);
color: #fff;
font-weight: bold;
float: left;
padding: 5px 10px;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.6);
}
#login_submit:hover {
background: linear-gradient(top, #5a6675, #333942);
}
#login_submit:active {
background: #333942;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.75), 0 1px 0 rgba(255, 255, 255, 0.75);
}
fieldset label {
color: #888;
cursor: pointer;
float: left;
font-size: 12px;
font-weight: normal;
margin: 5px 0 0 20px;
}
fieldset label input {
margin: -2px 2px 0 0;
padding: 0;
}

Demo
Username
Login

Password
Stay signed in

learn.shayhow e.com/html-css/building-forms

12/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

Resources & Links


Forms via HTML Dog
Form Element via Mozilla Developer Network
Input Element via Mozilla Developer Network
A Form of Madness via Dive Into HTML5
Form Examples via Twitter Bootstrap

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your
friends.

Lesson 7 Images, Audio, & Video

Lesson 9 Organizing Data with Tables

An Advanced Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any
designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e
learn.shayhow e.com/html-css/building-forms

13/14

1/15/13

Building Forms - A Beginner's Guide to HTML & CSS

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shayhow e.com/html-css/building-forms

14/14

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS
Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: n/a

Tw: 74

l: 33

+1: 0

whois

source

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 9

Organizing Data with Tables


In this Lesson 9
HTML

Creating a Table
Table Structure
CSS

Table Borders
Aligning Text
Table Striping
When HTML was coming to life tables were used all over the place, and were the primary means by which websites were
built. They were used for positioning content as well as building the overall layout of a page. Fortunately we have come a long
way since then. Today tables are, and should be, used specifically for organizing data.
When dealing with large amounts of tabular data tables are the go to foundation for displaying this information. Using tables
provides a quick and easy way to both read and digest information, giving users an overall understanding of the data.
Reserving tables for data, not page design, still has challenges. How a table should be built in HTML is largely dependent on
learn.shayhow e.com/html-css/organizing-data-tables

1/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

the data and how it is to be displayed. Upon being marked up in HTML, tables need to be stylized with CSS to make the
information more comprehensive and understandable to users.

Creating a Table
In general tables are made up of data within rows and columns. Depending on the table these rows and columns will correlate
to one another accordingly. In HTML, there are a few different elements needed to make a table. At a minimum a table must
consist of table, tr, and td elements. To take tables one step further they may include the th element as well. Getting all of
these elements to work together builds a solid table.

Table
To initialize a table on a page the table element is used. Using the table element signifies that the data within these tags will
displayed in two or more dimensions. The table element is only an initializer and it must encompass a table row, along with
table data.
<table>
...
</table>

Table Row
Once the table has been defined in HTML, table rows may be added using the tr element. A table can have numerous table
rows, or tr elements. Depending on the amount of information the number of table rows can be substantially high. To add
data into these table rows the table data, td, and table header, th, elements are used.
<table>
<tr>
...
</tr>
<tr>
...
</tr>
</table>

Table Data
The best way to add data to a table is via the table data, or td element. The table data element creates a cell, of which may
include data. Listing multiple table data elements one after the other will create columns within a table row. When the contents
of a cell is a heading for either a row or column it should be wrapped within the table header element, th, not the table data
element, td.
<table>
<tr>
<td>Date</td>
<td>Opponent</td>
<td>Location</td>
<td>Time</td>
</tr>
<tr>
<td>Monday, March 5th</td>
<td>Indiana Pacers</td>
<td>United Center, Chicago, IL</td>
<td>7:00 PM</td>
</tr>
<tr>
<td>Wednesday,
March 7th</td>
learn.shayhow
e.com/html-css/organizing-data-tables

2/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

<td>Wednesday, March 7th</td>


<td>Milwaukee Bucks</td>
<td>Bradley Center, Milwaukee, WI</td>
<td>7:00 PM</td>
</tr>
<tr>
<td>Thursday, March 8th</td>
<td>Orlando Magic</td>
<td>United Center, Chicago, IL</td>
<td>7:00 PM</td>
</tr>
<tr>
<td>Saturday, March 10th</td>
<td>Utah Jazz</td>
<td>United Center, Chicago, IL</td>
<td>7:00 PM</td>
</tr>
</table>

Table Data Demo


Date

Opponent

Location

Time

Monday, March 5th

Indiana Pacers

United Center, Chicago, IL

7:00 PM

Wednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PM


Thursday, March 8th

Orlando Magic

Saturday, March 10th Utah Jazz

United Center, Chicago, IL

7:00 PM

United Center, Chicago, IL

7:00 PM

Table Header
To designate a heading for a column or row of cells the table header element, th, should be used. The table heading element
works just like that of the table data element in that it creates a cell for data. The value to using the table header element over
the table data element is that the table header provides a semantic value to table, signifying the data within the cell as a
heading. The two elements are comparable to that of a heading, h1, and paragraph, p. While a headings content could be
placed within a paragraph tag it doesnt make sense to do so. Using a heading tag specifically adds more value to the content
and provides an easier way to stylize all headings. The exact same is true for headers within tables.
Table headers are available to use within both rows and columns. The table data will determine where the headers are
placed. To help the headers in noting exactly what content they pertain to the scope attribute is available. The scope
attribute signifies whether a header applies to a row or column with the values row, col, rowgroup, and colgroup. The
most commonly used values are row and col. The row value notes that every cell within the row relates directly to that
header, and the col value notes that every cell within the column relates directly to that header.
The Headers Attribute
Very similar to the scope attribute is the headers attribute. By default the scope attribute may only be used on the th
element. In the case that a cell, either a td or th, needs to be associated with a different header the headers attribute comes
into play. The value of the headers attribute on a td or th needs to match the id of the th that cell pertains to.
Additionally, depending on the browser, table headers may also appear bold and centered. Should these default styles not be
the preferred styling they may be over written in CSS.
<table>
<tr>
<th scope="col">Date</th>

<th
scope="col">Opponent</th>
learn.shayhow
e.com/html-css/organizing-data-tables

3/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

<th scope="col">Opponent</th>
<th scope="col">Location</th>
<th scope="col">Time</th>
</tr>
<tr>
<td>Monday, March 5th</td>
<td>Indiana Pacers</td>
<td>United Center, Chicago, IL</td>
<td>7:00 PM</td>
</tr>
<tr>
<td>Wednesday, March 7th</td>
<td>Milwaukee Bucks</td>
<td>Bradley Center, Milwaukee, WI</td>
<td>7:00 PM</td>
</tr>
<tr>
<td>Thursday, March 8th</td>
<td>Orlando Magic</td>
<td>United Center, Chicago, IL</td>
<td>7:00 PM</td>
</tr>
<tr>
<td>Saturday, March 10th</td>
<td>Utah Jazz</td>
<td>United Center, Chicago, IL</td>
<td>7:00 PM</td>
</tr>
</table>

Table Header Demo


Date
Monday, March 5th

Opponent
Indiana Pacers

Location
United Center, Chicago, IL

Time
7:00 PM

Wednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PM


Thursday, March 8th

Orlando Magic

Saturday, March 10th Utah Jazz

United Center, Chicago, IL

7:00 PM

United Center, Chicago, IL

7:00 PM

Combining Multiple Cells


There often comes a time when two or more cells will need to be combined into one without breaking the overarching row
and column layout. Perhaps two cells next to each other contain the same data, or the cells need to be combined for
stylization purposes. In this case we can use the colspan and rowspan attributes. These two attributes work on either the
table data or table header elements.
The colspan attribute is used to span a cell across multiple columns within a table, where the rowspan attribute is used to
span a cell across multiple rows. Each attribute accepts an integer value indicating the number of cells to span across, with 1
being the default value.
<table>
<tr>
<th
<th
<th
<th
</tr>
<tr>

scope="col">Date</th>
scope="col">Opponent</th>
scope="col">Location</th>
scope="col">Time</th>

learn.shayhow e.com/html-css/organizing-data-tables

4/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

<td>Monday, March 5th</td>


<td>Indiana Pacers</td>
<td>United Center, Chicago, IL</td>
<td rowspan="4">7:00 PM</td>
</tr>
<tr>
<td>Wednesday, March 7th</td>
<td colspan="2">Milwaukee Bucks, Bradley Center, Milwaukee, WI</td>
</tr>
<tr>
<td>Thursday, March 8th</td>
<td>Orlando Magic</td>
<td rowspan="2">United Center, Chicago, IL</td>
</tr>
<tr>
<td>Saturday, March 10th</td>
<td>Utah Jazz</td>
</tr>
</table>

Combining Multiple Cells Demo


Date

Opponent

Monday, March 5th

Indiana Pacers

Location

Time

United Center, Chicago, IL

Wednesday, March 7th Milwaukee Bucks, Bradley Center, Milwaukee, WI 7:00 PM


Thursday, March 8th

Orlando Magic

Saturday, March 10th Utah Jazz

United Center, Chicago, IL

Table Structure
Knowing how to build a table and arrange data is extremely powerful, and a skill set necessary for every front-end
developer. On top of building table rows and cells there are a few additional elements to help us organize data within a table.
These elements include caption, thead, tfoot, and tbody.

Table Caption
To provide a caption or title for a table the caption element is used. A caption will help users identify what the table pertains
to and what they can expect within the table. The caption element must come immediately after the opening table tag. Its
default positioning is at the top of the table by default, however may be changed using CSS. Should a table fall within the
figure element, the figcaption element should be used in place of the caption element.
<table>
<caption>Chicago Bulls Schedule - Week of March 5th</caption>
...
</table>

Table Caption Demo

Date

Chicago Bulls Schedule - Week of March 5th


Opponent
Location

Monday, March 5th

Indiana Pacers

Wednesday,
March 7th Milwaukee Bucks
learn.shayhow
e.com/html-css/organizing-data-tables

United Center, Chicago, IL

Time
7:00 PM

Bradley Center, Milwaukee, WI 7:00 PM

5/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

Wednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PM


Thursday, March 8th Orlando Magic United Center, Chicago, IL
7:00 PM
Saturday, March 10th Utah Jazz

United Center, Chicago, IL

7:00 PM

Table Head, Body, & Foot


Tables can be broken up into multiple groups, including a header, footer, and body. The elements to help better organize a
table are thead for a table header, tbody for a table body, and tfoot for a table footer.
The table header element, thead, wraps the heading row, or rows, of a table denoting the heading. The table header should
be placed at the top of a table, after any caption and before any tbody.
Following the table header may come either the table body or table footer elements. Originally the tfoot element had to
come immediately after the thead, however HTML5 has provided leeway here. They may now come in any order so long as
they are never the parent element of one another. Moving forward, the tbody element should contain the primary data within
the table, while the tfoot contains data that outlines the contents of the table.
Table Head, Body, & Foot<table>
<caption>...</caption>
<thead>
...
</thead>
<tbody>
...
</tbody>
<tfoot>
...
</tfoot>
</table>

Table Borders
One design component used to help make tables more comprehensible are borders. Borders around a table, rows, or
individual cells can make a large impact when trying to interpret data and quickly scan for information. When stylizing table
borders with CSS there are two properties that will quickly come in hand, they are the border-collapse and borderspacing properties.

Border Collapse Property


Tables consist of a parent table element as well as subsequent td elements. Applying a border to both of these elements
will begin to stack up borders all around. Take for example, putting a 2 pixel border around an entire table and then an
additional 2 pixel border around each table cell. In return this would create a 4 pixel border around every cell within the table.
The border-collapse property determines a tables border model. There are three values for the border-collapse
property, including collapse, separate, and inherit. By default the value is separate meaning that all of the different
borders will stack up to one another accordingly, like mentioned above. The collapse property, on the other hand, will
condense the borders down to one, choosing the table cell as the primary border.
table {
border: 2px solid blue;
border-collapse: separate;
}
th, td {
border: 2px solid red;
}
learn.shayhow
e.com/html-css/organizing-data-tables

6/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

Border Collapse Property Demo

Luke Brad
88

76

separate

Luke Brad
88

76

collapse

Border Spacing Property


Understanding that the border-collapse property with the separate values allows borders to be stacked up against one
another the border-spacing property can determine how much space, if any, appears between the borders. Going back to
our example, a table with a 2 pixel border and a 2 pixel border around each cell creates a 4 pixel border all around. Adding
in a border-spacing value of 2 pixels would then separate the two borders by 2 pixels, creating a 6 pixel total border
width.
table {
border: 2px solid blue;
border-collapse: separate;
border-spacing: 2px;
}
th, td {
border: 2px solid red;
}

Border Spacing Property Demo


Luke Brad
88

76

Adding in Borders
Putting a border around a table is fairly simple, however putting borders around rows or cells can be more difficult. Below
are a few examples of how to add these borders. For an additional reference and examples on how to add borders around a
table check out the tables within Bootstrap, from Twitter.
Row Borders
Putting a border between each row is as simple as adding a bottom border to each table cell. To remove the bottom border
of the cells within the last row of the table the pseudo-class last-child selector is used.
table {
border-collapse: collapse;

border-spacing:
0;
learn.shayhow
e.com/html-css/organizing-data-tables

7/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

border-spacing: 0;
}
th, td {
border-bottom: 1px solid #c6c9cc;
}
tr:last-child td {
border: 0;
}

Row Borders Demo


Track
We Are Young

Artist
Fun.

Length
4:10

Pumped Up Kicks Foster the People 3:59


Midnight City

M83

4:03

Cell Borders
On the other hand, putting a border around every individual cell is fairly easy. Simply put a border around each table header
or table data cell and set the overall table to have a border-spacing value of collapse.
table {
border-collapse: collapse;
border-spacing: 0;
}
th, td {
border: 1px solid #c6c9cc;
}

Cell Borders Demo


Track
We Are Young

Artist
Fun.

Length
4:10

Pumped Up Kicks Foster the People 3:59


Midnight City

M83

4:03

Aligning Text
In addition to table borders, aligning text within cells, both horizontally and vertically, plays an integral part of table formatting.
Commonly names, descriptions, and so forth are flush left while numbers and figures are flush right. Other information,
depending on its context, should be centered. To accomplish moving text horizontally can be accomplished using the textalign property within CSS, as covered in the typography lesson.
To align text vertically the vertical-align property is used. The vertical-align property only works with inline and
table-cell display elements. That said, the vertical-align property will not work for block level or any other level
elements.
The vertical-align property accepts a handful of different values, of which change depending on if the element is
displayed as an inline and table-cell element. Within tables the most popular values include top, middle, and bottom.
These values then vertically position text within the cell in relation to their value.

learn.shayhow e.com/html-css/organizing-data-tables

8/15

HTML

<table>
<thead>
<tr>
<th colspan="2">Items</th>
<th class="qty">Qty</th>
<th class="price">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td class="item">Envisioning Information <span>By Edward R. Tufte Hardcover</span></td>
<td class="stock in">In Stock</td>
<td class="qty">1</td>
<td class="price">$33.32</td>
</tr>
<tr>
<td class="item">Outliers <span>By Malcolm Gladwell Hardcover</span></td>
<td class="stock in">In Stock</td>
<td class="qty">2</td>
<td class="price">$33.58 <span>($16.79 2)</span></td>
</tr>
<tr>
<td class="item">Dont Make Me Think <span>By Steve Krug Paperback</span></td>
<td class="stock out">Out of Stock</td>
<td class="qty">1</td>
<td class="price">$22.80</td>
</tr>
<tr>
<td class="item">Steve Jobs <span>By Walter Isaacson Hardcover</span></td>
<td class="stock in">In Stock</td>
<td class="qty">1</td>
<td class="price">$17.49</td>
</tr>
</tbody>
<tfoot>
<tr class="sub">
<td colspan="3">Subtotal</td>
<td>$107.19</td>
</tr>
<tr class="tax">
<td colspan="3">Tax</td>
<td>$10.71</td>
</tr>
<tr class="total">
<td colspan="3">Total</td>
<td>$117.90</td>
</tr>
</tfoot>
</table>
CSS

table {
border-collapse: collapse;
border-spacing: 0;
}
th, td {
border: 1px solid #c6c9cc;
vertical-align: top;
}

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

th {
font-size: 11px;
text-transform: uppercase;
}
th.qty, th.price {
text-align: center;
}
tbody td.item {
color: #404853;
font-weight: bold;
}
tbody td.stock, tbody td.qty, tbody td.price {
vertical-align: middle;
}
tbody td.stock, tbody td.qty {
text-align: center;
}
tbody td.price {
text-align: right;
}
tfoot td {
text-align: right;
}
tfoot tr.sub td, tfoot tr.tax td {
color: #8c8c8c;
font-size: 12px;
}
tfoot tr.total td {
color: #404853;
font-size: 14px;
font-weight: bold;
}
.in {
color: #00b515;
}
.out {
color: #b50000;
}
span {
color: #8c8c8c;
display: block;
font-size: 12px;
font-weight: normal;
}

Aligning Text Demo


Items

Qty

Price

Envisioning Information By Edward R. Tufte Hardcover In Stock


1
Outliers By Malcolm Gladwell Hardcover
In Stock
2
Dont Make Me Think By Steve Krug Paperback
Out of Stock 1
Steve Jobs By Walter Isaacson Hardcover
In Stock
1

$33.32
$33.58 ($16.79 2)
$22.80
$17.49

Subtotal
Tax

$107.19
$10.71

Total

$117.90

Table Striping
10/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

In the effort to help make tables more legible, one common pattern is to "stripe" the table rows so that they alternate
background colors. This makes the rows more identifiable and provides a great visual cue for scanning information. One way
to do this is to place a class on every other row and set a background color to that class. Another way is to use the nthchild pseudo-class selector and set the select to odd or even rows.
th {
background: #404853;
background: linear-gradient(#687587, #404853);
color: #fff;
}
tbody tr:nth-child(even) td {
background: #e8eae9;
background: linear-gradient(#f7faf9, #e8eae9);
}
tfoot tr.total td {
background: #e8eae9;
background: linear-gradient(#f7faf9, #e8eae9);
}

Table Striping Demo


Items

Qty

Price

Envisioning Information By Edward R. Tufte Hardcover In Stock


1
Outliers By Malcolm Gladwell Hardcover
In Stock
2
Dont Make Me Think By Steve Krug Paperback
Out of Stock 1
Steve Jobs By Walter Isaacson Hardcover
In Stock
1

$33.32
$33.58 ($16.79 2)
$22.80
$17.49

Subtotal
Tax

$107.19
$10.71

Total

$117.90

Full Featured Table Completely Styled


HTML

<table>
<thead>
<tr>
<th class="item" colspan="2">Items</th>
<th class="qty">Qty</th>
<th class="price">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td class="item">Envisioning Information <span>By Edward R. Tufte Hardcover</span></td>
<td class="stock in">In Stock</td>
<td class="qty">1</td>
<td class="price">$33.32</td>
</tr>
<tr>
<td class="item">Outliers <span>By Malcolm Gladwell Hardcover</span></td>
<td class="stock in">In Stock</td>
<td class="qty">2</td>
<td class="price">$33.58 <span>($16.79 2)</span></td>
</tr>
<tr>
learn.shayhow
e.com/html-css/organizing-data-tables

11/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

<tr>
<td class="item">Dont Make Me Think <span>By Steve Krug Paperback</span></td>
<td class="stock out">Out of Stock</td>
<td class="qty">1</td>
<td class="price">$22.80</td>
</tr>
<tr>
<td class="item">Steve Jobs <span>By Walter Isaacson Hardcover</span></td>
<td class="stock in">In Stock</td>
<td class="qty">1</td>
<td class="price">$17.49</td>
</tr>
</tbody>
<tfoot>
<tr class="sub">
<td class="title" colspan="3">Subtotal</td>
<td class="price">$107.19</td>
</tr>
<tr class="tax">
<td class="title" colspan="3">Tax</td>
<td class="price">$10.71</td>
</tr>
<tr class="total">
<td class="title" colspan="3">Total</td>
<td class="price">$117.90</td>
</tr>
</tfoot>
</table>
CSS

table {
border-collapse: separate;
border-spacing: 0;
}
th, td {
vertical-align: top;
}
th {
background: #404853;
background: linear-gradient(#687587, #404853);
border-left: 1px solid rgba(0, 0, 0, 0.2);
border-right: 1px solid rgba(255, 255, 255, 0.1);
color: #fff;
font-size: 11px;
padding: 9px 8px 7px 8px;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.6);
text-transform: uppercase;
}
th.qty, th.price {
padding: 9px 20px 7px 20px;
text-align: center;
}
th.item {
border-left: 0;
}
th.price {
border-right: 0;
}
td {
padding: 8px;
learn.shayhow e.com/html-css/organizing-data-tables

12/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

}
tbody td {
border-bottom: 1px solid #c6c9cc;
border-left: 1px solid #e4e7eb;
border-right: 1px solid rgba(255, 255, 255, 0.6);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.6);
}
tbody tr:nth-child(even) td {
background: #e8eae9;
background: linear-gradient(#f7faf9, #e8eae9);
border-left: 1px solid #d5d8db;
}
tbody td.item, tbody tr:nth-child(even) td.item {
border-left: 1px solid #c6c9cc;
}
tbody td.item {
color: #404853;
font-weight: bold;
}
tbody td.stock, tbody td.qty, tbody td.price {
vertical-align: middle;
}
tbody td.stock, tbody td.qty {
text-align: center;
}
tbody td.price {
border-right: 1px solid #c6c9cc;
text-align: right;
}
tfoot td {
border-bottom: 1px solid #c6c9cc;
border-left: 1px solid #e4e7eb;
border-right: 1px solid rgba(255, 255, 255, 0.6);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.6);
text-align: right;
}
tfoot td.title {
border-left: 1px solid #c6c9cc;
}
tfoot td.price {
border-right: 1px solid #c6c9cc;
}
tfoot tr.sub td {
border-bottom: 0;
padding: 8px 8px 0 8px;
}
tfoot tr.tax td {
padding: 0 8px 8px 8px;
}
tfoot tr.sub td, tfoot tr.tax td {
color: #8c8c8c;
font-size: 12px;
}
tfoot tr.total td {
background: #e8eae9;
background: linear-gradient(#f7faf9, #e8eae9);
color: #404853;
font-size: 14px;
font-weight: bold;
}
tfoot tr.total td.price {
border-left: 1px solid #d5d8db;
}
learn.shayhow e.com/html-css/organizing-data-tables

13/15

1/15/13
Organizing Data w ith Tables - A Beginner's Guide to HTML & CSS

.in {
color: #00b515;
}
.out {
color: #b50000;
}
span {
color: #8c8c8c;
display: block;
font-size: 12px;
font-weight: normal;
}

Demo
Items

Qty

Price

Envisioning Information By Edward R. Tufte Hardcover In Stock

$33.32

Outliers By Malcolm Gladwell Hardcover

In Stock

$33.58 ($16.79 2)

Dont Make Me Think By Steve Krug Paperback

Out of Stock 1

$22.80

Steve Jobs By Walter Isaacson Hardcover

In Stock

$17.49

Subtotal

$107.19

Tax

$10.71

Total

$117.90

Resources & Links


HTML Tables via Dev.Opera
Bring on the Tables via 456 Berra St.
Styling Tables via Dev.Opera
Table Borders via Twitter Bootstrap

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share it with your
friends.

Lesson 8 Building Forms

Lesson 10 Coding Practices & Additional Resources

An Advanced Guide to HTML & CSS


learn.shayhow e.com/html-css/organizing-data-tables

14/15

1/15/13

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the latest for any
designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

Get Updates

learn.shayhow e.com/html-css/organizing-data-tables

15/15

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

Info

PR: error

I: error

L: 0

LD: 36

I: n/a

Rank: 238450

Age: n/a

I: 2

Tw: 74

l: 33

+1: wait...

A Beginners Guide to HTML & CSS


Lesson 1 Terminology, Syntax, & Introduction
Lesson 2 Elements & Semantics
Lesson 3 Box Model & Positioning
Lesson 4 Typography
Lesson 5 Backgrounds & Gradients
Lesson 6 Unordered, Ordered, & Definition Lists
Lesson 7 Images, Audio, & Video
Lesson 8 Building Forms
Lesson 9 Organizing Data with Tables
Lesson 10 Coding Practices & Additional Resources
A Beginners Guide to HTML & CSS is led by designer & front-end developer Shay Howe.
Additional help has been generously provided from a few amazing friends.
Taught in person as part of
The Starter League in beautiful downtown Chicago, Illinois.
Follow @shayhowe
Le sson 10

Coding Practices & Additional Resources


In this Lesson 10
HTML

HTML Coding Practices


Additional Resources
CSS

CSS Coding Practices


There are a lot of different elements, attributes, properties, values, and so forth to learn in order to write HTML
and CSS. Every lesson up until this point has had the primary objective of communicating these different parts of
HTML and CSS, in hopes of helping teach the core fundamentals. This lesson takes a step back and looks at a
more abstract picture of HTML and CSS.
learn.shay howe.com/html-css/coding-practices

1/10

This lesson in particular focuses on the best coding practices for both HTML and CSS. These coding practices,
while not covered in detail up until this point, serve as an overarching theme to the guide as a whole. They apply
to every lesson and should always be in consideration when programming.
In reviewing these best practices think about how they may be used in other areas or programming languages.
Using comments to organize code, as covered below, is beneficial in all programming languages. Keep an open
mindset and think about how to get the most out of each practice.

HTML Coding Practices


A lot of coding best practices are focused around keeping code lean and well organized. The general practices
within HTML are no different. The goal is to write well structured and standards compliant markup. The
guidelines outlined below provide a brief introduction to HTML coding practices, however this is not an
exhausted list.

Write Standards Compliant Markup


HTML by nature is a forgiving language, allowing poor code to execute and render accurately. This, however,
does not mean that the code is semantic or guarantee that it will validate as standards compliant. Stay focused
when writing HTML, be sure to nest and close all elements correctly, use IDs and classes accordingly, and
always validate your code.
<p id="intro"><strong>Lorem ipsum dolor sit.</p></strong>
<p id="intro">Ut enim veniam, quis nostrud exercitation.
<p class="intro"><strong>Lorem ipsum dolor sit.</strong></p>
<p class="intro">Ut enim veniam, quis nostrud exercitation.</p>

Make Use of Semantic Elements


The library of elements in HTML is nothing to laugh at with well over 100 elements available for use. Deciding
what elements to use to markup different content can be difficult, yet these elements are the backbone of
semantics. Do your research and double check your code to ensure you are using the proper semantic elements.
Users will thank you in the long run for building a more accessible website. If you are still weary of your code
find a friend to help out and perform routine code reviews.
<span class="heading"><strong>Welcome Back</span></strong>
<br /><br />
Duis aute irure dolor in reprehenderit in voluptate.
<br /><br />
<h1>Welcome Back</h1>
<p>Duis aute irure dolor in reprehenderit in voluptate.</p>

Use Practical ID & Class Values


Creating ID and class values can oddly be one of the more difficult parts of writing HTML. These values need to
be practical, relating to the content itself, not the style of the content. Using a value of red to describe red text

isnt ideal as it describes the presentation of the content. Should the text ever need to be changed to blue, not
only does the CSS need to be changed, but so does the HTML in every instance the class red exist.
<p class="red">Error! Please try again.</p>
<p class="alert">Error! Please try again.</p>

Provide Proper Attributes for Images & Links


Images and links should always include the alt and title attributes respectfully. Screen readers and other
accessibility software rely on these attributes to provide context around the image or link.
For images the alt value should be very descriptive of what the image contains. If the image is not of anything
pertinent the alt attribute should be included, however the value should be left blank so that screen readers
ignore it rather than read the name of the image file. Additionally, if an image doesnt have a meaningful value,
perhaps it is part of the user interface, it should be included as a background image if at all possible.
A links title attribute value works similar to that of an images alt attribute value. The title attribute value
should be the name of the page being linked to, not the hypertext being wrapped by the link element. From an
accessibility perspective the hypertext of click here doesnt mean anything, where the title attribute value of
Adobe Reader download does.
<img src="puppy.jpg" />
<a href="/reader/">Click Here</a>
<img src="puppy.jpg" alt="3 month old basset hound puppy" />
<a href="/reader/" title="Adobe Reader download">Click Here</a>

Separate Content from Style


Never, ever, use inline styles within HTML. Doing so creates pages that take longer to load, are difficult to
maintain, and an overall headache for users and developers alike. Instead, use external styles, using of IDs and
classes as necessary.
<p style="color: #393; font-size: 24px;">Thank you!</p>
<p class="alert-success">Thank you!</p>

Avoid a Case of Divitis


When writing HTML it is easy to get carried away adding a div here and a div there to build out any necessary
styles. While this works it begins to add quite a bit of bloat to a page, and before too long youre not sure what
each div does. Keep your code as lean as possible, tying multiple styles to one element when possible.
Additionally, use the new HTML5 structural elements as suitable.
<div class="container">
<div class="article">
<div class="headline">Headlines Across the World</div>
</div>
</div>

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

<div class="container">
<article>
<h1>Headlines Across the World</h1>
</article>
</div>

Continually Refactor Code


Over time websites continue to grow and grow, leaving behind quite a bit of cruft. Remember to remove old
code and styles as necessary when editing a page. Also take the time to evaluate code after you write it, looking
for ways to condense and make it more manageable.

CSS Coding Practices


Similar to HTML, the coding practices within CSS are focused around keeping code lean and well organized.
CSS also has some additional principles around how to specifically use some of the intricacies of the language.

Organize Code with Comments


CSS files can become quite extensive, spanning hundreds of lines. These large files can make finding and editing
code nearly impossible. Use comments to build a table of contents at the top of your file, as well as outline
blocks of code throughout the file. Doing so tells others exactly what is contained within the file, whereabout the
styles are located, and exactly what a specific style pertains to. Before sending CSS to the server it is a good
idea to compress and minify it, removing comments and other unnecessary spacing and characters.
header {...}
article {...}
.btn {...}
/* Header */
header {...}
/* Article */
article {...}
/* Buttons */
.btn {...}

Indent Selectors
In effort to better organize and make CSS more legible indenting selectors, nesting them based on the previous
selector, provides better coordinated code. At a glance you can recognize groups of selectors, helping identify
specific sets of styles.
footer {...}
footer h3 {...}
footer .col {...}
section a {...}
section strong {...}
learn.shay howe.com/html-css/coding-practices

4/10

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

footer {...}
footer h3 {...}
footer .col {...}
section a {...}
section strong {...}

Group & Align Vendor Prefixes


With CSS3 vendor prefixes have taken off, adding quite a bit of code to CSS files. The trade off of using vendor
prefixes is worth the generated styles, however they have to be kept organized. Again, keeping with the theme of
writing code that is easy to read and modify. With vendor prefixes grouping them together and indenting them to
align all of the properties and values together provides a quick and easy way to read and edit the styles.
div {
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
div {

-moz-border-radius:
-ms-border-radius:
-o-border-radius:
-webkit-border-radius:
border-radius:

5px;
5px;
5px;
5px;
5px;

Write CSS with Multi-Line Spacing


When writing CSS it is important to write it spanning multiple lines, placing selectors and each style declaration
on a new line. Doing so makes the code easy to read as well as edit. When all of the code is piled into one line
its harder to scan and make changes. Additionally, if you are looking for the difference between two sets of
code, placing all of the properties within one line makes it nearly impossible to spot a small change.
Compressing and minifying CSS before sending it to the server is completely acceptable, even encouraged.
However, when working with CSS files locally, comments and multi-line spacing can make a world of difference.
a {background: #aaa; color: #f60; font-size: 18px; padding: 6px;}
a {
background: #aaa;
color: #f60;
font-size: 18px;
padding: 6px;
}

Modularize Styles for Reuse


CSS by default is built in a way to allow styles to be reused, specifically with the use of classes. Class styles
learn.shay howe.com/html-css/coding-practices

5/10

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

should be modular and available to be applied to any element as necessary. If a section of news is presented
within a box, including a border, background color, and other styles the class of news might sound like a good
option. However, those same styles may also need to be applied to a section of upcoming events. The class of
news doesnt fit in this case. A class of modal would make more sense and may be used across the entire
website.
Pump the Brakes
Yes, the best practices around class values from HTML and CSS are a bit conflicting. Use values that pertain to
the content, however naming them in away that they can be reused across the entire website doesnt quite make
sense. The main point here is to really think about what you are using as values and provide values that are
meaningful.
Twitter Bootstrap does a great job of this. Buttons are modularized using the btn class and can be used on a,
button, or any other element. No matter what, any element receiving the btn class will inherit the correct button
styles. Additionally, if you want a red button, instead of using a class of red you can use the class of btndanger. Combining the two classes, btn btn-danger, generates a red button.
.news {
background: #eee;
border: 1px solid #ccc;
border-radius: 6px;
}
.events {
background: #eee;
border: 1px solid #ccc;
border-radius: 6px;
}
.modal {
background: #eee;
border: 1px solid #ccc;
border-radius: 6px;
}

Create Proper Class Names


As mentioned above, class values should be modular while pertaining to the content as much as possible. These
values should be named in such a way that they resemble the CSS language. In such, class names should be all
lowercase, using hyphen delimiters.
.Alert_Message {...}
.alert-message {...}

Build Proficient Selectors


CSS selectors can get out of control if not carefully watched. They can become too location specific as well as
too long fairly easily. For the longest time weve been told not to use classes and to use element selectors as
much as possible. Regrettably, this isnt true.
learn.shay howe.com/html-css/coding-practices

6/10

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

The longer a selector is, chaining multiple elements together, the more work the browser has to do in checking to
make sure each selector matches before applying a style. Doing so creates a large performance hit, slowing
down the rending of any styles. Make selectors as small as possible while still targeting the desired element.
Additionally, the more specific a selector is the more dependent it is on its location within HTML. If emphasized
text is nested within a heading inside of an aside the selector might look something like aside h1 em. Should
the emphasized text ever be moved out of the heading the styles will no longer apply. A better, more flexible
selector would be aside em.
ul.news li a {...}
ul.news li a em.special {...}
.news a {...}
.news .special {...}

Use Specific Classes When Necessary


There often comes a time when a CSS selector is so long and specific that it no longer makes sense. It creates a
performance lag and is strenuous to manage. In this case a class is advised. While applying a class to the targeted
element may create more code within HTML it will render faster and remove any managing obstacles.
article div h4 a span {...}
.offset {...}

Use Shorthand Properties When Available


One of the benefits of CSS is the ability to use shorthand properties. Nearly every property has an acceptable
shorthand property or value. As an example, rather than using four different sets of properties and values to
declare a margin one single property can be used. Additionally, one margin property can be used to set the four
values in a couple of different ways. All four value can be declared individually in a clockwise order, two values
can be declared by combining the top/bottom and left/right values, or by declaring one value for all four sides of
an element. The same pattern, and many others, may be reused with multiple properties.
When setting one value shorthand properties should not be favored. If a box simply needs a bottom margin, the
bottom-margin property should be used so that other margin values will not be overwritten.
img {
margin-top: 5px;
margin-right: 10px;
margin-bottom: 5px;
margin-left: 10px;
}
button {
padding: 0 0 0 20px;
}
img {
margin: 5px 10px;
}
button {
learn.shay howe.com/html-css/coding-practices

7/10

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

padding-left: 20px;

Drop Unit Type from Zero Values


One way to easily cut down on the amount of CSS code written is to remove the unit type from any zero value.
No matter what length value being used, pixels, percentages, em, and so forth, zero is always zero.
div {
margin: 20px 0px;
letter-spacing: 0%;
padding: 0px 5px;
}
div {
margin: 20px 0;
letter-spacing: 0;
padding: 0 5px;
}

Additional Resources & Links


Every lesson within this guide has come with a few resources for additional learning and discovery. Outlined
below is a longer list of resources, as well as beneficial links. Many of these resources have helped in preparing
the guide while others are simply nice to know.

HTML & CSS


Mozilla Developer Network via Mozilla
The Web Standards Curriculum via Opera.Dev
30 Days to Learn HTML & CSS via Tuts+
HTML and CSS Tutorials via HTML Dog
DocHub Instant documentation search
Pears Common patterns of markup and style

Design Inspiration
Dribbble
Pattern Tap
Premium Pixels
Launched Pixels

Frameworks & Styleguides


Web Style Guide
Bootstrap, from Twitter
Skeleton Framework
Starbucks Styleguide
learn.shay howe.com/html-css/coding-practices

8/10

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

GitHub Styleguide
Global Experience Language for the BBC
WordPress.org UI Styleguide

Icons
Fugue Icons via Yusuke Kamiyamane
famfamfam Icons via Mark James
Social Network Icon Pack via Rogie King

Miscellaneous
960 Gridder Easily align and lay out websites
Responsive.is Display responsive web designs
W3Clove Validate an entire sites HTML markup
FontFuse Find and create cool font pairings
COLOURlovers Color trends and palettes
ColorHexa Color encyclopedia
Modernizr JavaScript feature detection library
jQuery Tools jQuery user interface components

Complete! Any questions?


Share
Tweet
Like
Email
Please feel free to contact me on Twitter if you have any questions. Also, if you enjoyed this lesson please share
it with your friends.

Lesson 9 Organizing Data with Tables

An Advanced Guide to HTML & CSS

learn.shay howe.com/html-css/coding-practices

Coding
1/15/13
Practices & Additional Resources - A Beginner's Guide to HTML & CSS

An Advanced Guide to HTML & CSS takes a deeper look at front-end design & development, teaching the
latest for any designer looking to round out their skills.
View the Advanced Guide to HTML & CSS

Join the Newsletter


SPAM Fre e

To stay up to date and learn when new courses and lessons are posted, please sign up for the newsletter.
Email Address

learn.shay howe.com/html-css/coding-practices

Get Updates

10/10

You might also like