Sams Teach Yourself HTML And CSS In 24 Hours, Eighth Edition

Transcription

Sams Teach Yourself HTML and CSS in 24 Hours, Eighth EditionCopyright 2010 by Sams PublishingAll rights reserved. No part of this book shall be reproduced, stored in a retrieval system,or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed withrespect to the use of the information contained herein. Although every precaution hasbeen taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from theuse of the information contained herein.International Standard Book Number: 0-672-33097-0Library of Congress Cataloging-in-Publication DataMeloni, Julie C.Sams teach yourself HTML and CSS 24 hours / Julie Meloni, MichaelMorrison. -- 8th ed.p. cm.Rev. ed. of: Sams teach yourself HTML and CSS in 24 hours / DickOliver, 7th ed., 2006.ISBN 978-0-672-33097-1 (pbk.)1. HTML (Document markup language) 2. XHTML (Document markuplanguage) 3. Cascading style sheets. I. Morrison, Michael, 1970- II.Oliver, Dick. Sams teach yourself HTML and CSS in 24 hours. III. Title.QA76.76.H94O4526 2010006.7'4--dc222009046100Printed in the United States of AmericaFirst Printing: December 2009TrademarksAll terms mentioned in this book that are known to be trademarks or service marks havebeen appropriately capitalized. Sams Publishing cannot attest to the accuracy of thisinformation. Use of a term in this book should not be regarded as affecting the validity ofany trademark or service mark.Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate as possible,but no warranty or fitness is implied. The information provided is on an “as is” basis. Theauthor and the publisher shall have neither liability nor responsibility to any person orentity with respect to any loss or damages arising from the information contained in thisbook or from the use of the CD or programs accompanying it.Bulk SalesSams Publishing offers excellent discounts on this book when ordered in quantity for bulkpurchases or special sales. For more information, please contactU.S. Corporate and Government or sales outside of the U.S., please contactInternational Salesinternational@pearson.comAcquisitions EditorMark TaberDevelopment EditorMichael ThurstonManaging EditorPatrick KanouseProject EditorJennifer GallantIndexerKen JohnsonProofreaderDan KnottTechnical EditorWilliam WolffPublishing CoordinatorVanessa EvansCompositionMark ShirarBook DesignerGary Adair

viiIntroductionIn 2009, it is estimated that more than 1.5 billion people have access to the Internet, including220 million in the U.S. alone. Throw in 338 million Chinese users, 55 million German users, 48million British users, 38 million Russian users, and 67 million Brazilians, and you can see themeaning of the word “world” in the term World Wide Web. Many of these Internet users are alsocreating content for the Web—you can be one of them! Although accurate measurements of thetotal number of web pages are difficult to come by, Google’s most recent data indicates they hitthe 1 trillion mark of indexed pages in the middle of 2008.In the next 24 hours, hundreds of millions of new pages will appear in accessible areas of theInternet. At least as many pages will be placed on private intranets, where they will be viewed bybusinesspeople connected via their local networks. Every one of those pages—like the more than1 trillion pages already online—will use Hypertext Markup Language (HTML).As you complete the 24 one-hour lessons in this book, your web pages will be among those thatappear on the Internet. These lessons will also help you develop one of the most valuable skills inthe world today: mastery of HTML.Can you really learn to create top-quality web pages yourself, without any specialized software, inless time than it takes to schedule and wait for an appointment with a highly paid HTML wizard?Can this relatively short, easy-to-read book really enable you to teach yourself state-of-the-art webpage publishing?Yes. In fact, within the first two lessons in this book, someone with no previous HTML experienceat all can have a web page ready to place on the web.How can you learn the language of the Web so fast? By example. This book organizes HTML intosimple steps and then shows you exactly how to tackle each step. Every HTML code example islisted directly before a picture of the web page it produces. You see how it’s done, you read aclear, concise explanation of how it works, and then you immediately do the same thing with yourown page. Ten minutes later, you’re on to the next step.After 24 hours of work, you’re marveling at your own impressive pages on the Internet.Beyond HTMLThis book covers more than just HTML because HTML isn’t the only thing you need to know to create web content today. The goal of this book is to give you all the skills you need to create a modern, standards-compliant web site in just 24 short, easy lessons. This book covers the followingkey skills and technologies:. XHTML (eXstensible Hypertext Markup Language) is the current standard for web page creation. Every example in this book is fully XHTML-compatible. Where applicable, HTML 5 isalso covered.

viii. All the examples in the book have been tested for compatibility with the latest version ofevery major web browser. That includes Apple Safari, Google Chrome, Microsoft InternetExplorer, Mozilla Firefox, and Opera. You’ll learn from the start to be compatible with thepast, yet ready for the future. There is extensive coverage of Cascading Style Sheets (CSS), which allows you to carefullycontrol the layout, fonts, colors, and formatting of every aspect of your web pages, includingboth text and images. When it comes to creating eye-popping web pages, CSS goes farbeyond what traditional HTML pages could do by themselves. For example, did you know thatCSS allows you to specifically tailor the information on a page just for printing, in addition tonormal web viewing?. Hours 10 through 12 introduce you to multimedia applications and their use, including whereto find industry-standard software you can download and try free. The technical stuff is not enough, so this book also includes the advice you need when setting up a web site to achieve your goals. Key details—designing an effective page layout,posting your page to the Internet with FTP software, organizing and managing multiple pages,and getting your pages to appear high on the query lists at all the major Internet searchsites—are all covered in enough depth to get you beyond the snags that often frustratebeginners.Attention to many of these essentials are what made the first seven editions of this book bestsellers, and this updated edition—the first for this title since 2005—is no different. All of theexamples have been updated and a significant portion of the content has been revised to matchnew examples and new technologies.Visual ExamplesEvery example in this book is illustrated in two parts:. The text you type to make an HTML page is shown first, with all HTML and CSS code highlighted. The resulting web page is shown as it will appear to users who view it with the world’s mostpopular web browsers.You’ll often be able to adapt the example to your own pages without reading any of the accompanying text at all.All the examples in this book are standards-compliant and work with Apple Safari, Google Chrome,Microsoft Internet Explorer, Mozilla Firefox, and Opera. While all of the screenshots are taken inFirefox, rest assured that all of the code has been tested in all other browsers.

ixYou will also find the use of colors within code examples and when elements of code appear in theexplanatory text. These colors highlight the different bits and pieces of code both to enhance yourfamiliarity with them and to call attention to their use. HTML tags are displayed in dark blue. HTML comments are displayed in brown. CSS elements are displayed in green. HTML attribute names are displayed in light blue. HTML attribute values are displayed in magenta.Be aware that the colors of certain terms change depending on their context. For instance, whenCSS elements are used within the style attribute of an HTML tag, they will be color-coded as HTMLattribute values (magenta) rather than CSS elements (green).Special ElementsAs you complete each hour, margin notes help you immediately apply what you just learned to yourown web pages.TIPNOTEWARNINGTips and tricks to save youprecious time are set aside in“Tip” boxes so that you canspot them quickly.“Note” boxes provide additional information about the topicsbeing discussed.When there’s something youneed to watch out for, you’ll bewarned about it in “Warning”boxes.Q&A, Quiz, and ExercisesEvery hour ends with a short question-and-answer session that addresses the kind of “dumb questions” everyone wishes they dared to ask. A brief but complete quiz lets you test yourself to besure you understand everything presented in the hour. Finally, one or two optional exercises giveyou a chance to practice your new skills before you move on.

HOUR 3Understanding HTMLand XHTML ConnectionsThe first two hours gave you a basic idea of the process behind creatingweb content and viewing it online or locally, if you do not yet have a webhosting provider. In this hour, we’ll get down to the business of explainingthe various elements that must appear in an HTML file.At the end of the hour, you’ll learn how HTML differs from XHTML andwhy there are two different languages designed to do the same thing—create web content. In general, this hour provides a quick summary of HTMLand XHTML basics and gives some practical tips to make the most of yourtime as a web page author and publisher. It’s not all theory, however; you doget to see a real web page and the HTML code behind it.Here’s a review of what you need to do before you’re ready to use the restof this book:1. Get a computer. I used a computer with Windows Vista to test thesample web content and capture the figures in this book, but you canuse any Windows, Macintosh, or Linux/UNIX machine to create andview your web content.2. Get a connection to the Internet. Whether you have a dial-up, wireless, or broadband connection doesn’t matter for the creation andviewing of your web content, but the faster the connection, the betterfor the overall experience. The Internet Service Provider (ISP), school,or business that provides your Internet connection can help you withthe details of setting it up properly. Additionally, many public spacessuch as coffee shops, bookstores, and libraries offer free wirelessInternet service that you can use if you have a laptop computer withWi-Fi network support.WHAT YOU’LL LEARN INTHIS HOUR:. How to create a simpleweb page in HTML. How to include all theHTML Tags that every webpage must have. How to organize a pagewith paragraphs and linebreaks. How to organize your content with headings. How to validate your webcontent. How to differentiatebetween HTML, XML,XHTML, and HTML 5NOTENot sure how to find an ISP?The best way is to comparisonshop online (using a friend’scomputer or a public computerthat’s already connected to theInternet). You’ll find a comprehensive list of national andregional ISPs at http://www.thelist.com/.

28NOTEAlthough all web browsersprocess and handle informationin the same general way, thereare some specific differencesamong them that result in thingsnot always looking the same indifferent browsers. Be sure tocheck your web pages in multiple browsers to make sure thatthey look reasonably consistent.NOTEAs discussed in Hour 1, if youplan to put your web content onthe Internet (as opposed to publishing it on CD-ROM or a localintranet), you’ll need to transfer itto a computer that is connectedto the Internet 24 hours a day.The same company or school thatprovides you with Internet accessmight also provide web space; ifnot, you might need to pay a hosting provider for the service.WARNINGDo not create your first HTMLfile with Microsoft Word or anyother HTML-compatible wordprocessor; most of these programs attempt to rewrite yourHTML for you in strange ways,potentially leaving you totallyconfused. Additionally, I recommend that you do not use agraphical, what-you-see-is-whatyou-get (WYSIWYG) editor, suchas Microsoft FrontPage orAdobe Dreamweaver. You’ll likely find it easier and more educational to start out with a simple text editor while you’re justlearning HTML. You canprogress to visual tools (suchas FrontPage and Dreamweaver)after you have a better understanding of what’s going on“under the hood.”HOUR 3: Understanding HTML and XHTML Connections3. Get web browser software. This is the software your computer needsin order to retrieve and display web content. As you learned in thefirst hour, the most popular browser software (in alphabetical order)is Apple Safari, Google Chrome, Mozilla Firefox, Microsoft InternetExplorer, and Opera. It’s a good idea to install several of thesebrowsers so that you can experiment and make sure that your content looks consistent across them all; you can’t make assumptionsabout the browsers other people are using.4. Explore! Use a web browser to look around the Internet for web sitesthat are similar in content or appearance to those you’d like to create.Note what frustrates you about some pages, what attracts you andkeeps you reading others, and what makes you come back to somepages over and over again. If there is a particular topic that interestsyou, consider searching for it using a popular search engine such asGoogle (http://www.google.com/) or Bing(http://www.bing.com/).Getting Started with a Simple WebPageIn the first hour, you learned that a “web page” is just a text file that is“marked-up” by (or surrounded by) HTML codes that tell the browserhow to display the text. To create these text files, use a text editor such asNotepad (on Windows) or TextEdit (on a Mac)—do not use WordPad,Microsoft Word, or other full-featured word-processing software, as thosecreate different sorts of files than the plain-text files we use for web content.Before you begin working, you should start with some text that you wantto put on a web page:1. Find (or write) a few paragraphs of text about yourself, your family,your company, your softball team, or some other subject in whichyou’re interested.2. Save this text as plain, standard ASCII text. Notepad and most simple text editors always save files as plain text, but if you’re usinganother program, you might need to choose this file type as anoption (after selecting File, Save As).As you go through this hour, you will add HTML markup (called tags) tothe text file, thus making it into web content.

Getting Started with a Simple Web PageWhen you save files containing HTML tags, always give them a name ending in .html. This is important: if you forget to type the .html at the end ofthe filename when you save the file, most text editors will give it someother extension (such as .txt). If that happens, you might not be able tofind the file when you try to look at it with a web browser; if you find it, itcertainly won’t display properly. In other words, web browsers expect aweb page file to have a file extension of .html.You might also encounter a web page with a file extension of .htm, whichis also acceptable. You might find other file extensions used on the Web,such as .jsp (Java Server Pages), .asp (Microsoft Active Server Pages), or.php (PHP: Hypertext Preprocessor), but these file types use server-sidetechnologies that are beyond the scope of HTML.Listing 3.1 shows an example of text you can type and save to create a simple HTML page. If you opened this file with Firefox, you would see thepage shown in Figure 3.1. Every web page you create must include the html /html , head /head , title /title , and body /body tag pairs.Listing 3.1The html , head , title ,and body 29NOTEIf you’re using TextEdit on aMacintosh computer, the stepsfor creating an HTML file are alittle different than for usingNotepad on a Windows computer—both are popular text editors, but with the latter youmust first click on the Formatmenu and select Make PlainText and then change the preferences under the Saving header by unchecking the box forAppend ‘.txt’ Extension to PlainText Files. Also, the default preferences are set to show .htmldocuments as they wouldappear in a browser, whichwon’t allow you to edit them. Tofix this, check Ignore Rich TextCommands in HTML Files underthe Rich Text Processing header.Tags ?xml version ”1.0” encoding ”UTF-8”? !DOCTYPE html PUBLIC “-//W3C//DTD XHTML l11.dtd” html xmlns ”http://www.w3.org/1999/xhtml” xml:lang ”en” head title The First Web Page /title /head body p In the beginning, Tim created the HyperText Markup Language. The Internetwas without form and void, and text was upon the face of the monitor andthe Hands of Tim were moving over the face of the keyboard. And Tim said,Let there be links; and there were links. And Tim saw that the links weregood; and Tim separated the links from the text. Tim called the linksAnchors, and the text He called Other Stuff. And the whole thing togetherwas the first Web Page. /p /body /html

30HOUR 3: Understanding HTML and XHTML ConnectionsFIGURE 3.1When you save the text in Listing3.1 as an HTML file and view itwith a web browser, only the actualtitle and body text are displayed.NOTETechnically speaking, HTML 5will be the next web standardbut it’s not quite at the point offull adoption. Current estimateput the full adoption of HTMLsomewhere in the year 2011.However, as you learn aboutimportant features of HTML andXHTML in this book, I willinclude notes about how HTML5 features might differ.In Listing 3.1, as in every HTML page, the words starting with and ending with are actually coded commands. These coded commands arecalled HTML tags because they “tag” pieces of text and tell the web browser what kind of text it is. This allows the web browser to display the textappropriately.The first few lines of code in the web page serve as standard boilerplatecode that you will include in all of your pages. This code actually identifiesthe page as an XHTML 1.1 document, which means that, technically, theweb page is an XHTML page. All the pages developed throughout thebook are XHTML 1.1 pages. Because XHTML is a more structured versionof HTML, it’s still okay to generally refer to all the pages in the book asHTML pages. By targeting XHTML 1.1 with your code, you are developingweb pages that adhere to the very latest web standards. This is a goodthing!

Getting Started with a Simple Web PageBefore you learn the meaning of the HTML tags used in Listing 3.1, you mightwant to see exactly how I went about creating and viewing the documentitself. Follow these steps:31TRY IT YOURSELF Creating and Viewinga Basic Web Page1. Type all the text in Listing 3.1, including the HTML tags, in WindowsNotepad (or use Macintosh TextEdit or another text editor of yourchoice).2. Select File, Save As. Be sure to select plain text (or ASCII text) as thefile type.3. Name the file firstpage.html.4. Choose the folder on your hard drive where you would like to keep yourweb pages—and remember which folder you choose! Click the Save orOK button to save the file.5. Now start your favorite web browser. (Leave Notepad running, too, soyou can easily switch between viewing and editing your page.)In Internet Explorer, select File, Open and click Browse. If you’re using Firefox,select File, Open File. Navigate to the appropriate folder and select thefirstpage.html file. Some browsers and operating systems will also allowyou to drag and drop the firstpage.html file onto the browser window inorder to view it.Voilà! You should see the page shown in Figure 3.1.If you have obtained a web hosting account, you could use FTPat this point to transfer the firstpage.html file to the web server.In fact, from this hour forward, the instructions will assume youhave a hosting provider and are comfortable sending files backand forth via FTP; if that is not the case, please review the firsttwo hours before moving on. Or, if you are consciously choosingto work with files locally (without a web host), be prepared toadjust the instructions to suit your particular needs (such asignoring “transfer the files” and “type in the URL”).NOTEYou don’t need to be connected to theInternet to view a web page stored onyour own computer. By default, your webbrowser tries to connect to the Internetevery time you start it, which makessense most of the time. However, thiscan be a hassle if you’re developingpages locally on your hard drive (offline)and you keep getting errors about a pagenot being found. If you have a full-timeweb connection via a LAN, cable modem,or DSL, this is a moot point because thebrowser will never complain about beingoffline. Otherwise, the appropriate disciplinary action will depend on your breedof browser; check the options under yourbrowser’s “Tools” menu.

32HOUR 3: Understanding HTML and XHTML ConnectionsHTML Tags Every XHTML Web PageMust HaveNOTEIt isn’t terribly important thatyou understand concepts suchas character encoding at thispoint. What is important is thatyou include the appropriate boilerplate code in your pages sothat they adhere to the latestweb standards. As of this writing, XHTML 1.1 is a web standard. HTML 5 is not yet a webstandard, but if you were creating an HTML 5 document, theselines at the beginning of yourHTML file would not be necessary.The time has come for the secret language of HTML tags to be revealed toyou. When you understand this language, you will have creative powersfar beyond those of other humans. Don’t tell the other humans, but it’sreally pretty easy.Before you get into the HTML tags, let’s first address the messy-lookingcode at the top of Listing 3.1. The first line indicates that the HTML document is, in fact, an XML document: ?xml version ”1.0” encoding ”UTF-8”? The version of XML is set to 1.0, which is fairly standard, as is the type ofcharacter encoding (UTF-8).The second and third lines of code in Listing 3.1 are even more complicated looking: !DOCTYPE html PUBLIC “-//W3C//DTD XHTML l11.dtd” NOTEThe XML/XHTML boilerplatecode isn’t strictly required inorder for you to create webpages. You can delete theopening lines of code in theexample so that the pagestarts with the html tag and itwill still open fine in a webbrowser. The extra code isincluded to ensure your pagesare up to date with the currentweb standards. Additionally, theextra code allows you to validate your web pages for accuracy, which you’ll learn how to doa bit later in this lesson.Again, the specifics of this code aren’t terribly important as long as youremember to include the code at the start of your pages. This code identifies the document as being XHTML 1.1, which then allows web browsersto make sure the code meets all the requirements of XHTML 1.1.Most HTML tags have two parts: an opening tag, which indicates where apiece of text begins, and a closing tag, which indicates where the piece oftext ends. Closing tags start with a / (forward slash) just after the symbol. Another type of tag is the empty tag, which is unique in that it doesn’tinclude a pair of matching opening and closing tags. Instead, an empty tagconsists of a single tag that starts with a and ends with a / just before the symbol. Following is a quick summary of these three tags just to makesure you understand the role each of them plays:. An opening tag is an HTML tag that indicates the start of an HTMLcommand; the text affected by the command appears after the opening tag. Opening tags always begin with and end with , as in html . A closing tag is an HTML tag that indicates the end of an HTML command; the text affected by the command appears before the closingtag. Closing tags always begin with / and end with , as in /html .

HTML Tags Every XHTML Web Page Must Have. An empty tag is an HTML tag that issues an HTML command without enclosing any text in the page. Empty tags always begin with and end with / , as in br / and img / .For example, the body tag in Listing 3.1 tells the web browser where theactual body text of the page begins, and /body indicates where it ends.Everything between the body and /body tags will appear in the maindisplay area of the web browser window, as shown in Figure 3.1.The very top of the browser window (refer to Figure 3.1) shows title text,which is any text that is located between title and /title . The titletext is also used to identify the page on the browser’s Bookmarks orFavorites menu, depending on which browser you use. It’s important toprovide titles for your pages so that visitors to the page can properlybookmark them for future reference.You will use the body and title tag pairs in every HTML page you create because every web page needs a title and body text. You will also use html and head , which are he other two tags shown in Listing 3.1.Putting html at the very beginning of a document simply indicates thatthe document is a web page. The /html at the end indicates that the webpage is over.Within a page, there is a head section and a body section. Each section isidentified by head and body tags. The idea is that information in thehead of the page somehow describes the page but isn’t actually displayedby a web browser. Information placed in the body, however, is displayedby a web browser. The head tag always appears near the beginning of theHTML code for a page, just after the opening html tag.The title tag pair used to identify the title of a page appears within thehead of the page, which means it is placed after the opening head tagand before the closing /head tag. (Upcoming hours reveal some otheradvanced header information that can go between head and /head , suchas style sheet rules that are used to format the page.)The p tag used in Listing 3.1 encloses a paragraph of text. You shouldenclose your chunks of text in the appropriate container tags wheneverpossible.33NOTEYou no doubt noticed in Listing3.1 that there is some extracode associated with the html tag. This code consistsof two attributes (xmlns andxml:lang), which are used tospecify additional informationrelated to the tag. These twoattributes are standard requirements of all XHTML web pages;the former defines the XMLnamespace, while the latterdefines the language of thecontent. Throughout this book astandard namespace isdefined, and the English language is used. If you are writingin a different language, replacethe “en” (for English) with thelanguage identifier relevant toyou.TIPYou might find it convenient tocreate and save a bare-bonespage (also known as a skeletonpage) with just the opening andclosing html , head , title ,and body tags, similar to thedocument used in Listing 3.1.You can then open that document as a starting point whenever you want to make a newweb page and save yourself thetrouble of typing all those obligatory tags every time.

34HOUR 3: Understanding HTML and XHTML ConnectionsOrganizing a Page with Paragraphsand Line BreaksWhen a web browser displays HTML pages, it pays no attention to lineendings or the number of spaces between words. For example, the top version of the poem shown in Figure 3.2 appears with a single space betweenall words, even though that’s not how it’s entered in Listing 3.2. This isbecause extra whitespace in HTML code is automatically reduced to a single space. Additionally, when the text reaches the edge of the browser window, it automatically wraps to the next line, no matter where the linebreaks were in the original HTML file.Listing 3.2HTML Containing Paragraph and Line Breaks ?xml version ”1.0” encoding ”UTF-8”? !DOCTYPE html PUBLIC “-//W3C//DTD XHTML l11.dtd” html xmlns ”http://www.w3.org/1999/xhtml” xml:lang ”en” head title The Advertising Agency Song /title /head body p When your client’shopping mad,put his picture in the ad.If he still shouldprove refractory,add a picture of his factory. /p hr / p When your client’s hopping mad, br / put his picture in the ad. /p p If he still should prove refractory, br / add a picture of his factory. /p /body /html

Organizing a Page with Paragraphs and Line Breaks35FIGURE 3.2When the HTML in Listing 3.2 isviewed as a web page, line andparagraph breaks only appearwhere there are br / and p tags.You must use HTML tags if you want to control where line and paragraphbreaks actually appear. When text is enclosed within the p /p containertags, a line break will be assumed after the closing tag. In later hours, youwill learn to control the height of the line break using CSS. The br / tagforces a line break within a paragraph. Unlike the other tags you’ve seenso far, br / doesn’t require a closing /br tag—this is one of those emptytags discussed earlier. Although HTML 4 does not require the / in emptytags, XHTML does and future standards will, so it’s important for you tostick to the latest standards and create web pages that are coded properly.Always code empty tags so that they end with / .The poem in Listing 3.2 and Figure 3.2 shows the br / and p tagsbeing used to separate the lines and verses of an advertising agency song.You might have also noticed the hr / tag in the listing, which causes ahorizontal rule line to appear on the page (see Figure 3.2). Inserting a horizontal rule with the hr / tag also causes a line break, even if you don’tinclude a br / tag along with it. Like br / , the hr / horizontal ruletag is an empty tag and therefore never gets a closing /hr tag.WARNINGYou might fin

Sams teach yourself HTML and CSS 24 hours / Julie Meloni, Michael Morrison. -- 8th ed. p. cm. Rev. ed. of: Sams teach yourself HTML and CSS in 24 hours / Dick . At the end of the hour, you'll learn how HTML differs from XHTML and why there are two different languages designed to do the same thing—cre-ate web content. In general, this hour .