1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Web Programming with HTML, XHTML, and CSS pps

832 457 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning Web Programming with HTML, XHTML, and CSS
Tác giả Jon Duckett
Trường học Brunel University
Chuyên ngành Web Programming
Thể loại Book
Năm xuất bản 2004
Thành phố London
Định dạng
Số trang 832
Dung lượng 16,61 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Keeping Style Separate from Structure and Semantics 10 Differences Between Writing XHTML and Writing HTML 13 Understanding the Basic Document Structure 26 Creating Paragraphs Using the

Trang 2

with HTML, XHTML, and CSS

i

Trang 3

Beginning Web Programming with HTML, XHTML, and CSS

Jon Duckett

Wiley Publishing, Inc

Trang 4

Beginning Web Programming with HTML,

XHTML, and CSS

CopyrightC 2004 by Wiley Publishing, Inc All rights reserved

Published simultaneously in Canada

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 aspermitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the priorwritten permission of the Publisher, or authorization through payment of the appropriate per-copy fee

to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax(978) 646-8700 Requests to the Publisher for permission should be addressed to the Legal Department,Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)572-4355, E-mail:brandreview@wiley.com

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHORMAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY ORCOMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WAR-RANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULARPURPOSE NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONALMATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLEFOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUB-LISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONALSERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENTPROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHORSHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZA-TION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIALSOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUB-LISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE ORRECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTER-NET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEENWHEN 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 (800) 762-2974, outside the United States at (317) 572-3993 orfax (317) 572-4002

Trademarks:Wiley, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress aretrademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the UnitedStates and other countries, and may not be used without written permission All other trademarks arethe property of their respective owners Wiley Publishing, Inc., is not associated with any product orvendor mentioned in this book

Wiley also publishes its books in a variety of electronic formats Some content that appears in printmay not be available in electronic books

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1

eISBN: 0-7645-7813-8

Trang 5

About the Author

Jon Duckett published his first Web site in 1996 while studying for a BSc (Hons) in Psychology at BrunelUniversity, London Since then he has helped create a wide variety of Web sites and has co-written morethan ten programming-related books on topics from ASP to XML (via many other letters of the alphabet)covering diverse aspects of Web programming including design, architecture, and coding

After graduation, Jon worked for Wrox Press first in its Birmingham (UK) offices for three years and then

in Sydney, Australia, for another year He is now a freelance developer and consultant based in a leafysuburb of London, working for a range of clients spread across three continents

When not stuck in front of a computer screen, Jon enjoys listening to music and writing

Trang 6

Mary Beth Wakefield

Vice President & Executive Group Publisher

Trang 7

Keeping Style Separate from Structure and Semantics 10

Differences Between Writing XHTML and Writing HTML 13

Understanding the Basic Document Structure 26

Creating Paragraphs Using the <p> Element 38

Trang 8

Creating Line Breaks Using the <br /> Element 38Creating Preformatted Text Using the <pre> Element 39

The <s> and <strike> Elements (deprecated) 44

The <strong> Element Adds Strong Emphasis 47The <abbr> Element Is for Abbreviations 48The <acronym> Element Is for Acronym Use 48The <dfn> Element Is for Special Terms 49The <blockquote> Element Is for Quoting Text 49The <q> Element Is for Short Quotations 50The <cite> Element Is for Citations 51

The <kbd> Element Is for Text Typed on a Keyboard 52The <var> Element Is for Programming Variables 52The <samp> Element Is for a Program Output 53The <address> Element Is for Addresses 53

Grouping Elements with <div> and <span> 66

Trang 9

Summary 67

Understanding Directories and Directory Structures 73

Creating Links with the <a> Element 80Creating a Source Anchor with the href Attribute 81Creating a Destination Anchor Using the name and id Attributes (linking to a

Adding Images Using the <img> Element 111

Trang 10

Adding Other Objects with the <object> Element 117

The <table> Element Creates a Table 134The <tr> Element Contains Table Rows 138The <td> and <th> Elements Represent Table Cells 140

Splitting up Tables Using a Head, Body, and Foot 146

Spanning Columns Using the colspan Attribute 149Spanning Rows Using the rowspan Attribute 149Grouping Columns Using the <colgroup> Element 151Columns Sharing Styles Using the <col> Element 152

Creating a Form with the <form> Element 161

Trang 11

The enctype Attribute 163

Browser-Specific Extensions to the <frameset> Element 210

The marginwidth and marginheight Attributes 213

Trang 12

The scrolling Attribute 214

Setting a Default Target Frames Using the <base> Element 217

Floating or Inline Frames with <iframe> 222

The <s> and <strike> Elements 235

The <listing>, <plaintext>, and <xmp> Elements 236

The clear Attribute (on <br /> element) 246

The <dir> and <menu> Elements 250

Trang 13

Miscellaneous Attributes 252

Trang 14

The text-shadow Property 287

Trang 15

The background-position Property (for fixing

The background-attachment Property (for watermarks) 328The background Property (the well-supported shorthand) 330

The @import Rule: Modularized Style Sheets 349

Trang 16

The z-index Property 356

Whitespace Helps Make More Attractive Pages 420

Trang 17

Wide Columns of Text Are Harder to Read 423Background Images Can Make Text Hard to Read 424

Fixed Size Fonts Are Affected by Screen Resolution 426

Working with (not Against) the Constraints of a Device 485Why Use XHTML if Content or Sections of Sites

Trang 18

Complementary Services for Different Devices 493

Trang 19

Has Someone Already Written This Script? 549

Trang 20

Hiding Your E-mail Address 588

Anything the User Requires from Your Site 588

The Importance of Directory Structure and Relative URLs 599

Checking Different Screen Resolutions and Color Depths 604

Checking in Different Versions of Browsers 606

Server-Side Web Programming: ASP, JSP, and PHP 622

Trang 21

Appendix A: Answers to Exercises 631

Trang 23

There are a lot of books about designing and building Web pages, so thank you for picking up this one.Why do I think it is different? Well, the Web has been around for quite a few years now, and during its lifeseveral technologies have been introduced to help you create Web pages, some of which have lasted,others of which have disappeared Indeed, even enduring technologies such as HTML have had featuresadded and removed over the years Many books that teach you to write Web pages are revisions of earlierversions of the same book and therefore still take the same approach as the previous edition did Thisbook, however, is completely new, written from scratch, and its purpose is to teach you how to createWeb pages for the Web as it is today and will be for the next few years Once you have worked throughthis book, it should continue to serve as a helpful reference text you can keep nearby and dip into whenyou need to

About the Book

At the time of this writing, Internet Explorer version 6 and Netscape version 7 are the main Webbrowsers, and each of the previous versions of these browsers had added new features as the Webdeveloped (and sometimes old features were removed) As all this change might suggest, there is morethan one way to build a Web site For example, if you want to have a heading for a page displayed in abold, black, Arial typeface, you can achieve this in several ways However, you can also consider this avery good time to come to the Web, as many of the technologies used to create Web pages are maturing,and favored methods for creating Web sites, or “best practices,” are emerging

Writing Web pages today thus requires a balance On the one hand you want to use the latest and bestmethods, while on the other hand you have to remember that not everyone who visits your Web site hasthe latest browser software So you need to be able to write pages that take advantage of the features ofthe latest browsers while at the same time ensuring your sites can be viewed in older browsers (Indeed, if

you want to make a living from working on Web pages, you will need to be aware of some of the older ways of doing things.) In this book, I teach you the best practices that you should be learning, and, where

necessary, I expose the older techniques that help you achieve the results you want

Over the past few years there have also been innovations and changes in the way people access theInternet The Web is no longer just viewed on desktop computers; Web sites are becoming available ondevices with small screens, such as mobile phones and PDAs (personal digital assistants), and somedevices such as televisions have lower resolutions than computer monitors There are even stories in thenewspapers about how we will all soon have refrigerators and other appliances that will allow us tobrowse the Web So, while most of the examples in this book are written for a computer, I will teach you

to code your Web pages so that you can make them available to other devices without rewriting yourwhole site Learning to code for the emerging generation of applications will make your Web sites andyour skills last much longer

Another area where the Web has changed from a few years back is the increased emphasis on usability

and accessibility Usability refers to making the site easy for users to get around (or navigate) and achieve what they came to your site for, whereas accessibility addresses making a site available to as many users as

Trang 24

possible, in particular people with disabilities (who may have impaired vision or difficulty using amouse) Many governments around the world will not issue a contract to build Web sites for them unlessthe site will meet strict accessibility standards A little careful thought before you build your Web sitemeans that people with vision impairments can either view your site with larger text or have it read tothem by a screen reader There are books dedicated to the topics of usability and accessibility that areaimed at Web developers who need to learn how to make their code more accessible and usable, but myaim is to teach you to code with these principles in mind from the start.

By the end of this book, you will be writing Web pages that not only use the latest technologies, but alsoare still viewable by older browsers Pages that look great can still be accessed by those with visual andphysical impairments—pages that not only address the needs of today’s audiences but can also work onemerging technologies—and the skills you learn should be relevant for longer

Who This Book Is For

This book is written for anyone who wants to learn how to create Web pages, and for people who mighthave dabbled in writing Web pages (perhaps using some kind of Web page authoring tool) but want toreally understand the languages of the Web to create better pages

More experienced Web developers can also benefit from this book because it teaches some of the latesttechnologies, such as XHTML, and encourages you to embrace Web standards that not only meet theneeds of the new devices that access the Web, but also help make your sites available to more visitors.You do not need any previous programming experience to work with this book—even though these bigred Wrox books are published under the trademark Programmer to Programmer (because the books arewritten by programmers for programmers) 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 youthe basics of programming for the Web Sure, the term “programmer” might be associated with geeks,but as you will see by the end of the book, even if you would prefer to be known as a Web designer, youneed to know how to code to write great Web sites

What This Book Covers

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 markup languages such as HTML, but you will also seehow to apply this code so you can create sophisticated layouts for your pages, positioning text andimages where you want and getting the colors and fonts you want Along the way, you will see how tomake your pages easy to use and available to the biggest audience possible You will also learn practicaltechniques such as how to put your Web site available on the Internet and how to get search engines torecognize your site

The main technologies covered in this book are HTML, XHTML, and CSS XHTML is not actually acompletely different language than HTML; it is more like the latest version of it What would have beenHTML 5 was named XHTML, rather like how Microsoft called what would have been Windows 2001Windows XP XHTML stands for eXtensible Hypertext Markup Language; it describes the structure ofWeb pages such as the headings, paragraphs of text, tables, bulleted lists, and so on CSS is then used toapply styles the documents, to change things such as colors, typefaces, sizes of text, and so on Once you

Trang 25

have learned the basics of these languages you will learn some more practical aspects of applying them.You will also learn the basics of JavaScript, enough to work on some examples that add interactivity toyou pages and allow you to work with basic scripts Along the way I introduce and point you to othertechnologies you might want to learn in the future.

The code I will encourage you to write is based on what are known as Web standards; HTML, XHTML,and CSS are all created and maintained by the World Wide Web Consortium, or W3C (http://www.w3.org/), an organization dedicated to creating specifications for the Web You will also learn about somefeatures that are not standards, but it is helpful to know some of these in case you come across suchmarkup and need to know what it does (where these are introduced I make it clear that they are not part

of the standard)

What You Need to Use This Book

All you need to work through this book is a computer with a Web browser (preferably Netscape 6 orhigher, or Internet Explorer 6 or higher), and a simple text editor such as Notepad on Windows orSimpleText on Mac

If you have a Web page editor program, such as Macromedia Dreamweaver or Microsoft FrontPage, youare welcome to use it, but I will not be teaching you how to use these programs Each program is differentand entire books could be and have been written on the individual programs Even if you were to use one

of these tools, you can write much better sites when you really understand the code such programsgenerate Like many of the other books on the shelves, these programs were created years ago and do notaddress the best way to write pages today They get jobs done, but not necessarily in the best waypossible, so you will often want to edit the code they create

How This Book Is Organized

The first chapter of this book gives you the big picture of creating pages for the Web It explains how allthe technologies you will be learning in this book fit together In this very first chapter you will also create

your first Web page and learn how the main task in creating a Web site is marking up the text you want to appear on your site using things called elements and attributes.

The next six chapters of the book describe the different elements and attributes that make up HTML andXHTML and how you can use them to write Web pages The chapters are organized into task-relatedareas, such as structuring a document into headings and paragraphs, creating links between pages,adding color and images, displaying tables, and so on With each task or topic that is introduced you willsee an example first to give you an idea of what is possible; then you can look at the elements andattributes used in detail

These task-focused chapters are followed by one on deprecated markup, which is markup that is no longer

part of XHTML, and browser-specific markup, which was introduced by the main browser vendors butnot used in the W3C HTML and XHTML recommendations While you should not rely on this markupfor writing your pages, you are likely to come across it when working with older Web pages

At the end of each are exercises that are designed to get you working with some of the concepts youlearned about in each chapter Don’t worry if you have to go back and review the content of the chapter inorder to complete the exercises; this book has been created with the intention that it should be a helpful

Trang 26

reference for years to come, so don’t feel you need to learn everything by heart Along the way you seewhich browsers support each element, and you learn plenty of handy tips, tricks, and techniques forcreating professional Web pages.

Once you have seen how to create and structure a document using HTML and XHTML, you then learnhow to make your pages look more attractive using cascading style sheets (CSS) You’ll learn how tochange the typefaces and size of fonts used, color of text, backgrounds and borders around items, andalignment of objects to the center, left, or right of the page

Having worked through these chapters, and using the examples in the book, you should be able to writequite complex Web pages These chapters will serve as a helpful reference you can keep coming back toand the examples will act as a toolkit for building your own sites

The next chapters look at important Web page design issues You see some examples of popular pagelayouts and how to construct them; you learn how to create a good navigation bar to allow users to findthe pages they want on your site; you find out what makes a form effective; and you learn how to makeyour Web sites available to as many people as possible These chapters really build upon the theory youlearned in the first half of the book and help you create professional looking pages that really attract usersand make your site easy to use

The final chapters then take you through some more advanced issues There is a chapter on ModularizedXHTML, which is the future of XHTML, and which will allow you to create pages for devices other thandesktop computers Indeed, you will see an example of a site that uses XHTML to send pages to a mobile

phone Then two chapters introduce you to JavaScript, a programming language known as a scripting

language that you use in Web pages While the entire JavaScript language is too large to teach you in two

chapters, you should get a feel for how it works and see how to integrate scripts into your pages The lastchapter prepares you to put your site on the Internet and covers Web hosting, FTP, and validating yourcode Finally, I give you some ideas of where you can go now that you’ve worked through this book;there are a lot of other things you might want to add to your site or learn to advance your Web skills, andthis chapter gives you an idea of what else is possible and what you need to learn to do that

Conventions

To help you get the most from the text and keep track of what’s happening, this book uses a number oftypographical conventions

Boxes like this one hold important, not-to-be forgotten information that is directly

relevant to the surrounding text.

Tips, hints, tricks, and asides to the current discussion are set off and placed in italics like this.

As for styles in the text:

Important words are italicized when first introduced.

❑ Keyboard strokes appear like this: Ctrl+A

Trang 27

❑ Filenames, URLs, and code within the text appear in monospace, like so:version="10".

❑ Code appears two different ways:

In code examples, new and important code appears with a gray background

The gray highlighting is not used for code that's less important in thepresent context or has been shown before

Source Code

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 isavailable for download atwww.wrox.com Once at the site, simply locate the book’s title (either by usingthe Search box or by using one of the title lists) and click the Download Code link on the book’s detailpage to obtain all the source code for the book

Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 0-7645-7078-1.

Once you download the code, just decompress it with your favorite compression tool Alternately, youcan go to the main Wrox code download page atwww.wrox.com/dynamic/books/download.aspx

to see the code available for this book and all other Wrox books

To find the errata page for this book, go towww.wrox.comand 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 allerrata that has been submitted for this book and posted by Wrox editors A complete book list includinglinks to each book’s errata is also available atwww.wrox.com/misc-pages/booklist.shtml

If you don’t spot “your” error on the Book Errata page, go towww.wrox.com/contact/techsupport.shtmland complete the form there to send us the error you discovered We’ll check the informationand, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions

of the book

p2p.wrox.com

For author and peer discussion, join the P2P forums atp2p.wrox.com The forums are a Web-basedsystem for you to post messages related to Wrox books and related technologies and interact with otherreaders and technology users The forums offer a subscription feature to e-mail you about topics of your

Trang 28

choosing when new posts are made to the forums Wrox authors, editors, other industry experts, andyour fellow readers are present on these forums.

Athttp://p2p.wrox.comyou will find a number of different forums that will help you not only as youread this book, but also as you develop your own applications To join the forums, just follow these steps:

1. Go top2p.wrox.comand click the Register link

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish toprovide and click Submit

4. You will receive an e-mail with information describing how to verify your account and completethe registration process

You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post You can readmessages at any time on the Web If you would like to have new messages from a particular forume-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 toquestions about how the forum software works as well as many common questions specific to P2P andWrox books To read the FAQs, click the FAQ link on any P2P page

Trang 29

Beginning Web Programming with HTML, XHTML, and CSS

Trang 31

Untangling the Web

At one time, you had to learn only one language to write Web pages: HTML As the Web hasadvanced, however, so have the technologies you need to learn in order to create effective andattractive Web pages As the title of this book suggests, you will be learning a few differentlanguages: HTML, XHTML, CSS, and a bit of JavaScript But before you start learning each of theselanguages individually, it helps if you understand what each of these languages does and how theyfit together

This is not just a theory and history lesson, however; you will be writing your first Web page soonerthan you might think, and along the way you will also learn some of the essential backgroundinformation, such as what a markup language actually is, the difference between a tag and anelement, and how a Web page is structured

As you are about to see, a Web page is made up of not only the text or images you see when you visit

a site, but also information about the structure of the document, such as what text is a heading andwhere each paragraph starts and finishes Each Web page can also contain general information such

as a title for the page, a description that can help search engines such as Google index your Web site,and links to things called style sheets that change the appearance of fonts, colors, and so on

In this chapter, then, you will:

❑ Meet HTML, XHTML, CSS, and JavaScript and learn what each does

❑ Learn the difference between tags, elements, and attributes

❑ See how a Web page is structured

❑ Learn why rules that say how a document looks are best kept separate from the content

of the Web page

❑ Cover the differences between writing HTML and XHTML

❑ Meet some of the tools you can use to help you write Web pages

❑ Learn the basics of how a Web page gets to you when you request it

By the end of the chapter you will have a good idea of how Web pages are created, and you willhave built your own first Web page

Trang 32

A Web of Structured Documents

To start off, you need to consider the concept of the Web as a sea of documents In its relatively short life,

the Web has grown to feature millions of sites and billions of pages For the moment, think of each ofthese pages as a document Many documents on the Web bear a strong similarity to the documents youmeet in everyday life, and all documents have a structure, so think for a moment about the structure ofsome of the documents you see in everyday life

Every morning I used to read a newspaper A newspaper is made up of several stories or articles (andprobably 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

I don’t buy a daily paper anymore as I tend to look at news online, but the structure of articles on newsWeb sites is very similar to the structure of articles in newspapers Each article is made up of headings,paragraphs of text, the odd picture (and, yes, maybe some ads, too) The parallel is quite clear The onlyreal difference is that each story gets its own page on a Web site, which is usually accessible from aheadline and a brief summary either on the home page or the title pages for one of the subsections (such

as the politics, sports, or entertainment sections)

Consider another example: Say I’m catching a train to see a friend, so I check the schedule to see whattime the trains go that way The main part of the schedule is a table telling me what times trains arrive atand when they depart from different stations Like paragraphs and headings, a lot of documents usetables From the stocks and shares pages in the financial supplement of my paper to the TV listings at theback, you come across tables of information every day—and these are often recreated on the Web

A different kind of document you often come across is a form For example, I have a form sitting on mydesk (which I really must mail) from an insurance company This form contains fields for me to write myname, address, and the amount of coverage I want, and boxes I have to check off to indicate the number

of rooms in the house and what type of lock I have on my front door Indeed, there are lots of forms onthe Web, from a simple search box that asks what you are looking for to the registration forms you arerequired go through 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 acrossevery day and pages you see on the Web So you will hardly be surprised to learn that when it comes towriting Web pages, your code tells the Web browser the structure of the information you want todisplay—what text to put in a heading, or in a paragraph, or in a table, and so on—so that the browsercan present it properly to the user

The languages you need to learn in order to tell a Web browser the structure of a document—how tomake a heading, a paragraph, a table, and so on—are HTML and XHTML

How the Web Works

Before you learn how to write a very basic Web page, you should understand a little about how the Webworks, such as what happens when you type a Web address such ashttp://www.wrox.com/or

http://www.google.com/into the browser and a page gets returned

Every computer that is connected to the Internet is given a unique address made up of a series of fournumbers between 0 and 256 separated by periods—for example, 192.168.0.123 or 197.122.135.127 These

Trang 33

numbers are known as IP addresses IP (or Internet Protocol) is the standard for how data is passed

between machines on the Internet

When you connect to the Internet using an ISP you will be allocated an IP address, and you will often beallocated a new IP address each time you connect

Every Web site, meanwhile, sits on a computer known as a Web server (often you will see this shortened to

server) When you register a Web address, also known as a domain name, such aswrox.comyou have to

specify the IP address of the computer that will host the site.

When you visit a Web site, you are actually requesting pages from a machine at an IP address, but ratherthan having to learn that computer’s 12-digit IP address, you use the site’s domain name, such as

google.comorwrox.com When you enter something likehttp://www.google.com, the request

goes to one of many special computers on the Internet known as domain name servers (or name servers, for

short) These servers keep tables of machine names and their IP addresses, so when you type in

http://www.google.com, it gets translated into a number, which identifies the computers that servethe Google Web site to you

When you want to view any page on the Web, you must initiate the activity by requesting a pageusing your browser (if you do not specify a specific page, the Web server will usually send

a default Web page) The browser asks a domain name server to translate the domain name yourequested into an IP address The browser then sends a request to that server for the page you want,

using a standard called Hypertext Transfer Protocol or HTTP (hence thehttp://you see at the start ofmany Web addresses)

The server should constantly be connected to the Internet—ready to serve pages to visitors When itreceives a request, it looks for the requested document and returns it When a request is made, the serverusually logs the client’s IP address, the document requested, and the date and time it was requested

An average Web page actually requires the Web browser to request more than one file from theWeb server—not just the XHTML page, but also any images, style sheets, and other resources in the

page Each of these files, including the main page, needs a URL (a uniform resource locator) to

identify it A URL is a unique address on the Web where that page, picture, or other resource can befound and is made up of the domain name (for example,wrox.com), the name of the folder orfolders on the Web server that the file lives in (also known as directories on a server), and the name

of the file itself For example, the Wrox logo on the home page of the Wrox Web site has the uniqueaddresswrox.com/images/mainLogo.gifand the main page iswrox.com/default.html Afterthe browser acquires the files it then inserts the images and other resources in the appropriate place todisplay the page

The final chapter of the book covers putting your site on a Web server, but first you must learn how tobuild your site

You may have noticed on the Web that Web pages do not always end in html There are lots of other suffixes, such as asp and php You are introduced to the languages ASP and PHP in the final chapter; they usually run extra code on the server to generate a page especially for you Meanwhile, htm files are just HTML files like those you have already started creating—because you can save HTML files with either the suffix htm or html

For an example of how all of this works, see Figure 1-1 and the explanation that follows it

Trang 34

Figure 1-1

Here’s what’s going on in the figure:

1. A user enters a URL into a browser (for example,http://www.wrox.com) This request ispassed to a domain name server

2. The domain name server returns an IP address for the server that hosts the Web site (for

Introducing Web Technologies

Now that you are thinking of the Web as a huge collection of documents, not dissimilar to the documentsyou come across in everyday life, and you know how a Web page gets to you when you type a URL intoyour browser, it is time to look at the technologies used to write Web pages

In this section you meet HTML, CSS, XHTML, and JavaScript You will get an idea what each language isused for and start to see the basics of how each works With a basic understanding of each of thesetechnologies you will find it easier to see the big picture of creating pages for the Web

Introducing HTML

HTML, or Hypertext Markup Language, is the most widely used language on Web As its name suggests,

HTML is a markup language, which may sound complicated, although really you come across markup

every day Markup is just something you add to a document to give it special meaning; for example,when you use a highlighter pen you are marking up a document When you are marking up a document

for the Web, the special meaning you are adding indicates the structure of the document, and the markup

indicates which part of the document is a heading, which parts are paragraphs, what belongs in a table,and so on This markup in turn allows a Web browser to display your document appropriately

When creating a document in a word processor, you can distinguish headings using a heading style(usually with a larger font) to indicate which part of the text is a heading You can use the Enter

Trang 35

(or Return) key to start a new paragraph You can insert tables into your document, create bulleted lists,and so on When marking documents up for the Web you are performing a very similar process.

HTML and XHTML are the languages you use to tell a Web browser where the heading is for a Web page,what is a paragraph, what is part of a table and so on, so it can structure your document and render itproperly But what is the difference between HTML and XHTML? Well, first you should know that thereare several versions of both HTML and XHTML, but don’t let that bother you—it all sounds a lot morecomplicated than it really is Whereas there are several versions of HTML, each version just addsfunctionality on top of its predecessor (like a new version of some software might add some features or anew version of a dictionary might add a few extra words), or offers better ways of doing things that werealready in earlier versions So, you do not need to learn each version of HTML and XHTML, nor do youneed to focus on one variation This book teaches you all you need to know to write Web pages usingHTML and XHTML Indeed, as I mentioned in the Introduction, XHTML is just like the latest version

of HTML, as you will see shortly (although to be accurate, while it is almost identical to the last version ofHTML, it is technically HTML’s successor)

Let’s have a look at a simple page in HTML (Remember that you can download this example along withall the code for this book from the Wrox Web site atwww.wrox.com; the example is in the Chapter 1folder and is calledch01_eg01.htm.)

<h1>About Acme Toys Inc.</h1>

<p>Acme Toys has been making toys for popular cartoon characters forover 50 years One of our most popular customers was Wile E Coyote, whoregularly purchased items to help him catch Road Runner.</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 words in the angle brackets are known as markup Figure 1-2 illustrates what this page

would look like in a Web browser

Figure 1-2

Trang 36

As you can see, this document contains the heading “About ACME Toys Inc.” and a paragraph of text tointroduce the fictional company Note also that it says “Acme Toy Company: About Us” right at the top of

the window in the middle; this is known as the title of the page.

To understand the markup in this first example, you need to look at what is written between the anglebrackets and compare that with what you see in the figure, which is what you will do next

Tags and Elements

If you look at the first and last lines of the code for the last example, you will see pairs of angle bracketscontaining the letters<html> The two brackets and all of the characters between them are known as a

tag, and there are lots of tags in the example All of the tags in this example come in pairs; there are opening tags and closing tags The closing tag is always slightly different than the opening tag in that it has

a forward slash character before the characters</html>

A pair of tags and the content it includes is known as an element In Figure 1-3 you can see the heading for

the page of the last example

Figure 1-3Again, the tags in Figure 1-3 come in pairs I mentioned earlier in the chapter that markup adds meaning

to a document, and in HTML it is the tags that are the markup The special meaning these tags give is adescription of the structure of the document The opening tag says “This is the beginning of a heading”and the closing tag says “This is the end of a heading.” Without the markup, the words in the middlewould just be another bit of text; it would not be clear that they formed the heading

Now look at the paragraph of text about the company; it is held between an opening<p>tag and aclosing</p>tag And, you guessed it, thepstands for paragraph

Because this basic concept is so important to understand, I think it bears repeating:

tags are the letters and numbers between the angle brackets, whereas elements are

tags and anything between the opening and closing tags.

As you can see, the markup in this example actually describes what you will find between the tags, andthe added meaning the tags give is describing the structure of the document For example, between theopening<p>and closing</p>tags are paragraphs and between the<h1>and</h1>tags is a heading.Indeed, the whole HTML document is contained between opening<html>and closing</html>tags

If you were wondering why there is a number 1 after the h , it is because in HTML and XHTML there are six levels of headings A level 1 heading is sometimes used as the main heading for a document (such as a chapter title), which can then contain subheadings, with level 6 being the smallest This allows you to

structure your document appropriately with subheadings under the main heading (You look at this in

detail in the next chapter.)

Trang 37

You will 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, while the element that is 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

Separating Heads from Bodies

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 last example Inside the<html>element, thereare two main parts to the page:

The <head> element: Often referred to as the head of the page, this contains information about

the page (this is not the main content of the page) It is information such as a title and adescription of the page, or keywords that search engines can use to index the page It consists ofthe opening<head>tag, the closing</head>tag, and everything in between

The <body> element:Often referred to as the body of the page, this contains the informationyou actually see in the main browser window It consists of the opening<body>tag, closing

</body>tag, and everything in between

Inside the<head>element of the first example page you can see a<title>element:

The head element contains information about the document, which is not displayed within the main page itself The body element holds the actual content of the page that is viewed in your browser.

Adding Style

The first example page isn’t going to win any awards for design Indeed, when the Web started it was arather gray place filled with drab pages like this one While the Web was originally conceived to transmitscientific research documents (so that existing research could reach wider audiences), it did not take longfor people to find other uses for it No one can question that the speed with which the Web has grown isphenomenal, and it did not take long for people to start creating Web pages for all different kinds ofpurposes—from individuals setting up homepages about their family or hobbies to big corporationssetting up vast sites that highlighted their products and services

Trang 38

As the Web grew, people who were building these pages wanted more control over how their pagesappeared In order for this to happen, the W3C (which stands for World Wide Web Consortium, the bodyresponsible for creating the HTML specifications), and the people writing the Web browsers (in particularNetscape and Microsoft) introduced new markup Soon there was markup allowing you to specifydifferent fonts, colors, backgrounds, and so on It was in catering to these new requirements of the Webthat new versions of HTML were spawned.

Consider the possibilities: You could take the first brief Web page from earlier in the chapter, specify thetypeface (or font) you want the page to use, change the color of the text in the main paragraph to red, andindicate that some of the text should be in a bold or italic font The whole of the page could also have avery light gray background, in which case it would look something like Figure 1-4

Figure 1-4

This page is still not going to be a hot contender for any design awards, but it shows that you do havecontrol over how the page looks The typeface has been specified, the paragraph is in red text (which youcan’t see from the black and white figure), and it also features bold and italic text

Here is the code for this example (eg01_eg02.htm):

<font face="arial" color="#CC0000">

<p><b>Acme Toys</b> has been making toys for popular cartooncharacters for over 50 years One of our most popular customerswas <i>Wile E Coyote</i>, who regularly purchased our items to helphim catch Road Runner.</p>

</font>

</body>

</html>

Trang 39

First you should note how parts of the text in the paragraph are in bold and italic typefaces The<b>

element is used to indicate the parts of the text that should be in a bold typeface, and an<i>element isused to indicate which parts should be in italics

The most obvious changes to this page, however, are the<font>elements, which specify that the pageshould be displayed in an Arial typeface If the book were in color you would also notice that theparagraph text is in red (This is just one way of indicating which typeface to use, and you will meet apreferred way in Chapter 9.)

Attributes Tell Us About Elements

In order to specify which font you want to use, the<font>element must carry an attribute calledface

It is important to take a moment now to look at attributes, as they are used a lot in HTML

You can use attributes to say something about an element They appear on the opening tag of the element that carries them All attributes are made up of two parts: a name and a value:

The name is the property you want to set For example, the<font>element in the examplecarries an attribute whose name isface, which you can use to indicate which typeface you wantthe text to appear in

The value is what you want the value of the property to be The first example was supposed to use

the Arial typeface, so the value of thefaceattribute isArial

The value of the attribute should be put in double quotation marks, and is separated from the name bythe equals sign You can see that a color for the text has been specified as well as the typeface in this

<font>element:

<font face="arial" color="#CC0000">

This illustrates that elements can carry several attributes, although an element should never have twoattributes of the same name

You might have noticed that the value of thecolorattribute is#CC0000, which might seem a strangeway to describe a red, but there are many shades of red and this notation allows us to describe lots ofdifferent reds Don’t worry about it for now; you learn all about color in Chapter 4 As you will see in thatchapter, colors on the Web can be described using six-digit codes preceded by the pound (or hash) sign#

and the characters after it represent the amount of red, green, and blue used to make up the color Thesame notation is used for thebgcolorattribute on the<body>element, which indicates that we wantthe background of our page to be a very light gray (Appendix D also lists over 100 color names and theircorresponding numbers.)

All attributes are made up of two parts, the attribute’s name and its value, separated

by an equal sign Values should be held within double quotation marks.

Trang 40

Keeping Style Separate from Structure and Semantics

By the time the W3C had released version 3 of HTML, it contained all kinds of markup that indicatedhow a document should look Markup that indicates how the document should look, rather than

describing the structure or content of the document, is known as stylistic markup The<font>,<b>, and

<i>elements, and thecolorandbgcolorattributes are examples of stylistic markup

You can contrast stylistic markup with the markup from the first example The first example contained

only structural markup indicating the structure of a document (the paragraphs and headings), and semantic

markup telling us something about the content of the data, like the<title>element But that firstexample also looked plain and gray, which is why the stylistic markup was introduced

Stylistic markup made Web pages look more interesting, but the result was that even the very basic Webpages became longer and more complicated Furthermore, the markup no longer just described thestructure and contents of the document Whereas in the first example the markup added informationabout the document’s structure and its content only, the second example used markup to describe howthe document should look

You see, a heading is a heading whether it is printed in black and white or shown on a Web browser inbold, red, Arial typeface Similarly, a title is the title of a document, no matter whether it is on the frontpage of a document or at the top of each individual page But when you use markup to indicate whatshould be in an Arial typeface, 12 pt in size, red in color, and bold, you are saying how the documentshould look rather than just saying “this is a paragraph” or “this is a heading.”

Introducing CSS

By the time the W3C released version 4 of HTML, it had decided to move away from including stylistic

markup in HTML and instead created a separate language with which to style documents called cascading

style sheets or CSS CSS uses rules to say how a document should appear (rather than elements and

attributes) These rules usually live in a separate document rather than in the page with the content, thus

keeping the presentation rules separate from the structural and semantic markup

Each CSS rule is made up of two parts:

A selector to indicate which elements a rule applies to.

Declarations indicating the properties of an element you want to change, such as its typeface or

color, and the value you want this to be, such as Arial or red Declarations are very similar toattribute names and their values

Figure 1-5 shows an example of a CSS rule that would apply to the<body>element of a document.Because it is used on the<body>element, it also applies to all of the elements between the opening

Figure 1-5

Ngày đăng: 03/07/2014, 04:20