a beginners guide to html & css

97
1/15/13 Terminology , Sy ntax, & Introduction - A Beginner's Guide to HTML & CSS 1/9 learn.shay howe.com/html-css/terminology -sy ntax-intro Info PR: error I: error L: 1 LD: 36 I: n/a Rank: 238450 Age: n/a I: 103 Tw: 74 l: 33 A Beginner’s 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 Beginner’s 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 Lesson 1 Terminology, Syntax, & Introduction In this Lesson 1 HTML Common Terms Structure & Syntax Referencing CSS CSS Common Terms Structure & Syntax Selectors Reset

Upload: natnael22

Post on 12-Jan-2016

261 views

Category:

Documents


2 download

DESCRIPTION

HTML & CSS

TRANSCRIPT

Page 1: A Beginners Guide to HTML & CSS

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

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 1

Terminology, Syntax, & Introduction

In this Lesson 1

HTML

Common TermsStructure & SyntaxReferencing CSS

CSS

Common TermsStructure & SyntaxSelectorsReset

Page 2: A Beginners Guide to HTML & CSS

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

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

Before beginning our journey to learn HTML and CSS it is important to understand the differences between thetwo 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 CSSdetermines the style and appearance of this content. The two languages are independent of one another. CSSshould 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. Thep element is specifically used here as it is provides the most value for the content, thus being the most semanticelement. CSS then uses a type selector of p which can determine the color, font size, font weight, and otherstylistic 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 willbecome 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 morepopular 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 thebeginning of an element, such as <div>. Closing tags mark the end of an element and begin with a forwardslash, such as </div>.

<a>...</a>

Attributes

Attributes are properties used to provide additional instruction to given elements. More commonly, attributes areused to assign an id, class, or title to an element, to give media elements a source (src), or to provide ahyperlink reference (href).

<a href="http://www.shayhowe.com/" title="Shay Howe">Shay Howe</a>

Common HTML Terms Example

Shay Howe

Page 3: A Beginners Guide to HTML & CSS

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

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

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 placedat the very beginning of the HTML document. Following the doctype declaration, html tags signify thebeginning 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 contentvisible 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. Themore 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 caninclude a combination of different IDs, classes, types, and other attributes – all depending on how specific youwish 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 comingimmediately before a colon. There are an abundance number of properties you can use, and new ones arecontinually being added.

p { color: #ff0; font-size: 16px;

Page 4: A Beginners Guide to HTML & CSS

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

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

}

Values

A value determines the behavior of a property. Values can be identified as the text in-between the colon andsemicolon.

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 differentstyles 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, andweight. 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 multipledeclarations, one after the other for each property and value. With short hand CSS you use one property and listmultiple values. It is best to use short hand CSS as it requires less code. Not all properties support short handCSS 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 */

Page 5: A Beginners Guide to HTML & CSS

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

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

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 helpwith organization, set reminders, and manage code more effectively. Comments become especially useful whenthere are multiple people working on the same code. Any content wrapped within comments will not berendered on the page.

HTML comments wrap the content starting with <!-- and end with -->. CSS comments wrap the contentstarting with /* and end with */.

Selectors

Selectors, as mentioned earlier, are the determining factor as to which elements are to be stylized. In so, it isimportant to fully understand how to use selectors and how they can be leveraged. Some of the most commonselectors 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 aretargeted to apply styles. Type selectors are preferred whenever possible as they require less code and are easyto 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 classattribute. Classes are denoted in CSS by identifying the class with a leading period. It is permissible to use thesame class attribute on multiple elements on a page.

HTML

Page 6: A Beginners Guide to HTML & CSS

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

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

<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, IDsare denoted by identifying the ID with a leading hash sign. IDs are only allowed to be used once per page andshould 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 moregeneric selector and work your way to being more specific as necessary. In addition, you can combine differentselectors 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 moreadvanced selectors exist and are readily available. Before dropping classes or IDs on random elements checkand see if there might be a better selector to do the job for you. It is also worth mentioning that not all advanceselectors work in every browser, particularly with new selectors introduced in CSS3. If a selector doesn’t seemto be working properly check its browser support.

Page 7: A Beginners Guide to HTML & CSS

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

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

Referencing CSS

Once content is in place you may begin to style the HTML with CSS. There are a handful of different ways toreference 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, referencedwithin the heading of a page. Using an external stylesheet allows you to use the same styles across an entirewebsite and quickly make changes site wide.

Other options include internal and inline styles. These options are generally frowned upon as they make updatingwebsites 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 useone set of styles across an entire website. Making changes to the style of a website becomes painless, and usersdownload 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 HTMLfile and the CSS file. Since you are linking to CSS the rel attribute with a value of stylesheet is used tospecify 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 fileis stored. In the example above the file.css is stored within the root directory, the same location as theHTML 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 bestyles/file.css, using a forward shash to indicate different directories.

<head> <link rel="stylesheet" href="styles/file.css"></head>

Reset

Page 8: A Beginners Guide to HTML & CSS

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

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

By default every web browser has it’s own interpretation on how different elements are to be stylized. HowChrome decides to render an input field is likely going to be much different than how Internet Explorer rendersan 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 crossbrowser compatibility and testing. Websites don’t need to look the same in every browser but they should beclose. What browsers you wish to support and to what degree is a decisions you will need to make inaccordance 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 oneunified style. These resets involve removing any sizing, margins, paddings, or additional styles. Resets need to bethe very first CSS styles to be rendered to ensure that all the styles there after are being applied to the skeletonof a page.

There are a ton of different resets available to use, all of which have their own forte. My personal favorite is EricMeyers reset, which has been adapted to include a reset for the new HTML5 elements. Eric’s reset is short andto the point, but feel free to research your own resets and find what you’re comfortable using.

Code Validation

As proficient as we all are, we do make mistakes. Thankfully when writing HTML and CSS we have a validatorthat can check our work. The W3C has built both HTML and CSS validators that will scan your code lookingfor mistakes. Validating your code not only helps it render properly across all browsers, it also teaches you thebest practices for writing code.

Resources & Links

Common HTML Terms via Scripting MasterCSS Glossary via Code StyleTaming Advanced CSS Selectors via Smashing MagazineCSS Tools: Reset CSS via Eric MeyerAn Intro to HTML & CSS via Shay Howe

Complete! Any questions?

Share

TweetLikeEmail

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

Page 9: A Beginners Guide to HTML & CSS

1/15/13

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

«»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 thelatest for any designer looking to round out their skills.

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

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

Email Address Get Updates

Page 10: A Beginners Guide to HTML & CSS

1/15/13 Elements & Semantics - A Beginner's Guide to HTML & CSS

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 2

Elements & Semantics

In this Lesson 2

HTML

Semantics OverviewDivisions & SpansTypographyHyperlinksHTML5 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 thesedifferent 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 wellinformed 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 andstructure. 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 givingcomputers, screen readers, search engines, and other devices the ability to adequately read and understand web pages. Additionaly, semantic code is easier to manage and workwith, 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 semanticvalue. 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 commonlyused 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. What’s 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.

Page 11: A Beginners Guide to HTML & CSS

1/15/13 Elements & Semantics - A Beginner's Guide to HTML & CSS

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

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 contextof 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 thatorange 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 thecontents 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 differentelements 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 theTypography 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 andprovide 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 asnecessary. 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, addinginformation 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 proident.</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 willmake 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 meansstylistically offset, which isn’t 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 elementaccordingly.

<p>Duis in <strong>voluptate</strong> velit esse cillum.</p>

Bold Text Demo

Duis in voluptate velit esse cillum.

Italicize Text with Emphasis

Page 12: A Beginners Guide to HTML & CSS

1/15/13 Elements & Semantics - A Beginner's Guide to HTML & CSS

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

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 differentsemantic 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 valuestext 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 thelink. 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, andother devices obtain a little more context to what the link is about. Generally speaking, the title shouldn’t 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 thestandard 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 valueof 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 onthe 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 thehref 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 hrefattribute 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 addresswhere 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 [email protected] the href attribute value would be mailto:[email protected].

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 asubject 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, spacesmust be encoded using %20 and line breaks must be encoded using %0A.

Altogether, a link to [email protected] with the subject of “Still Awesome” and body text of “This is awesome” would look like mailto:[email protected]?subject=Still%20Awesome&This%20is%20awesome. Please notice, the first parameter requires a ? to bind it to the email address and additional parameters require a & to bindthem the previous parameter.

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:[email protected]?subject=Still%20Awesome&body=This%20is%20awesome" title="[email protected]">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, howeverlinks 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 determineswhere 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>

Page 13: A Beginners Guide to HTML & CSS

1/15/13 Elements & Semantics - A Beginner's Guide to HTML & CSS

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

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 theappropriate 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 touse 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, ornavigation. 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 mayreappear 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 isused 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 reservedfor 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 navelement, 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

Page 14: A Beginners Guide to HTML & CSS

1/15/13 Elements & Semantics - A Beginner's Guide to HTML & CSS

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

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 contentthat 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 thearticle 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 beable 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. Wherea 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 shouldn’t be using a section aimlessly with the sole purpose of adding styles. Reserve the section element for largeparts 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 isn’texplicitly 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 commonlywill 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 apage 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 withheader 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 theaside to appear to the right or left of a block of content you will need to float the aside element. Don’t worry about floats right now, we will learn about floating and positioningcontent 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 orsection at hand and its context should include relative information.

<footer>...</footer>

D.R.Y. – Don’t Repeat Yourself

One principle of development is D.R.Y., also known as don’t repeat yourself. Within CSS this principle can speak volumes as it is easy to continually write the same styles over andover again. Don’t. 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 lightcode, of which is semantic and easily managed.

Resources & Links

Semantic code: What? Why? How? via BoagworldHTML5 DoctorThe i, b, em, & strong Elements via HTML5 DoctorThe Full mailto Link Syntax via Joost de ValkNew Structural Elements in HTML5 via Dev.Opera

Complete! Any questions?

Share

TweetLikeEmail

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

Page 15: A Beginners Guide to HTML & CSS

1/15/13 Elements & Semantics - A Beginner's Guide to HTML & CSS

6/6learn.shayhowe.com/html-css/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 Free

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

Email Address Get Updates

Page 16: A Beginners Guide to HTML & CSS

1/15/13

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 3

Box Model & Positioning

In this Lesson 3

HTML

Box Sizing

CSS

The Box ModelHeight & WidthMargin & PaddingBordersFloating ElementsPositioning Elements

Page 17: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

One principle necessary to fully understand HTML and CSS is the box model. The box model concept statesthat every element on a page is a rectangular box, and may include margins, padding, and borders.

That’s 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 anunderstanding 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 fewdifferent 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. Theseboxes can come in different sizes and may have margins, padding, and borders to alter their size. The formationof all of these properties together is referred to as the box model. Let’s take a look at the box model, along withthese 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 oftheir 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 ofdifferent 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, thecontents of the element, or by specified height and width properties. The height and width is then followedby the padding and border. The margin follows the border, however it is not technically included within theactual size of the box. Although it’s not included within the size of the box, the margin does help define the boxmodel.

Page 18: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

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 + 20pxHeight: 192px = 20px + 6px + 20px + 100px + 20px + 6px + 20px

Let’s 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 heightand width may be adequate. If an element is key to the layout and design of a page it may require a specifiedheight and width. In this case the default values for block level elements may be overridden.

CSS Height Property

Page 19: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

The default height of an element is determined by its content. An element will expand and contract vertically asnecessary to accommodate its content. To set a specific height for a block level element the height property isused.

div { height: 100px;}

CSS Width Property

The default width of an element depends on its display type. Block level elements have a default width of100%, consuming the entire horizontal space available. Inline elements expand and contract horizontally tooccupy their content then stop. Since inline level elements cannot have a fixed size, the width property, as withthe 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. Thedefault values for these properties differ from browser to browser and element to element. In lesson one wediscussed using a CSS reset to tune all of these default values down to zero. Using a reset allows us to workfrom 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 anyborder and are completely transparent. Margins can be used to help position elements within a particular placeon 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 elementsborder. Paddings will also inherit any backgrounds of an element. Padding is used to provide spacing within anelement, not for positioning an element like the margin property.

div { padding: 20px;}

Page 20: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

Fig. 3.03 A box model breakdown using margins for spacing between elements and padding forspacing 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 sidesof 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 withmargin or padding respectfully and is then followed with a dash and the side of the box to which the value is tobe applied, top, right, bottom, or left. As an example, the padding-left property takes one value andwill 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 needsthree values, a size, style, and color. Shorthand values fall in the order of size, style and color. Longhand, thesethree 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 tocome in numerous sizes, shapes, and colors.

Page 21: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

6/10

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 andabsolute values.

Relative values are correlative to the element of which the value is being applied. These values may include emand 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 involvesknowing how to properly align all of the different elements on the page. One way to position elements along sideone another is to use the float property. The float property allows you to take elements and float them rightor 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 levelelements, will be stacked on top of one another by default. However, we want them to sit side by side. By givingeach element a specific width and floating one of them left and the other to the right we can position themcorrectly.

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 isgoing to float all the way to the edge of its parent container. If there isn’t a parent element it will float all the wayto the edge of the page. Additionally, when floating an element without setting a specific width, other elementswill begin to line up around it within the natural flow of the page.

Page 22: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

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 thefloated one as necessary. Sometimes this is good, such as when floating an image to the side of a block ofcontent, 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 clearproperty. The clear property acts on the element it is applied to and returns the document back to its normalflow, 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 itto 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 propertycomes 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 valueallows you to use box offset properties such as top, right, bottom and left. The absolute and fixedvalues work with box offset properties too, but break the element from the normal flow of a document. Thesevalues, absolute and fixed, correspond directly with an elements parent who has a position value ofrelative.

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

Page 23: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

as a static element yet act as the primary container to any absolutely positioned element within it. The ul is thenabsolutely 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 offsetproperties include top, right, bottom and left. Depending on the property, they position an element in thedirection specified, top, right, bottom or left.

For example, bottom: 32px; will position an element 32 pixels from the bottom of its parent element with aposition value of relative. In contrast, bottom: -32px; will position an element 32 pixels below its parentelement with a position value of relative.

Box offset properties may be used in pairs, top or bottom and left or right. CSS will cascade theseproperties 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 frameworkshave risen to the forefront.

Grids, both vertical and baseline, provide a great way to add cadence to your website and keep everythingaligned. There are a handful of different recommended grids that have become popular over the years. You canpick 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. Dependingon the project, frameworks can provide a great starting point or even a complete solution. They can also causemore trouble than they’re worth. Before getting too far over your head, research the framework and make sureyou are comfortable working with it and editing it.

Page 24: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

Resources & Links

CSS Length Values via Mozilla Developer NetworkHTML Borders via Quackit.comThe CSS Box Model via CSS-TricksCSS Float Theory via Smashing MagazineCSS Positioning 101 via A List ApartResources for Grid-Based Design via Vandelay Design

Complete! Any questions?

Share

TweetLikeEmail

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

«Lesson 2 Elements & Semantics«»Lesson 4 Typography

An Advanced Guide to HTML & CSS

Page 25: A Beginners Guide to HTML & CSS

1/15/13 Box Model & Positioning - A Beginner's Guide to HTML & CSS

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

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

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

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

Email Address Get Updates

Page 26: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

1/8learn.shayhowe.com/html-css/typography

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 4

Typography

In this Lesson 4

HTML

Formatting ContentCitations & Quotes

CSS

Text ColorFont PropertiesText PropertiesWeb Safe FontsEmbedding 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 theability 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 acomputer, 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 oftypography 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 termsshould 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 iscreated 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 theartistic 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 ontypography. As a brief review let’s recap headings, paragraphs, and how to bold or italicize text.

Headings

Page 27: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

2/8learn.shayhowe.com/html-css/typography

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, moreimportant 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 wemust 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 couldbe 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 typefaceimmediately 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, hexadecimalvalues, 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 withCSS3 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. Thesepatterns 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 shortenedto #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 textbased properties. Most properties corresponding to these categories will be prefaced with either font-* or text-*. To begin we’ll 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, allcomma 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 toright. 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 fontin 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 andmore often the pixel value is used as it provides the most control over a font’s size. Previously, em and percentage values used to be fairly popular because they allow the text to scalerelatively 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, andinherit. 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.

Page 28: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

3/8learn.shayhowe.com/html-css/typography

p { font-style: italic;}

Font Variant

It isn’t 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-variantproperty accepts three values, including normal, small-caps, and inherit. The most typically seen values are normal and small-caps to switch between normal and small-caps, 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 thisproperty.

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-weightproperty 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 tochange 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 thethickest 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 numeralvalues 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 existwithin 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, asmentioned 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 quicklyaccomplished 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 bepreferred.

Line height may also be used to vertical center single lines of text within an element. Setting an element’s line-height to the same value as the element’s height will verticallycenter 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 toright: 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 rightwithout 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 shorthandvalue 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 auctor tortor, et lorem massa orci… <a href="#" title="Sample Blog Post Title">Continue reading →</a></p>

CSS

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

Page 29: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

4/8learn.shayhowe.com/html-css/typography

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, andspace 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 notbe 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 entireelement. 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, andinherit. 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 itcan 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 dependingon 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 threevalues are all lengths while the last value is a color. Within the three length values the first value determines the shadow’s horizontal offset, the second value determines the shadow’svertical offset, and the third value determines the shadow’s blur radius. The fourth, and last, value is the shadow’s color, which can be any of the color values used within the colorproperty.

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 andbelow 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 thetext-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. Usingnone will take any of these inherited values and roll them back to the text default.

Page 30: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

5/8learn.shayhowe.com/html-css/typography

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 lengthvalues 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 lengthvalues 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 auctor tortor, et lorem massa orci… <a href="#" title="Sample Blog Post Title">Continue reading →</a></p>

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 →

Page 31: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

6/8learn.shayhowe.com/html-css/typography

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 fontsto 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 ahandful of web safe fonts, of which the safest ones to use are listed below.

ArialCourier New, CourierGaramondGeorgiaLucida Sans, Lucida Grande, LucidaPalatino LinotypeTahomaTimes New Roman ,TimesTrebuchetVerdana

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. Thisability 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 andposting 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 thecorrect 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. Recentbrowsers 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 apage. 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 titleof 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 contextto 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 shouldn’t includeany 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 ifrelevant.

<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 truly inspirational.</p>

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 tosemantically note dialog or prose and shouldn’t 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 doesn’t alter the

appearance of the element, it simply adds value to screen readers and other devices. Since the attribute isn’t viewable within the browser it is recommended to provide a hyperlink

Page 32: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

7/8learn.shayhowe.com/html-css/typography

appearance of the element, it simply adds value to screen readers and other devices. Since the attribute isn’t viewable within the browser it is recommended to provide a hyperlinkincluding 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</a> once said, <q cite="http://www.businessweek.com/magazine/content/06_06/b3970001.htm">“One home run is much better than two doubles.”</q></p>

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 thatmay include other block level elements nested inside of it including headings and paragraphs.

<blockquote> <p>“In most people’s vocabularies, design is a veneer. It’s interior decorating. It’s 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.”</p> <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 befairly 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 qelement 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 don’t add any visual reference for users hyperlinks are also preferred when available. These hyperlinks shouldhighlight 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 people’s vocabularies, design is a veneer. It’s interior decorating. It’s 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.”</p> <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/fortune/fortune_archive/2000/01/24/272277/index.htm" title="Apple's One-Dollar-a-Year Man">Fortune Magazine</a></cite></p></blockquote>

External Demo

“In most people’s vocabularies, design is a veneer. It’s interior decorating. It’s the fabric of the curtains, of the sofa. But to me, nothing could be further from the meaningof 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 properlywith 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 todynamically 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 pseudo-elements 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.OperaQuoting and citing with blockquote, q, cite, and the cite attribute via HTML5 DoctorCSS Font Shorthand Property Cheat Sheet via Impressive WebsThe Elements of Typographic Style by Robert Bringhurst

Complete! Any questions?

Share

Tweet

Page 33: A Beginners Guide to HTML & CSS

1/15/13 Typography - A Beginner's Guide to HTML & CSS

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

LikeEmail

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 Free

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

Email Address Get Updates

Page 34: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 5

Backgrounds & Gradients

In this Lesson 5

CSS

Background ColorBackground ImageGradient BackgroundsMultiple BackgroundsCSS3 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 anelement’s content, enhancing usability. With use cases large and small, backgrounds have a significant impact onthe 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

Page 35: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

solid color, an image, or a combination of the two. The ability to control exactly how a background isimplemented on an element provides greater direction to the overall appearance.

With CSS3, new backgrounds and capabilities were introduced, including the ability to include gradientbackgrounds and multiple background images on a single element. These progressions are becoming widelysupported 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 backgroundor background-color property. The background property accepts colors and images, while thebackground-color property is used strictly for background colors. Either property will work, which one youdecide 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 othercolor values, you can pick from keywords, hexadecimals, RGB, RGBa, HSL, and HLSa. Most commonly seenare hexadecimal values, however it is important to note RGBa and HLSa. These color spectrums allow us to useopacity within our background via an alpha channel. If we are looking to use a 30% opaque black we can usergba(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 declarationabove 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 imageswork similarly to background color, however they also offer a few additional properties to finesse the images. Asbefore, you can use the background property or the background-image property. No matter which propertyyou use there must be an image source identified using the url value. The url value should be the backgroundimage’s 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 andvertically from the top left of the containing element. Thankfully we can use the background-repeat andbackground-position properties to straighten things out.

Page 36: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

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 backgroundproperty 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. Therepeat value is set by default and will repeat an image both vertically and horizontally. repeat-x will repeat theimage horizontally and repeat-y will repeat the image vertically. no-repeat simply means: display thebackground 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 orrepeated from. As with the other background properties, a background position may be added using thebackground 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 abackground position value you can use the top, right, bottom, left keywords, pixels, percentages, andother length measurements. Keywords and percentages work very similarly. The keywords top left areidentical 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 avalue. To center the background image at the top of an element you could use the value 50% 0. Using pixels fora background position is also popular, as pixels give you exact control of where your background will bepositioned.

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

Page 37: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

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 modernbrowsers.

Gradient backgrounds are treated as a background image. You can create a gradient using the background orbackground-image properties just like you would a regular background image. The value for these propertiesvary 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 makerimplementing new properties in a slightly different way. In doing so browsers used vendor prefixes to establishexactly how their features should look and perform. Gradient backgrounds took the brunt of this as eachbrowser had its own preferred method for gradient values. Fortunately, most browsers have settled on astandard, however it is still worth outlining support for all of them as a fall back.

While vendor prefixes are becoming less relevant it still doesn’t hurt to use them for older browsers.

Mozilla Firefox: -moz-Microsoft Internet Explorer: -ms-Opera: -o-Webkit (Chrome & Safari): -webkit-

Linear Gradient Background

Page 38: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

For years designers and developers have been cutting up image files and using them as linear gradientbackgrounds. The process worked, but took a while to implement and was difficult to change. Fortunately, thosedays are gone and linear gradient backgrounds can now be specified within CSS. If a color needs changed, thereis 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: #70bf32; background: url('linear-gradient.png') 0 0 repeat-x; background: -moz-linear-gradient(top, #a1e048, #6a942f); background: -ms-linear-gradient(top, #a1e048, #6a942f); background: -o-linear-gradient(top, #a1e048, #6a942f); background: -webkit-linear-gradient(top, #a1e048, #6a942f); background: 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 mostsupported and thus the standard. Moving forward, including radial gradients, we’ll use this formatting but don’tforget the other values.

Taking a closer look at the value you will notice the keyword top declared. The keyword value states where thebackground gradient will start and then move in the opposite direction. All top, right, bottom, and leftkeywords 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 lefttop 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 radialgradient 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. We’ll cover thebasics, 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,

Page 39: A Beginners Guide to HTML & CSS

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

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

some coming with presets and examples and some having an expansive list of options. If interested, I recommenddoing 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 transitionmore than two colors you can use color stops. Instead of declaring two color values, you can declare numerousvalues. The browser will transition from one to the next accordingly. Adding a length value to these color stopsdetermines at what position and distance the transition will take place. If no length value is declared the gradientwill 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 class="play"><a href="#" title="Play">Play</a></li> <li class="back"><a href="#" title="Skip Backward">Skip Backward</a></li> <li class="stop"><a href="#" title="Pause/Stop">Pause/Stop</a></li> <li class="forward"><a href="#" title="Skip Forward">Skip Forward</a></li></ul>

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;

Page 40: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

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

PlaySkip BackwardPause/StopSkip 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 withanother element and assign a background to the wrapping element. This created bloated code for the simple useof adding additional backgrounds. Now with CSS3 we can use multiple background images on a single elementby chaining these background values together.

div { background: url('foreground.png') no-repeat 0 0, url('middle-ground.png') no-repeat 0 0,

Page 41: A Beginners Guide to HTML & CSS

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

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

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 CSSproperties, 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 firstvalue declared is the width of the image and the second value is the height. These values may include any lengthmeasurement or keyword, most notably pixels and percentages. If only one value is declared, the auto keywordmay 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;

Page 42: A Beginners Guide to HTML & CSS

}

Cover & Contain Values

The cover keyword value specifies that the background image should be resized proportionally to completelycover an element. How the background will be resized depends on the dimensions of the background andelement. While the background will hold its dimensions proportionally, the quality of the image may be resized ina 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 theelement. This may mean that there are parts of the element without a background, however the entirebackground image will be visible. As with the cover keyword value, the resizing of the background image willbe proportional to the image’s dimensions, however it may result in a distorted image.

Shay HoweFig. 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 background-origin property specifies where the background-position should originate. The introduction of these twonew properties also includes three new values: border-box, padding-box, and content-box. Each of thesethree 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

Page 43: A Beginners Guide to HTML & CSS

1/15/13 Backgrounds & Gradients - A Beginner's Guide to HTML & CSS

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

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 WeakleyCSS3 Linear Gradients via Dev.OperaCSS3 Radial Gradients via Dev.OperaCSS Gradient Background Maker

Complete! Any questions?

Share

TweetLikeEmail

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

«Lesson 4 Typography«»Lesson 6 Unordered, Ordered, & Definition Lists

An Advanced Guide to HTML & CSS

Page 44: A Beginners Guide to HTML & CSS

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

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

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

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

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

Email Address Get Updates

Page 45: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 6

Unordered, Ordered, & Definition Lists

In this Lesson 6

HTML

Unordered ListOrdered ListDefinition ListNested Lists

CSS

List Item StylizationHorizontally 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 alist 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 orderisn’t 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 listsare 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 instylization.

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 isaccomplished 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

iPadiPhoneMacBook Air

Page 46: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

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 anunordered 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. iPad2. iPhone3. 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 attributedetermines 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 startattribute 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. iPad31. iPhone32. 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 Booleanattribute so it doesn’t 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 andreversed 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 updatedvalue 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. Allother items below this one will be calculated as necessary, starting at ten.

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

Value Attribute Demo

1. iPad9. 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 actuallyrequires 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 multipledescriptions 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 andpadding properties within CSS.

<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 person’s regular occupation, profession, or trade</dd></dl>

Page 47: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

Definition List Demo

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

designa plan or drawing produced to show the look and function or workings of a building, garment, or other object before it is built or madepurpose, planning, or intention that exists or is thought to exist behind an action, fact, or material object

businesswork

a person’s 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 livewithin 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 doesn’t provide free reignto 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 thewrapping 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 dog2. Fold laundry3. Go to the grocery and buy:

MilkBreadCheese

4. Mow the lawn5. 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 contentand 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 toArmenian 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 notrecommended 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. It’s rare that a single list item would need to be stylized differently than therest, however it is possible.

List Style Type Values

none No list itemdisc A filled circlecircle A hollow circlesquare A filled squaredecimal Decimal numbersdecimal-leading-zero Decimal numbers padded by initial zeroslower-roman Lowercase roman numeralsupper-roman Uppercase roman numeralslower-greek Lowercase classical Greeklower-alpha / lower-latin Lowercase ASCII lettersupper-alpha / upper-latin Uppercase ASCII lettersarmenian Traditional Armenian numberinggeorgian Traditional Georgian numbering

Page 48: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

ul { list-style-type: circle;}

List Style Type Demo

iPadiPhoneMacBook 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 completelypossible. 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 beconsidered 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 elementstyle. 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

iPadiPhoneMacBook 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, thedefault 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 contentproperty. 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 itemcontent.

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

iPadiPhoneMacBook 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 directlyto 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 doesn’t allow any content towrap 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. It’s the most amazing iPhone yet.MacBook Air – The new MacBook Air is faster and more powerful than before, yet it’s still incredibly thin and light. It’s 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

Page 49: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

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 fewlist 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 listitems.

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 adefault 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 spacebetween them. Ideally margins or padding should be added to better space these elements apart.

li { display: inline; margin: 0 10px;}

Inline Display List Demo

iPadiPhoneMacBook Air

Floating List

Changing the display property to inline is quick, however it doesn’t provide much control over how to stylize the list items and removes the list item element. In the case where alist 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 stilldisplayed 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 thelist to return the page back to its intended flow.

li { float: left; margin: 0 20px;}

Floating List Demo

iPadiPhoneMacBook Air

Navigational List Example

HTML

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

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);

Page 50: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

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

ProfileSettingsNotificationsLogout

Resources & Links

HTML List via Dev.OperaStyling HTML Lists with CSS via Smashing MagazineList Style Type via Mozilla Developer NetworkCSS Design: Taming Lists via A List Apart

Complete! Any questions?

Share

TweetLikeEmail

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.

Page 51: A Beginners Guide to HTML & CSS

1/15/13 Unordered, Ordered, & Definition Lists - A Beginner's Guide to HTML & CSS

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

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

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

Email Address Get Updates

Page 52: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 7

Images, Audio, & Video

In this Lesson 7

HTML

Adding ImagesAdding AudioAdding VideoFigure & Caption

CSS

Sizing ImagesPositioning 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 giveusers 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 andvideo 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 wayonline.

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 doesn’t wrap any other content and exists as a single tag. For the imgelement 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 theserver 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 beavailable. 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

Page 53: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

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 onlineinclude 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 whilestill 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, let’s 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 aswell, 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 ifpossible. 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 thenscaled 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, alongwith 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 withit 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 veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute <img src="images-audio-video/cows.jpg" alt="Brown and white cows in a grass field"> 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.</p>

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

Page 54: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velitesse 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 isn’t very common. Most often images are set to be displayed as block level elements or floated flush to one side. Using a small image inlinewith 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 fordecoration, 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 thesurrounding 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 velitesse 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 isn’t the ideal usage. You may want the image to appear flush to the left or right while letting all of the other content surround theimage 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

Page 55: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velitesse 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 duiornare 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 imgelement, 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, andpreload.

By default the audio element doesn’t show up on the page. If the Boolean attribute autoplay were passed in, nothing would be shown on the page, however the audio clip wouldautomatically 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

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, whilethe 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 casethat 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, aFlash 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 thesrc 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 audioclip format.

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 willneed 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 isincluded. 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,autoplay, controls, loop, and preload) and fallbacks apply here too.

0:26

Page 56: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

With audio, if the controls Boolean attribute wasn’t specified the audio clip wouldn’t be shown. With videos, not specifying the controls attribute shows the video, howeverdoesn’t 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 reasonnot to allow users to start, stop, or replay the video.

Since videos will be displayed on the page it doesn’t hurt to specify dimensions, most commonly with a fixed height or width in CSS. This helps ensure that the video isn’t too largeand 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 videoto be shown.

<video src="earth.ogv" controls></video>

Adding Video Demo

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 beneeded. 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 videois 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 theEarth video.

<video src="earth.ogv" controls poster="cows.jpg"></video>

Poster Demo

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 ofbuilding 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 videofile 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 videofiles 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

0:00

0:00

Page 57: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

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 ofmedia. 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 orlegibility 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.OperaHTML5 audio & video via Mozilla Developer Networkaudio HTML5 Element via Mozilla Developer NetworkIntroduction to HTML5 Video via Dev.OperaThe figure & figcaption Elements via HTML5 Doctor

Complete! Any questions?

Share

TweetLikeEmail

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.

Page 58: A Beginners Guide to HTML & CSS

1/15/13 Images, Audio, & Video - A Beginner's Guide to HTML & CSS

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

«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 Free

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

Email Address Get Updates

Page 59: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

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 Rank:

A Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 8

Building Forms

In this Lesson 8

HTML

Initializing a FormText Fields & TextareasMultiple Choice Inputs & MenusForm ButtonsOrganizing Form ElementsForm & 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 smallamount of information, often a search query or username and password, or a large amount of information, perhaps shipping andbilling information or a job application.

Knowing how to build forms is necessary to acquire user input. In this lesson we’ll 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 won’t get too deep into howinformation from a form is processed and handled on the backend of a website. Form processing is a deeper topic, outside therealm of this lesson.

Initializing a Form

Page 60: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

To begin a form on a page the form element must be used. The form element signifies where on the page control elements willappear. 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. Theaction attribute is the URI where information included within the form will be sent to be processed by the server. The methodattribute is the HTTP method browsers use to submit the form data. Both of these form attributes revolve around submitting andprocessing 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 arespecifically 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 todetermine 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 asthe name of the control and is submitted along with the input’s 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 hasbrought along a handful of new type attribute values and form updates. These values were added to provide better semanticalcontext around an input as well as help provide better controls for users. Should a browser not understand one of these HTML5type attribute values, it will automatically fall back to the text attribute value. Below is a list of the new HTML5 input types.

colordatedatetimedatetime-localemailmonthnumberrangesearchteltimeurlweek

Page 61: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

Fig. 6.01 The date input type within iOS.

Fig. 6.02 The time input type within iOS.

Page 62: A Beginners Guide to HTML & CSS

1/15/13

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

Fig. 6.03 The email input type within iOS.

Fig. 6.04 The url input type within iOS.

Page 63: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

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 inthat it is for larger passages of text spanning multiple columns. The textarea also has start and end tags which can wrap plaintext. Since the textarea element only accepts one type of value the type attribute doesn’t apply here, however the nameattribute 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 schoolattributes, and in their place the width and height properties within CSS should be used.

Page 64: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

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 formcontrols 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 buttonsonly 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 thesame name attribute value so that all of the buttons correspond to one another. With text inputs the value of the input wasdetermined 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 checkboxas the type attribute value. The difference between the two is that a checkbox allows you to select multiple values and tie them allto 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 thecountry on a page with radio buttons would create a rather cluttered and daunting list. Drop down menus provide the perfectvenue 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 menuoptions 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 beincluded 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 Booleanattribute to preselect an option for users.

<select name="day"> <option value="Friday" selected>Friday</option>

Page 65: A Beginners Guide to HTML & CSS

1/15/13

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

<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 choosemore than one option from the menu. Additionally, using the selected Boolean attribute on more than one option element withinthe 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 formultiple selections. It may also be worth mentioning to users that to choose multiple options they will need to hold down the shiftkey 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

FridaySaturdaySaturday

Form Buttons

After a user inputs the requested information, buttons allow them to put that information into action. Most commonly, a submitbutton 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 typeattribute of either submit or image. The submit attribute value the most common as it is simple to use and provides the mostcontrol. The image attribute value is used specifically to set an image as a submit button, however with the use of CSS the need touse 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

Page 66: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

To take the complete opposite action from submitting a form, users may also reset a form using the reset button. The reset buttoncode 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 andusers. Users may spend quite a bit of time filling out a form only to click the reset button accidentally thinking it was the submitbutton. Chances of a user filling out the form again thereafter are small. Before using a reset button think of any potentialconsequences.

<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 passinghidden 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 trackingcodes, keys, or other information not pertinent to the users but helpful to the website overall. This information is not displayed onthe page, however it could be seen by viewing the source code of a page. That said, it should not be used for sensitive or secureinformation.

To create a hidden input you use the hidden value for the type attribute. Additionally, you pass along the appropriate name andvalue.

<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 shouldlook and doesn’t provide much control to override the default styling. JavaScript and other solutions can be built to allow for fileinput, but they are slightly more difficult to construct.

<input type="file" name="file">

File Input Demo

No file chosenChoose File

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 otherhalf. 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

Page 67: A Beginners Guide to HTML & CSS

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

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

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 bethe same as the value of the id attribute included within the form element the label corresponds to. Matching up the for and idvalues 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 soallows 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 ablock level element that wraps related elements, however specifically within a form for better organization. Fieldsets by defaultalso 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 withinthe fieldset. The HTML code should include the legend directly after the opening fieldset tag. The legend itself willappear on the page within the top left part of the fieldset border. The appearance of the legend on a page may be changedwith 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>

Page 68: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

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 soforth. 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 aredisabled 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 attributehas 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, orurl.

The main difference between the placeholder and value attributes is that the value text stays in place during focus unlessmanually deleted by a user. This is great for pre-populating data, such as personal information for a user, but not for providingsuggestions. 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 anelement or control not have a value an error message will be displayed requesting a user complete the required field. Currentlyerror message styles are controlled by the browser and are unable to be styled with CSS. Elements, on the other hand, can bestyled using the :optional and :required CSS pseudo-classes.

Validation also occurs specific to a control’s type. For example, an input with a type attribute value of email will require thatnot only a value exist within the input, but that it also includes a valid email format.

Page 69: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

<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 theseattributes as necessary.

acceptautocompleteautofocusformactionformenctypeformmethodformnovalidateformtargetmaxmaxlengthminpatternreadonlyselectionDirectionstep

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;

Page 70: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

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 Password

Login Stay signed in

Page 71: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

Resources & Links

Forms via HTML DogForm Element via Mozilla Developer NetworkInput Element via Mozilla Developer NetworkA Form of Madness via Dive Into HTML5Form Examples via Twitter Bootstrap

Complete! Any questions?

Share

TweetLikeEmail

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

«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 anydesigner looking to round out their skills.

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

Page 72: A Beginners Guide to HTML & CSS

1/15/13 Building Forms - A Beginner's Guide to HTML & CSS

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

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

Email Address Get Updates

Page 73: A Beginners Guide to HTML & CSS

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

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 9

Organizing Data with Tables

In this Lesson 9

HTML

Creating a TableTable Structure

CSS

Table BordersAligning TextTable Striping

When HTML was coming to life tables were used all over the place, and were the primary means by which websites werebuilt. They were used for positioning content as well as building the overall layout of a page. Fortunately we have come a longway 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 tablesprovides 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

Page 74: A Beginners Guide to HTML & CSS

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

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

the data and how it is to be displayed. Upon being marked up in HTML, tables need to be stylized with CSS to make theinformation 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 correlateto one another accordingly. In HTML, there are a few different elements needed to make a table. At a minimum a table mustconsist of table, tr, and td elements. To take tables one step further they may include the th element as well. Getting all ofthese 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 willdisplayed in two or more dimensions. The table element is only an initializer and it must encompass a table row, along withtable 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 tablerows, or tr elements. Depending on the amount of information the number of table rows can be substantially high. To adddata 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 mayinclude data. Listing multiple table data elements one after the other will create columns within a table row. When the contentsof a cell is a heading for either a row or column it should be wrapped within the table header element, th, not the table dataelement, 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>

Page 75: A Beginners Guide to HTML & CSS

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

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

<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 TimeMonday, March 5th Indiana Pacers United Center, Chicago, IL 7:00 PMWednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PMThursday, March 8th Orlando Magic United Center, Chicago, IL 7:00 PMSaturday, March 10th Utah Jazz 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 elementworks just like that of the table data element in that it creates a cell for data. The value to using the table header element overthe table data element is that the table header provides a semantic value to table, signifying the data within the cell as aheading. The two elements are comparable to that of a heading, h1, and paragraph, p. While a heading’s content could beplaced within a paragraph tag it doesn’t make sense to do so. Using a heading tag specifically adds more value to the contentand 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 areplaced. To help the headers in noting exactly what content they pertain to the scope attribute is available. The scopeattribute signifies whether a header applies to a row or column with the values row, col, rowgroup, and colgroup. Themost commonly used values are row and col. The row value notes that every cell within the row relates directly to thatheader, 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 thelement. In the case that a cell, either a td or th, needs to be associated with a different header the headers attribute comesinto 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 bethe preferred styling they may be over written in CSS.

<table> <tr> <th scope="col">Date</th> <th scope="col">Opponent</th>

Page 76: A Beginners Guide to HTML & CSS

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

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

<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 Opponent Location Time

Monday, March 5th Indiana Pacers United Center, Chicago, IL 7:00 PMWednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PMThursday, March 8th Orlando Magic United Center, Chicago, IL 7:00 PMSaturday, March 10th Utah Jazz 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 rowand column layout. Perhaps two cells next to each other contain the same data, or the cells need to be combined forstylization purposes. In this case we can use the colspan and rowspan attributes. These two attributes work on either thetable 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 tospan a cell across multiple rows. Each attribute accepts an integer value indicating the number of cells to span across, with 1being the default value.

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

Page 77: A Beginners Guide to HTML & CSS

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

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

<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 Location Time

Monday, March 5th Indiana Pacers United Center, Chicago, IL

7:00 PMWednesday, March 7th Milwaukee Bucks, Bradley Center, Milwaukee, WI

Thursday, March 8th Orlando MagicUnited Center, Chicago, IL

Saturday, March 10th Utah Jazz

Table Structure

Knowing how to build a table and arrange data is extremely powerful, and a skill set necessary for every front-enddeveloper. 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 pertainsto and what they can expect within the table. The caption element must come immediately after the opening table tag. Itsdefault positioning is at the top of the table by default, however may be changed using CSS. Should a table fall within thefigure 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

Chicago Bulls Schedule - Week of March 5thDate Opponent Location Time

Monday, March 5th Indiana Pacers United Center, Chicago, IL 7:00 PMWednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PM

Page 78: A Beginners Guide to HTML & CSS

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

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

Wednesday, March 7th Milwaukee Bucks Bradley Center, Milwaukee, WI 7:00 PMThursday, March 8th Orlando Magic United Center, Chicago, IL 7:00 PMSaturday, 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 atable 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 shouldbe 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 tocome immediately after the thead, however HTML5 has provided leeway here. They may now come in any order so long asthey are never the parent element of one another. Moving forward, the tbody element should contain the primary data withinthe 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, orindividual cells can make a large impact when trying to interpret data and quickly scan for information. When stylizing tableborders with CSS there are two properties that will quickly come in hand, they are the border-collapse and border-spacing properties.

Border Collapse Property

Tables consist of a parent table element as well as subsequent td elements. Applying a border to both of these elementswill begin to stack up borders all around. Take for example, putting a 2 pixel border around an entire table and then anadditional 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-collapseproperty, including collapse, separate, and inherit. By default the value is separate meaning that all of the differentborders will stack up to one another accordingly, like mentioned above. The collapse property, on the other hand, willcondense 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;}

Page 79: A Beginners Guide to HTML & CSS

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

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

}

Border Collapse Property Demo

Luke Brad

88 76

separate

Luke Brad88 76

collapse

Border Spacing Property

Understanding that the border-collapse property with the separate values allows borders to be stacked up against oneanother the border-spacing property can determine how much space, if any, appears between the borders. Going back toour example, a table with a 2 pixel border and a 2 pixel border around each cell creates a 4 pixel border all around. Addingin a border-spacing value of 2 pixels would then separate the two borders by 2 pixels, creating a 6 pixel total borderwidth.

table { border: 2px solid blue; border-collapse: separate; border-spacing: 2px;}th, td { border: 2px solid red;}

Border Spacing Property Demo

Luke Brad88 76

Adding in Borders

Putting a border around a table is fairly simple, however putting borders around rows or cells can be more difficult. Beloware a few examples of how to add these borders. For an additional reference and examples on how to add borders around atable 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 borderof the cells within the last row of the table the pseudo-class last-child selector is used.

table { border-collapse: collapse; border-spacing: 0;

Page 80: A Beginners Guide to HTML & CSS

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

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

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

Row Borders Demo

Track Artist LengthWe Are Young Fun. 4:10Pumped Up Kicks Foster the People 3:59Midnight 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 headeror 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 Artist LengthWe Are Young Fun. 4:10Pumped Up Kicks Foster the People 3:59Midnight 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 text-align 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 andtable-cell display elements. That said, the vertical-align property will not work for block level or any other levelelements.

The vertical-align property accepts a handful of different values, of which change depending on if the element isdisplayed 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.

Page 81: A Beginners Guide to HTML & CSS

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">Don’t 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;}

Page 82: A Beginners Guide to HTML & CSS

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

10/15

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 PriceEnvisioning Information By Edward R. Tufte – Hardcover In Stock 1 $33.32Outliers By Malcolm Gladwell – Hardcover In Stock 2 $33.58 ($16.79 × 2)Don’t Make Me Think By Steve Krug – Paperback Out of Stock 1 $22.80Steve Jobs By Walter Isaacson – Hardcover In Stock 1 $17.49Subtotal $107.19Tax $10.71Total $117.90

Table Striping

Page 83: A Beginners Guide to HTML & CSS

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

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

In the effort to help make tables more legible, one common pattern is to "stripe" the table rows so that they alternatebackground colors. This makes the rows more identifiable and provides a great visual cue for scanning information. One wayto 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 nth-child 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 PriceEnvisioning Information By Edward R. Tufte – Hardcover In Stock 1 $33.32Outliers By Malcolm Gladwell – Hardcover In Stock 2 $33.58 ($16.79 × 2)Don’t Make Me Think By Steve Krug – Paperback Out of Stock 1 $22.80Steve Jobs By Walter Isaacson – Hardcover In Stock 1 $17.49Subtotal $107.19Tax $10.71Total $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>

Page 84: A Beginners Guide to HTML & CSS

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

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

<tr> <td class="item">Don’t 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;

Page 85: A Beginners Guide to HTML & CSS

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

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

}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;}

Page 86: A Beginners Guide to HTML & CSS

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

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

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

Demo

Items Qty PriceEnvisioning Information By Edward R. Tufte – Hardcover In Stock 1 $33.32Outliers By Malcolm Gladwell – Hardcover In Stock 2 $33.58 ($16.79 × 2)Don’t Make Me Think By Steve Krug – Paperback Out of Stock 1 $22.80Steve Jobs By Walter Isaacson – Hardcover In Stock 1 $17.49Subtotal $107.19

Tax $10.71Total $117.90

Resources & Links

HTML Tables via Dev.OperaBring on the Tables via 456 Berra St.Styling Tables via Dev.OperaTable Borders via Twitter Bootstrap

Complete! Any questions?

Share

TweetLikeEmail

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

«Lesson 8 Building Forms«»Lesson 10 Coding Practices & Additional Resources

An Advanced Guide to HTML & CSS

Page 87: A Beginners Guide to HTML & CSS

1/15/13

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

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

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

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

Email Address Get Updates

Page 88: A Beginners Guide to HTML & CSS

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

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

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 Beginner’s Guide to HTML & CSS

Lesson 1 Terminology, Syntax, & IntroductionLesson 2 Elements & SemanticsLesson 3 Box Model & PositioningLesson 4 TypographyLesson 5 Backgrounds & GradientsLesson 6 Unordered, Ordered, & Definition ListsLesson 7 Images, Audio, & VideoLesson 8 Building FormsLesson 9 Organizing Data with TablesLesson 10 Coding Practices & Additional Resources

A Beginner’s 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

Lesson 10

Coding Practices & Additional Resources

In this Lesson 10

HTML

HTML Coding PracticesAdditional Resources

CSS

CSS Coding Practices

There are a lot of different elements, attributes, properties, values, and so forth to learn in order to write HTMLand CSS. Every lesson up until this point has had the primary objective of communicating these different parts ofHTML and CSS, in hopes of helping teach the core fundamentals. This lesson takes a step back and looks at amore abstract picture of HTML and CSS.

Page 89: A Beginners Guide to HTML & CSS

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 applyto 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 openmindset 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 practiceswithin HTML are no different. The goal is to write well structured and standards compliant markup. Theguidelines outlined below provide a brief introduction to HTML coding practices, however this is not anexhausted 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 focusedwhen writing HTML, be sure to nest and close all elements correctly, use IDs and classes accordingly, andalways 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. Decidingwhat elements to use to markup different content can be difficult, yet these elements are the backbone ofsemantics. 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 codefind 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 tobe practical, relating to the content itself, not the style of the content. Using a value of red to describe red text

Page 90: A Beginners Guide to HTML & CSS

isn’t ideal as it describes the presentation of the content. Should the text ever need to be changed to blue, notonly 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 otheraccessibility 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 anythingpertinent the alt attribute should be included, however the value should be left blank so that screen readersignore it rather than read the name of the image file. Additionally, if an image doesn’t 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 valueshould be the name of the page being linked to, not the hypertext being wrapped by the link element. From anaccessibility perspective the hypertext of “click here” doesn’t 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 tomaintain, and an overall headache for users and developers alike. Instead, use external styles, using of IDs andclasses 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 necessarystyles. While this works it begins to add quite a bit of bloat to a page, and before too long you’re not sure whateach 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>

Page 91: A Beginners Guide to HTML & CSS

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

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

<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 oldcode and styles as necessary when editing a page. Also take the time to evaluate code after you write it, lookingfor 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 editingcode nearly impossible. Use comments to build a table of contents at the top of your file, as well as outlineblocks of code throughout the file. Doing so tells others exactly what is contained within the file, whereabout thestyles are located, and exactly what a specific style pertains to. Before sending CSS to the server it is a goodidea 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 previousselector, provides better coordinated code. At a glance you can recognize groups of selectors, helping identifyspecific sets of styles.

footer {...}footer h3 {...}footer .col {...}

section a {...}section strong {...}

Page 92: A Beginners Guide to HTML & CSS

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

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

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 vendorprefixes is worth the generated styles, however they have to be kept organized. Again, keeping with the theme ofwriting code that is easy to read and modify. With vendor prefixes grouping them together and indenting them toalign 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: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;}

Write CSS with Multi-Line Spacing

When writing CSS it is important to write it spanning multiple lines, placing selectors and each style declarationon a new line. Doing so makes the code easy to read as well as edit. When all of the code is piled into one lineit’s harder to scan and make changes. Additionally, if you are looking for the difference between two sets ofcode, 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

Page 93: A Beginners Guide to HTML & CSS

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

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

should be modular and available to be applied to any element as necessary. If a section of news is presentedwithin a box, including a border, background color, and other styles the class of news might sound like a goodoption. However, those same styles may also need to be applied to a section of upcoming events. The class ofnews doesn’t fit in this case. A class of modal would make more sense and may be used across the entirewebsite.

Pump the Brakes

Yes, the best practices around class values from HTML and CSS are a bit conflicting. Use values that pertain tothe content, however naming them in away that they can be reused across the entire website doesn’t quite makesense. The main point here is to really think about what you are using as values and provide values that aremeaningful.

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 buttonstyles. Additionally, if you want a red button, instead of using a class of red you can use the class of btn-danger. 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. Thesevalues should be named in such a way that they resemble the CSS language. In such, class names should be alllowercase, 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 astoo long fairly easily. For the longest time we’ve been told not to use classes and to use element selectors asmuch as possible. Regrettably, this isn’t true.

Page 94: A Beginners Guide to HTML & CSS

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

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

The longer a selector is, chaining multiple elements together, the more work the browser has to do in checking tomake sure each selector matches before applying a style. Doing so creates a large performance hit, slowingdown 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 emphasizedtext is nested within a heading inside of an aside the selector might look something like aside h1 em. Shouldthe emphasized text ever be moved out of the heading the styles will no longer apply. A better, more flexibleselector 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 aperformance lag and is strenuous to manage. In this case a class is advised. While applying a class to the targetedelement 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 acceptableshorthand property or value. As an example, rather than using four different sets of properties and values todeclare a margin one single property can be used. Additionally, one margin property can be used to set the fourvalues in a couple of different ways. All four value can be declared individually in a clockwise order, two valuescan be declared by combining the top/bottom and left/right values, or by declaring one value for all four sides ofan 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, thebottom-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 {

Page 95: A Beginners Guide to HTML & CSS

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

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

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. Outlinedbelow is a longer list of resources, as well as beneficial links. Many of these resources have helped in preparingthe guide while others are simply nice to know.

HTML & CSS

Mozilla Developer Network via MozillaThe Web Standards Curriculum via Opera.Dev30 Days to Learn HTML & CSS via Tuts+HTML and CSS Tutorials via HTML DogDocHub — Instant documentation searchPears — Common patterns of markup and style

Design Inspiration

DribbblePattern TapPremium PixelsLaunched Pixels

Frameworks & Styleguides

Web Style GuideBootstrap, from TwitterSkeleton FrameworkStarbucks Styleguide

Page 96: A Beginners Guide to HTML & CSS

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

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

GitHub StyleguideGlobal Experience Language for the BBCWordPress.org UI Styleguide

Icons

Fugue Icons via Yusuke Kamiyamanefamfamfam Icons via Mark JamesSocial Network Icon Pack via Rogie King

Miscellaneous

960 Gridder — Easily align and lay out websitesResponsive.is — Display responsive web designsW3Clove — Validate an entire sites HTML markupFontFuse — Find and create cool font pairingsCOLOURlovers — Color trends and palettesColorHexa — Color encyclopediaModernizr — JavaScript feature detection libraryjQuery Tools — jQuery user interface components

Complete! Any questions?

Share

TweetLikeEmail

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

«Lesson 9 Organizing Data with Tables«

An Advanced Guide to HTML & CSS

Page 97: A Beginners Guide to HTML & CSS

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

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

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

View the Advanced Guide to HTML & CSS

Join the Newsletter

SPAM Free

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

Email Address Get Updates