Go to www.wiley.com/go/eula to access Wiley’s ebook EULA.
Table of Contents
Cover
Chapter 1: Structuring Documents for the Web
A Web of Structured Documents
Introducing HTML5
Attribute Groups
Core Elements
Basic Text Formatting
Understanding Block and Inline Elements
Grouping Content
Working with Lists
Summary
Chapter 2: Fine-tuning Your Text
Elements That Describe Text-Level Semantics
Editing Text
Using Character Entities for Special Characters
Comments
Summary
Chapter 3: Links and Navigation
Basic Links
Understanding Directories and Directory Structures
Understanding URLs
Creating In-Page Links with the <a> Element
Advanced E-mail Links
Summary
Chapter 4: Images, Audio, and Video
Adding Images Using the <img> Element
Using Images as Links
Choosing the Right Image Format
Adding Flash, Video, and Audio to Your Web Pages
Summary
Chapter 5: Tables
Introducing Tables
Basic Table Elements and Attributes
Adding a Caption to a Table
Grouping Sections of a Table
Nested Tables
Accessible Tables
Summary
Chapter 6: Forms
Introducing Forms
Creating a Form with the <form> Element
Form Controls
Creating a Contact Form
Creating Labels for Controls and the <label> Element
Structuring Your Forms with <fieldset> and <legend> Elements
Focus
Disabled and Read-Only Controls
Sending Form Data to the Server
Creating More Usable Form Fields
Summary
Chapter 7: Cascading Style Sheets
Introducing CSS
Where You Can Add CSS Rules
CSS Properties
Controlling Text
Text Formatting
Text Pseudo-Classes
Styling Text
Selectors
Lengths
Introducing the Box Model
Creating a Style Sheet for Code
Summary
Chapter 8: More Cascading Style Sheets
Links
Backgrounds
Lists
Tables
Outlines
The :focus and :active Pseudo-Classes
Generated Content
Miscellaneous Properties
Additional Rules
Positioning and Layout with CSS
Summary
Chapter 9: Rounded Corners, Animations, Custom Fonts, and More with CSS3
The Modular Approach of CSS3
Mature CSS3 Modules
New and In-Development Modules
Summary
Chapter 10: Learning JavaScript
What Is Programming About?
How to Add a Script to Your Pages
Create an External JavaScript
The Document Object Model
Starting to Program with JavaScript
Variables
Operators
Functions
Conditional Statements
Looping
Events
Built-in Objects
Writing JavaScript
Summary
Chapter 11: Working with jQuery
Why jQuery?
Adding jQuery to Your Page
jQuery Basics
jQuery and the DOM
Managing Events with jQuery
Summary
Chapter 12: jQuery: Beyond the Basics
Ajax with jQuery
jQuery UI
Summary
Chapter 13: Checklists
Search Engine Optimization Checklist
Accessibility Checklist
Appendix A: Answers to Exercises
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Appendix B: HTML Element Reference
Appendix C: CSS Properties
Font Properties
Text Properties
Color and Background Properties
Border Properties
Dimensions
Margin Properties
Padding Properties
List Properties
Positioning Properties
Outline Properties
Table Properties
Classification Properties
Internationalization Properties
Selected CSS3 Properties
Lengths
Appendix D: Color Names and Values
Using Hex Codes to Specify Colors
Understanding Hex Codes
Using Color Names to Specify Colors
Color Name and Number Reference
Appendix E: Character Encodings
Appendix F: Special Characters
Character Entity References for ISO 8859-1 Characters
Character Entity References for Symbols, Mathematical Symbols, and Greek Letters
Character Entity References for Markup-Significant and Internationalization Characters
Appendix G: Language Codes
Appendix H: MIME Media Types
Text
Image
Multipart
Audio
Video
Message
Model
Application
Appendix I: Changes between HTML4 and HTML5
New Elements
New <input> Element Types
New Attributes
Global Attributes
Changed Attributes
Obsolete Elements
Obsolete Attributes
At-Risk Elements
About the Author
Credits
Acknowledgments
Introduction
EULA
Beginning HTML & CSS
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-34018-9
ISBN: 978-1-118-34028-8 (ebk)
ISBN: 978-1-118-41651-8 (ebk)
ISBN: 978-1-118-65351-7 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2012954405
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
For Jo & Ingmar. I’ll take good care of Jude.
Rob Larsen has more than 13 years of experience as a front-end engineer and team lead, building websites and applications for some of the world’s biggest brands.
He is an active writer and speaker on web technology with a special focus on emerging standards like HTML5, CSS3, and the ongoing evolution of the JavaScript programming language. He is co-author of Professional jQuery (Wrox). He’s also active in the open source community, helping to bridge the gap between the front lines of web development and the people actively working on the tools that drive the web.
In his career Rob has spent time at Sapient Global Markets, Isobar, The Brand Experience, and Cramer and as an independent consultant. Over the years, he has solved unique problems for clients such as Samsung, Adidas, Motorola, Philips, Reebok, Gillette, Boston’s Museum of Science, and Harvard Kennedy School.
(Photo by Ricardo Salema: www.ricardosalema.com)
Executive Editor
Carol Long
Project Editor
Katherine Burt
Technical Editor
Dan Maharry
Production Editor
Daniel Scribner
Copy Editor
San Dee Phillips
Editorial Manager
Mary Beth Wakefield
Freelancer Editorial Manager
Rosemarie Graham
Associate Director of Marketing
David Mayhew
Marketing Manager
Ashley Zurcher
Business Manager
Amy Knies
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Neil Edde
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Katie Crocker
Compositor
Craig Woods, Happenstance Type-O-Rama
Proofreader
Nicole Hirschman
Indexer
Robert Swanson
Cover Designer
Elizabeth Brooks
Cover Image
©Aliaksandr Zabudzko/iStockphoto
I’d like to thank Carol Long and the rest of the folks at Wiley for giving me this opportunity. Without it, I probably would have spent half the summer playing video games.
I have to thank Katherine Burt a million times over for her patience and assistance in getting this slow-to-start monster up to speed.
Dan Maharry’s technical insight has been invaluable—teaching me a thing or two every chapter and asking the right questions throughout the process. It’s a much better book for his involvement.
At the pace I wrote some of this I’d be nuts not to thank our copy editor, San Dee Phillips. I should have apologized in advance.
I’d also like to thank Lynn Haller from Studio B for her ongoing help in navigating the business side of book writing.
I’ve got to give a big shout-out to John Duckett—standing on the shoulders of giants and all that.
As always, I want to thank all the great front-end engineers I’ve worked with at Cramer, Isobar, and Sapient for pushing me to be a better programmer, manager, and colleague.
Finally, I’d like to thank my wife for her support and understanding throughout this process. I couldn’t have done it without her.
There are a lot of books about building web pages, so thank you for picking up this one. I’ve spent the last 13 years building websites, so hopefully I’ve picked up a thing or two that I can share with you to make your purchase worthwhile.
If you’re just starting out with building web pages, you’ve picked a great time to get started. The way web pages are built is changing right now in a big way. While the same basic technologies we’ve used for the last 15–20 years are still in place, there are new versions available that have people like me very excited for the future of the web.
This book presents a practical introduction to the process of making websites using a blend of the latest and greatest techniques, as well as a healthy understanding of some older technologies that have been around for a while. The techniques described in this book are informed by having solved real-world problems; so, although it has an eye toward the future it’s grounded in the act of making websites today.
You will learn a few different languages to create effective and attractive web pages:
As you have already seen, you’ll learn how to control the structure of a web page using HTML, how to style it using CSS, and how to add interactivity using JavaScript and jQuery. Learning how this code works will give you a solid foundation for building websites, and alongside this you will see plenty of practical advice that helps you learn about issues you are likely to meet when you start building sites.
While learning how to code, you will see lots of advice on usability—how to build websites that are easy to use and enable visitors to achieve what they came for. In several parts of the book, I also discuss issues regarding accessibility—making a site available to as many users as possible (in particular, people with disabilities, who may have impaired vision or difficulty using a mouse). In the same way that many countries have laws requiring architects to design buildings that are accessible, there are strict accessibility guidelines for building websites to ensure they do not exclude visitors. A little careful thought before you build your website means that people with vision impairments can either view your site with larger text or have it read to them by a piece of software called a screen reader. Whole books are dedicated to the topics of usability and accessibility and are aimed at web developers who need to learn how to make their code more accessible and usable. My aim is to teach you to code with these principles in mind from the start.
Although it is important to learn the latest practices for creating web pages using these languages, if you intend to create websites that anyone can access, you will also have to learn some older aspects of the languages you meet. This is important because not everyone has the latest web browser installed on his or her computer; as a result, the latest features may not work for everyone, and in such cases you need to learn techniques that will work in some older browsers that are still popular today.
By the end of this book, you will be writing web pages that not only use the latest technologies but also are still viewable by older browsers—pages that look great and can also be accessed by those with visual and physical impairments. These are pages that not only address the needs of today’s audiences but can also work on emerging technologies—and therefore the skills you will learn should be relevant longer.
This book is written for anyone who wants to learn how to create web pages, and for people who may have dabbled in writing web pages (perhaps using some kind of web page authoring tool), but who want to really understand the languages of the web, to give them more control over the pages they create.
More experienced web developers can also benefit from this book because it teaches some of the latest technologies and encourages them to embrace web standards that not only meet the needs of the new devices that access the web but also help make their sites available to more visitors.
You don’t need any previous programming experience to work with this book. This is one of the first steps on the programming ladder. Whether you are just a hobbyist or want to make a career of web programming, this book will teach you the basics of programming for the web.
By the end of this book, you will be able to create professional-looking and well-coded web pages.
Not only will you learn the code that makes up HTML, but you will also see how to apply this code so you can create sophisticated layouts for your pages, positioning text and images where you would like them to appear and getting the colors and fonts you want. Along the way, you will see how to make your pages easy to use and available to the biggest audience possible.
The main technologies covered in this book are HTML and CSS. You will also learn the basics of JavaScript—enough to work on some examples that add interactivity to your pages and enable you to work with jQuery.
The code I encourage you to write is based on what are known as web standards; HTML and CSS are all created and maintained by the World Wide Web Consortium, or W3C (www.w3.org/), an organization dedicated to the development of the web. You will also learn about some features that are not in these standards; it is helpful to know about some of these in case you come across such markup and need to know what it does. Where these are introduced, I make it clear they are not part of the standard.
All you need to work through this book is a computer with a web browser (preferably the latest version of Firefox, Chrome, or Internet Explorer 9 or higher), and a simple text editor such as Notepad or Sublime Text on Windows or TextEdit or Sublime Text on Mac.
The first chapter of this book will show you that the main task in creating a website is marking up the text you want to appear on your site, using elements and attributes. As you will see, these elements and attributes describe the structure of a document (what is a heading, what is a paragraph of text, what is a link, and so on).
The first six chapters of the book describe the different elements and attributes that make up HTML and how you can use them to write web pages. These chapters are organized into task-related areas, such as structuring a document into headings and paragraphs; creating links between pages; adding images, audio, and video; and displaying tables. With each task or topic that is introduced, you will see an example first to give you an idea of what is possible; then you can look at the elements and attributes used in detail.
When you first read this book, you do not need to closely read the detailed explanations of every single element. As long as you understand the gist of the markup, feel free to move on, and then come back and look at the finer detail when you need it.
Each chapter ends with exercises designed to get you working with the concepts you’ve just learned. Don’t worry if you have to go back and review the content of the chapter in order to complete the exercises; this book has been created with the intention that it should be a helpful reference for years to come, so don’t feel that you need to learn everything by heart. Along the way, you’ll see which browsers support each element and you’ll learn plenty of handy tips, tricks, and techniques for creating professional web pages.
Once you have seen how to create and structure a document using HTML, Chapters 7, 8, and 9 will show you how to make your pages look more attractive using CSS. For example, you’ll learn how to change the typefaces and size of fonts, color of text, backgrounds, and borders that go around items. In addition, you’ll learn how to control where items appear on the page, which will enable you to create attractive layouts.
Having worked through the three chapters on CSS, and using the examples in the book, you should be able to write quite complex web pages. The chapters up to that point can then act as a helpful reference you can keep coming back to, and the examples will act as a toolkit for building your own sites.
Chapter 10 introduces you to JavaScript, a programming language that enables you to add interactivity to your pages. While the entire JavaScript language is too large to teach you in one chapter, you will learn how to create your own basic scripts and also how to integrate scripts other people have written into your pages.
Chapters 11 and 12 introduce you to jQuery, a library that helps you code JavaScript more easily. jQuery is by far the most popular library for working with JavaScript. It’s easy to use and fun, and it lies at the center of a vast ecosystem of scripts that you can use to enhance your own site.
The final chapter, Chapter 13, includes some checklists. These bring together some topics that are dotted throughout the book.
I have also included several helpful appendices, including a reference to HTML elements and CSS properties. There is an appendix that explains how HTML and CSS specify colors. Other appendices show you available character encodings, language codes, and escape characters that can be used with HTML, XHTML, CSS, and JavaScript. Finally, there is an appendix that outlines the major differences between the last two major versions of HTML.
To help you get the most from the text and keep track of what’s happening, I’ve used a number of conventions throughout the book.
As for styles in the text:
We use a monofont type with no highlighting for most code examples.
We use bolding to emphasize code that’s particularly important in the present context.
As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Specifically for this book, the code download is on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=9781118340189. You can also search for the book at www.wrox.com by ISBN (the ISBN for this book is to find the code.
Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
I’ve made every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in this book, such as a spelling mistake or faulty piece of code, I would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration, and at the same time you will be helping to provide even higher quality information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors.
If you don’t spot “your” error on the Errata page, click the Errata Form link and complete the form to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book but also as you develop your own applications. To join the forums, just follow these steps:
Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.
What You Will Learn in This Chapter
Wrox.com Code Downloads for this Chapter
The wrox.com code downloads for this chapter are found at www.wrox.com/remtitle.cgi?isbn=9781118340189 on the Download Code tab. The code is in the Chapter 1 download and individually named according to the names throughout the chapter.
In this chapter, you learn the key concept to create any web page: how to give it structure. You need to add structure to a document so that web browsers can present the page to people who visit your site in a way they can understand. For example, imagine a news article that contains a headline (or title) and several paragraphs of text; if you want to put this article on the web, you would need to add structure to the words in the document so that the browser knows which words are the headline, and where each paragraph starts and ends. To give a document structure, you need to learn how to create web pages using HTML.
Every day, you come across all kinds of printed documents—newspapers, train timetables, and insurance forms. You can think of the web as being a sea of documents that all link together and bear a strong similarity to the printed documents that you meet in everyday life.
Take the example of a newspaper. A newspaper consists of several stories or articles (and probably a fair smattering of advertisements, too). Each story has a headline and then some paragraphs, perhaps a subheading, and then some more paragraphs; it may also include a picture or two.
The structure of articles on news websites is similar to the structure of articles in newspapers. Each article consists of headings, paragraphs of text, and some pictures. (Sometimes the pictures might be replaced by a video.) The parallel is quite clear; the only difference is that in a newspaper you may have several stories on a single page, whereas on the web each story tends to get its own page. The news websites also often use homepages that display the headline and a brief summary of the stories.
Consider another example: You’re catching a train to see a friend, so you check the schedule or timetable to see what time the train leaves. The main part of the schedule is a table telling you what times trains arrive and when they depart from different stations. You can probably think of several types of documents that use tables. From the listings in the financial supplement of your paper to the TV schedule, you come across tables of information every day—and often when this information is put on the web, these tables are re-created.
Another common type of printed document is a form. For example, think about a common form from an insurance company. Such a form contains fields to write your name, address, and the amount of coverage, along with check boxes to indicate the number of rooms in the house and what type of lock is on the front door. There are lots of forms on the web, from simple search boxes that ask what you are looking for to the registration forms you are required to fill out before you can place an online order for books or CDs.
As you can see, there are many parallels between the structure of printed documents you come across every day and pages you see on the web. When you are writing web pages, it is the HTML code you start learning in this chapter that tells the web browser how the information you want to display is structured—what text to put in a heading, paragraph, or table, and so on so that the browser can present it properly to the user.
Even if you have never seen any HyperText Markup Language (HTML) code, you may know that it is used to create web pages. There have been five versions of HTML since the web began, and the development of the language is overseen by an organization called the World Wide Web Consortium (W3C).
This book focuses on the latest version of the language, popularly referred to as HTML5. There are two other versions you might encounter. These are HTML 4.01, the last major version of the language from December 1999, and a stricter version from 2000 called Extensible HyperText Markup Language (XHTML). XHTML is still popular in some applications, so important differences between it and HTML5 will be called out in the text.
As its name suggests, HTML is a markup language, which may sound complicated until you realize that you come across markup every day. When creating a document in a word processor, you can add styles to the text to explain the document’s structure. For example, you can distinguish headings from the main body of the text using a heading style (usually with a larger font). You can use the Return (or Enter) key to start a new paragraph. You can insert tables into your document to hold data or create bulleted lists for a series of related points, and so on. Although this does affect the presentation of the document, the key purpose of this kind of markup is to provide a structure that makes the document easier to understand.
When marking up documents for the web, you perform a similar process, except you do it by adding things called tags to the text. With HTML, the key thing to remember is that you must add the tags to indicate the structure of the document (not how you want it to be presented); for example, which part of the document is a heading, which parts are paragraphs, what belongs in a table, and so on. Browsers such as Internet Explorer, Firefox, and Google Chrome all use this markup to help present the text in a familiar fashion, similar to that of a word processor—main headings are bigger than the text in paragraphs, there is space above and below each paragraph, and lists of bullet points have a circle in front of them.
Now have a look at a simple web page (ch01_eg01.html). You don’t need any special programs to write web pages; you can simply use a text editor such as Notepad on Windows or TextEdit on a Mac and save your files with the .html or .htm file extension.
<html>
<head>
<title>Popular Websites: Google</title>
</head>
<body>
<h1>About Google</h1>
<p>Google is best known for its search engine, although
Google now offers a number of other services.</p>
<p>Google's mission is to organize the world's
information and make it universally accessible and
useful.</p>
<p>Its founders Larry Page and Sergey Brin started
Google at Stanford University.</p>
</body>
</html>
This may look a bit confusing at first, but it will all make sense soon. As you can see, there are several sets of angle brackets with words or letters between them, such as <html>, <head>, </title>, and </body>. These angle brackets and the words inside them are known as tags, and these are the markup previously mentioned. Figure 1-1 illustrates what this page would look like in a web browser.
As you can see, this document contains the heading “About Google” and a paragraph of text to introduce the company. Note also that it says “Popular Websites: Google” in the top-left corner of the browser window; this is known as the title of the page (to the right it says Mozilla Firefox, which is the browser this page was opened in).
To understand the markup in this first example, you need to look at what is written between the angle brackets and compare that with what you see in the figure, which is what you do next.
If you look at the first and last lines of the code for the previous example, you see pairs of angle brackets containing the letters “html”. Starting on the first line, the first angled bracket looks like a less-than sign (<); then there are the letters “html,” followed by a second angled bracket, which looks like a greater-than sign (>). The two brackets and all the characters between them are known as a tag.
In this example, there are lots of tags, and they are all in pairs; there are opening tags and closing tags. The closing tag is always slightly different from the opening tag in that it has a forward slash (/) after the first angled bracket: </html>.
A pair of tags and the content these include are known as an element. In Figure 1-2, you see the heading for the page of the previous example.
The opening tag says, “This is the beginning of a heading” and the closing tag says, “This is the end of a heading.” Like most tags in HTML, the text inside the angled brackets explains the purpose of the tag—here h1 indicates that it is a level 1 heading (or top-level heading). As you will see shortly, there are also tags for subheadings (<h2>, <h3>, <h4>, <h5>, and <h6>). If you don’t put tags around the words “About Google,” it is just another bit of text; it would not be clear that these words formed the heading.
Now look at the three paragraphs of text about the company; each one is placed between an opening <p> tag and a closing </p> tag. And you guessed it, the p stands for paragraph.
As you can see, the tags throughout this example actually describe what you will find between them, creating the structure of the document. The text between the <h1> and </h1> tags is a heading, and the text between the opening <p> and closing </p> tags makes up paragraphs. Indeed, the whole document is contained between opening <html> and closing </html> tags.
You often find that terms from a family tree are used to describe the relationships between elements. For example, an element that contains another element is known as the parent, whereas the element that’s between the parent element’s opening and closing tags is called a child of that element. So, the <title> element is a child of the <head> element, the <head> element is the parent of the <title> element, and so on. Furthermore, the <title> element can be thought of as a grandchild of the <html> element.
Additionally, if two elements are children of the same parent, they are referred to as siblings.
It is worth noting that the tags in this example are all in lowercase characters; you sometimes see web pages written in HTML where tags are uppercase (or a mix of uppercase and lowercase letters). When XHTML was introduced, with its stricter rules, it stated that all tags were written in lowercase. Technically, HTML5 loosens these restrictions to enable mixed case. In practice you generally see lowercase even in HTML5 documents.
Whenever you write a web page in HTML, the whole of the page is contained between the opening <html> and closing </html> tags, just as it was in the previous example. Inside the <html> element, there are two main parts to the page:
Together, the <html>, <head>, and <body> elements make up the skeleton of an HTML document—they are the foundation upon which every web page is built.
Inside the <head> element of the first example page, you see a <title> element:
<head>
<title>Popular Websites: Google</title>
</head>
Between the opening <title> tag and the closing </title> tag are the words “Popular Websites: Google,” or the title of this web page. Figure 1-1 shows the words at the top of the browser window, which is where browsers such as Internet Explorer, Firefox, and Chrome display the title of a document. It is also the name they use when you save a page in your Favorites List, and it helps search engines understand what your page is about. The <title> element is mandatory for all web pages.
The real content of your page is held in the <body> element, which is what you want users to read, and this is shown in the main browser window.
You may have noticed that the tags in this example appear in a symmetrical order. If you want to have one element inside another, both the element’s opening and closing tags must be inside the containing element. For example, the following is allowed:
<p> This paragraph contains some <em>emphasized text.</em></p>
whereas the following is wrong because the closing </em> tag is not inside the paragraph element:
<p> This paragraph contains some <em>emphasized text. </p></em>
In other words, if an element is to contain another element, it must wholly contain that element. This is referred to as nesting your elements correctly.
Attributes in HTML are much like the attributes you experience every day. They are the qualities that describe a person or thing, such as a tall man or a brown dog. Similarly, HTML elements can be described in ways that web browsers can understand. This section looks at attributes, starting with the most important one that beats at the heart of the web.
What differentiates web documents from standard documents are the links (or hyperlinks) that take you from one web page to another. Look at a link by adding one to the example you just looked at. Links are created using an <a> element. (The a stands for anchor.)
You can add a link from this page to Google in a new paragraph at the end of the document. There is just one new line in this example (ch01_eg02.html) and that line is highlighted:
<html>
<head>
<title>Popular Websites: Google</title>
</head>
<body>
<h1>About Google</h1>
<p>Google is best known for its search engine, although Google now offers a
number of other services.</p>
<p>Google's mission is to organize the world's information and make it
universally accessible and useful.</p>
<p>Its founders Larry Page and Sergey Brin started Google at Stanford
University.</p>
<p><a href="http://www.Google.com/">Click here to visit Google's Web
site.</a></p>
</body>
</html>
Inside this new paragraph is the <a> element that creates the link. Between the opening <a> tag and the closing </a> tag is the text that you can click, which says, “Click here to visit Google’s Web site.” Figure 1-3 shows you what this page looks like in a browser.
If you look closely at the opening tag of the link, it carries something called an attribute. In this case, it’s the href attribute; this is followed by an equal sign and then a pair of quotation marks, which contain the URL for Google’s website. In this case, the href attribute tells you where the link should take you. You look at links in greater detail in the Chapter 3, “Links and Navigation,” but for the moment this illustrates the purpose of attributes.
The value of the attribute should always be put in double quotation marks and separated from the name with the equal sign.
There are several attributes in HTML5 that do not consist of a name/value pair but consist of just a name. These are called boolean attributes and you will learn more about those in the section “Attribute Groups.”
Another common attribute on anchors is the title attribute, which gives a plain language description of the target of the link. You could add one to the example to inform people that Google is a popular search engine.
<a href="http://www.Google.com"
title="Google.com is the world's most popular search engine">
This illustrates that elements can carry several attributes; although, an element should never have two attributes of the same name.
When HTML first came out, a lot of people learned how to create pages by using a handy feature that you can find in most common browsers: the ability to look at the source code that made the page.
If you go to the View menu in your browser and then look for an option that says View Source or Page Source, you should see the code that created the page.
If you want to see how the author of a page achieved something on a page, this can be a handy technique. Figure 1-4 shows how to look at the source of the author’s homepage. (The window on the right contains the source for the page.)
You now know that an HTML page (also sometimes referred to as an HTML document) consists of elements that describe how its content is structured. Each element describes what you will find between its opening and closing tags. The opening tags can also carry attributes that tell you more about that particular element.
Equipped with this knowledge, you can find that much of learning HTML is a matter of learning what elements you can use, what each of these elements does, and what attributes each can carry.
As you have seen, attributes live on the opening tag of an element and provide extra information about the element that carries them. Many attributes consist of a name and a value; the name reflects a property of the element the attribute describes, and the value is a value for that property. For example, the lang attribute describes the language used within that element; a value such as EN-US would indicate that the language used inside the element is U.S. English.
Some attributes consist of only a name, such as required or checked. These are called boolean attributes. To say something is a boolean (which you learn more about in Chapter 10, “Learning JavaScript”) is to indicate that it can be in one of two states: true or false. For HTML attributes the presence of one of the boolean attributes in a tag indicates that the value is true. So, the following are equivalent:
<input type="text" required >
<input type="text" required="true">
Many of the elements in HTML can carry some or all the attributes you will meet in this section. At first some of them may sound a little abstract; although, they will make more sense as you see them used throughout the book. So don’t worry if they do not make much sense at first.
In this section, you look at three groups of attributes common to many HTML elements:
The four core attributes that you can use on the majority of HTML elements (although not all) are:
id title class style
Throughout the rest of the book, these attributes are revisited when they have special meaning for an element that differs from the description given here; otherwise their use can generally be described as you see in the subsections that follow.
You can use the id attribute to uniquely identify any element within a page. You might want to uniquely identify an element so that you can link to that specific part in the document or to specify that a CSS style or piece of JavaScript should apply to the content of just that one element within the document.
The syntax for the id attribute is as follows (where string is your chosen value for the attribute):
id="string"
For example, you can use the id attribute to distinguish between two paragraph elements, like so:
<p id="accounts">This paragraph explains the role of the accounts department.</p>
<p id="sales">This paragraph explains the role of the sales department.</p>
Following are some special rules for the value of the id attribute:
You can use the class attribute to specify that an element belongs to a class of elements. For example, you might have a document that contains many paragraphs, and a few of those paragraphs might contain a summary of key points, in which case you could add a class attribute whose value is summary to the relevant <p> elements to differentiate those paragraphs from the rest in the document.
<p class="summary">Summary goes here</p>
It is commonly used with CSS, so you learn more about the use of the class attribute in Chapter 7, which introduces CSS. The syntax of the class attribute is as follows:
class="className"
The value of the attribute may also be a space-separated list of class names, for example:
class="className1 className2 className3"
The title attribute gives a suggested title for the element. The syntax for the title attribute is as follows:
title="string"
The behavior of this attribute depends upon the element that carries it; although, it is often displayed as a tooltip or while the element loads. Not every element that can carry a title attribute actually needs one, so when you meet an element that particularly benefits from use of this attribute, you will see the behavior it has when used with that element.
The style attribute enables you to specify CSS rules within the element. You meet CSS in Chapter 7, but for now, here is an example of how it might be used:
<p style="font-family:arial; color:#Fc00f000;">Some text.</p>
As a general rule, however, it is best to avoid the use of this attribute. If you want to use CSS rules to govern how an element appears, it is better to use a separate style sheet instead. The only place where this attribute is still commonly used is when it is set with JavaScript. You learn more about that in Chapter 11, “Working with jQuery,” when you’re introduced to jQuery’s powerful tools for manipulating HTML elements.
The web is a worldwide phenomenon. Because of this, there are mechanisms built into the tools that drive the web that allow authors to create documents in different languages. This process is called internationalization.
Two common internationalization attributes help users write pages for different languages and character sets:
dir lang
You look at each next, but it is worth noting that even in current browsers, support for these attributes is still patchy. Therefore where possible you should specify a character set that creates text in the direction you require.
The website of a helpful W3C document that describes internationalization issues in greater detail is found at www.w3.org/TR/i18n-html-tech-char/