1. Trang chủ
  2. » Mẫu Slide

Stylin' with CSS: A designer's guide, second edition

313 9 0

Đ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

Định dạng
Số trang 313
Dung lượng 12,1 MB

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

Nội dung

Things get more complex if we want to add a liquid center to our three-column layout, where the content area changes width as the browser window is resized, but the side columns remain[r]

Trang 2

Stylin’ with CSS:

A Designer’s Guide

Second Edition

C H A R L E S W Y K E - S M I T H

Trang 3

Stylin’ with CSS: A Designer’s Guide, Second Edition

Find us on the Web at: www.newriders.com

To report errors, please send a note to errata@peachpit.com

New Riders is an imprint of Peachpit, a division of Pearson Education

Copyright © 2008 by Charles Wyke-Smith

Project Editor: Michael J Nolan

Development Editor: Marta Justak

Production Editor: Hilal Sala

Proofreader: Doug Adrianson

Indexer: Julie Bess

Compositor: David Van Ness

Book design: Aren Howell

Notice of Rights

All rights reserved No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher For information on getting permission for reprints and excerpts, contact permissions@peachpit.com

Notice of Liability

The information in this book is distributed on an “As Is” basis without warranty While every precaution has been taken in the preparation of the book, neither the author nor Peachpit shall have any liability to any person or entity with respect to any loss or damage caused or alleged

to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it

No such use, or the use of any trade name, is intended to convey endorsement or other affi tion with this book

Trang 4

For Jemma and Lucy

Trang 5

A book like this is never a solo effort and thanks go to publisher Nancy Ruenzel at Peachpit for encouraging me to write this second edition, Editor-in-Chief Nancy Davis for her insightful advice and good humor, and to Michael Nolan, New Riders’ Acquisition Editor for once again setting everything in motion On the production team, I want to thank my development editor, Marta Justak, for her input and direction as we thrashed the book into shape; production editor, Hilal Sala, for her grace and constant encouragement; David Van Ness, the compositor, for his care in laying out the pages, and Doug Adrianson for his detailed proofi ng A special thanks goes to

my technical reviewer, Virginia DeBolt, for her skilled review of my code and the related text

Thanks next to all the readers of the fi rst edition who wrote to me with ideas and feedback I hope that I understood and have deliv-ered on what you were looking for, and do keep on writing to me with your suggestions and sending me the URLs of your sites

At Benefi tfocus.com where I work, I want to thank my boss, VP of Enterprise Product Strategy Nancy Sansom, for giving me the fl ex-ibility I needed to write this book, for her constant energy and guid-ance in my work, and for giving me the opportunity to work for a really amazing company I also want to thank Benefi tfocus’ CEO, Shawn Jenkins, and COO, Jerry Lepore, for their support and leader-ship, and for building and running the best organization I have ever worked in

A big shout-out goes to the talented and creative members of the User Experience Group team who I am privileged to manage and learn from—they are Brad Bonham, Darin Cavenaugh, Daniel Nadeau, Michael Rosier, Mike Attisano, Leah Giorlando, Tony Malatanos, and Matt Megrue I also really enjoy the challenge of being part of the Product Strategy team, which includes the inven-tive minds of Raymond Minnis, Nathan Reel, John “Coach” Wilson, Kinsey Rawe, and Mike Fullan Let’s next mention some other people who make working at Benefi tfocus fun and exciting: Nina Sossamon-Pogue, Andrew Alberico, Elena Tudor, Will Deupree, Manon Husman, Kelli Hicks, Tracey Snyder, Annmarie Fini, Michelle Pagel, Nate DaPore, Randy Chitwood, Glenn Miller, Heather

Norton, Rebecca Laney, Paul Sparrow, Robert Moss, Don Taylor, and Jonathan Chandler—I appreciate your inspiration, friendship, and support every day

Trang 6

I’ll save the last and biggest thank you for my wife, Beth She really stepped up to help me with this book and her graphic design and

writing skills are on every single page She checked my grammar,

clarifi ed my explanations, and re-punctuated my paragraph-length run-on sentences that I like so much She also laid out the diagrams,

designed the Stylin’ with CSS Web site that is featured in Chapter 7

(I wouldn’t have made my photo so big, but otherwise, nice job,

Sweetie!), and generally ensured that complete and coherent ters went to the editor the fi rst time This book is whatever it is in

chap-large part due to her unceasing attention to detail and constructive suggestions for improvements Thanks, my love

Finally, to my two lovely daughters, Jemma and Lucy, I want to say

you both have been incredibly patient and understanding while

your daddy has been writing, and now we can go and get ice cream again on Saturday mornings!

— Charles Wyke-Smith Charleston, South Carolina, November 14, 2007

AC K N O W LE D G E M E NT S

Trang 7

This page intentionally left blank

Trang 8

About the Author

Charles Wyke-Smith has been creating Web sites since 1994 and

is currently Director of User Experience at Benefi tfocus.com (www.benfi tfocus.com), a South Carolina software company that provides online benefi ts enrollment for over 40 million people through the nation’s major healthcare insurance companies, and that also develops consumer healthcare Web sites, including ICyou.com and iHealthfocus.com

In 1986, he started PRINTZ Electronic Design, which was the fi rst all-computerized design house in San Francisco Charles has worked

as a Web design consultant for such companies as Wells Fargo, ESPN Videogames, and the University of California, San Francisco An accomplished speaker and instructor, he has taught multimedia and interface design and spoken at many industry conferences

Charles lives in Charleston, SC, with his wife, Beth, and two daughters In his spare time, he composes and records music in his home studio

Photo – Lowell Downey, Art and Clarity, Napa, CA

Trang 9

The Times They Are A-Changing • 7

The Way We Were • 7The Future Just Happened • 9

XHTML and How To Write It • 10

XHTML—The Rules • 11

An XHTML Template • 16Marking Up Your Content • 18Document Flow—Block and Inline Elements • 18Document Hierarchy: Meet the XHTML Family • 24

C HAP TE R 2 : H O W C S S W O R K S • 26

The Three Ways to Style Your Document • 28

Inline Styles • 28Embedded Styles • 29Linked Styles • 30

Anatomy of a CSS Rule • 32 Writing CSS Rules • 33 Targeting Tags Within the Document Hierarchy • 34

Using Contextual Selectors • 34Working with Child Selectors • 38Adding Classes and IDs • 39Introducing IDs • 43The Difference Between IDs and Classes • 44Specialized Selectors • 45

Summary of Selectors • 48

Pseudo-Classes • 49

Anchor Link Pseudo-Classes • 49Other Useful Pseudo-Classes • 51

Trang 10

Pseudo-Elements • 52 Inheritance • 54 The Cascade • 55

Sources of Styles • 55The Cascade Rules • 56

Rule Declarations • 60

Numerical Values • 60Color Values • 63

C HAP TE R 3 : S T Y LI N ’ FO NT S AN D TE X T • 6 6

Specifying Fonts in CSS • 68

Introducing Font Collections • 69

Exploring Font Families • 71

Using Embedded Styles (for Now) • 73Setting the Font Family for the Entire Page • 74

Sizing Fonts • 76

Inherited Styles in Nested Tags • 79

Font Properties • 81

Font-Style Property • 81Font-Weight Property • 82Font-Variant Property • 83The Font Property Shorthand • 84

Text Properties • 84

Text-Indent Property • 86Letter-Spacing Property • 88Word-Spacing Property • 89Text-Decoration Property • 90Text-Align Property • 91Line-Height Property • 92Text-Transform Property • 93Vertical-Align Property • 94

Using Font and Text Styles • 96

C O NTE NT S

Trang 11

S T Y LI N ’ W ITH C S S

x

C HAP TE R 4 : P O S ITI O N I N G E LE M E NT S • 10 0

Understanding the Box Model • 102

The Box Border • 103The Box Padding • 106The Box Margins • 106Collapsing Margins • 108

How Big Is a Box? • 109 Floating and Clearing • 114

The Float Property • 114The Clear Property • 116

The Position Property • 120

Static Positioning • 120Relative Positioning • 121Absolute Positioning • 122Fixed Positioning • 123Positioning Context • 124

The Display Property • 127 Positioning/Display Example • 128

C HAP TE R 5 : B A S I C PAG E L AYO U T • 134

Some Multi-Column Layouts • 136 Introducing Stylib—the Stylin’ Library • 139 Width Matters • 139

Floated Versus Absolutely-Positioned Layouts • 140

A Simple Two-Column Fixed-Width Layout • 141Know Your Inner Div • 146

Prevent Unwanted Overfl ow • 146Freely Style Your Inner Divs • 147Styling the Text • 147

A Simple Two-Column Liquid Layout • 147

Use a Little Constraint • 149

To Float or Not To Float? • 150

A Three-Column Fixed-Width Layout • 151

A Three-Column Liquid Layout • 155

Trang 12

Making All the Columns the Same Length • 159

Faux Columns • 160Programmatically Extend Columns (and Round Their Corners!) • 164

An Absolutely-Positioned Layout • 168

C HAP TE R 6 : D E S I G N I N G I NTE R FAC E C O M P O N E NT S • 174

Styling Tables • 176 Styling Forms • 189

How Forms Work • 189Form Markup • 190Form Styling • 198

Styling Lists and Menus • 205

Lists • 205Creating CSS-Based Menus • 217

C HAP TE R 7 : B U I L D I N G W E B PAG E S • 230

The Stylin’ Site • 232 Setting Up the Folder Structure • 234 Creating the Site Architecture • 236

Copy the Required CSS Files from the Library • 239The @import Rule • 239

The Text and Colors Style Sheet • 243The Page Markup • 248

The Background Images • 251The Drop-Down Menus • 254The Transparent Sidebar Panel • 257Adding the Registration Form • 262Styling the Text • 265

Conclusion • 271APPE N D I X A : X H TM L TAG S • 272

APPE N D I X B : C S S P R O PE RTI E S • 276

I N D E X • 29 0

C O NTE NT S

Trang 13

It’s hard to believe it’s been over three years since I wrote the fi rst

edition of Stylin’ with CSS In the intervening time, I have been

involved in the development of numerous Web sites and have

fi ne-tuned the way I use CSS in the process I intended to make

a few small adjustments to this book for the second edition to cover IE7 and generally bring it up to date, but I ended up making numerous improvements to the fi rst three chapters and completely rewriting the rest of the book What should have taken weeks took almost a year

The changes I have made refl ect the inevitable improvement to the skills of anyone who works constantly with CSS, and these changes also more deeply address two skills that all programmers need to master: to avoid rewriting code that they have previously written elsewhere, and to learn to write code in the most economi-cal way possible Ways in which you can achieve these two worthy goals in your own work are presented throughout this new edition

Stylib that contains all kinds of interface elements, organized as CSS

code with its associated XHTML markup I have included this library with the downloadable code examples for the book on the Web site, www.stylinwithcss.com It’s at an early stage but already contains many useful components that have saved me hours of development work, and I hope will do the same for you I will continue to publish new code for this library and make it available for download

The other goal, economy of code, is another theme that runs

through this new edition For example, by adding a style at the highest possible level in the document hierarchy, that style can then infl uence numerous elements I often see CSS style sheets that declare the same font-family on every heading and paragraph, but adding that font-family to the top-level body tag means you

Trang 14

only write and maintain that style in one place The underlying

concept is a programming maxim known as DRY, meaning Don’t

Repeat Yourself We will look at many other examples like this in

the chapters ahead

Master the Key Techniques

I’ve also come to realize that truly understanding just a few

impor-tant CSS techniques can turn a struggling newbie into a competent CSS journeyman These techniques include correctly using the posi-tioning and display properties, and understanding how fl oating and clearing really work I have dedicated Chapter 4 to explaining these aspects of CSS and showing simple examples that illustrate how to

apply them in practice Anyone who has dabbled in CSS and wants

to take their skills to the next level may fi nd this chapter to be very

enlightening—I certainly hope so

Use the Right Tools

So before we launch into to the book proper, I want to explain how

to get set up to work so that you can in the shortest possible time

achieve page layouts that will work across the largest number of

browsers

You need a good code editor to write your code, and an FTP client

to move your fi les to the Web server Adobe Dreamweaver (about

$400) integrates both of these and is my programming tool of

choice The code view is very helpful, color coding the different

elements of your code, indicating syntax errors, and guessing what you are typing so you can auto-complete many common code

elements after typing the fi rst couple of letters The design view,

which attempts to render the page like a browser, is also useful if

only because you can click any displayed element and immediately

be jumped to related part of the code in the code view There are

also many low- and no-price editors and FTP clients out there that offer similar features if you don’t want to make the investment in

Dreamweaver However, what ultimately matters is not what tools

you use to write and upload your code, but what your Web pages

look like in the user’s browser

I NT R O D U C TI O N

Trang 15

S T Y LI N ’ W ITH C S S

xiv

Only Four Browsers Matter

You may be surprised when I tell you that there are only four ers you really need to care about testing your work in:

brows-• Firefox

• Safari

• Internet Explorer 7

• Internet Explorer 6 That is because these four browsers account for over 95 percent

of all Web users, with none of the others having more than about

a 2 percent market share (source: my averaging of Wikipedia’s listing

of many browser statistics sites at http://en.wikipedia.org/wiki/Usage_share_of_web_browsers)

One of these four browsers is IE6 which, despite its rendering bugs and poor support for many newer CSS properties, is currently still

a dominant browser, although slowly (too slowly) falling out of use

The other three browsers are all what are commonly known as SCBs,

which stands for Standards Compliant Browsers This means they closely comply with the browser standards recommended by the World Wide Web Consortium They all quite accurately render virtu-ally all of CSS2 and many CSS3 properties (CSS2 and CSS3 can be thought of as versions of CSS and you will learn more about them as

we proceed.) Generally, there is little difference between them in the way that they render valid CSS-styled XHTML

You could include Netscape in the above list, even though at best its market share is in single digits, but because Netscape and Firefox are both built on the Mozilla rendering engine, if your page works

in Firefox, you’re almost sure to see the same result on Netscape So really, testing and tweaking to the point where you get a satisfac-tory result on just the four browsers listed above enables you to be confi dent that virtually everyone will see your site as you intended

I don’t even bother testing in IE5.5 any more; it has less than half a percent usage now, and anyone who is running an eight-year-old browser probably has bigger technical problems than how your site renders

My advice is defi nitely not to use IE6 as a development browser, but to develop using one of the three SCBs above, and then test and make any adjustments for IE6 only after your page is in advanced state on your SCB of choice Actually, I’ll go further, and say that I

Trang 16

strongly advise you to view your pages during development using the Firefox browser I say this because I fi nd that overall Firefox is the most standards-compliant of all the SCBs Also, you can install the Web Developer Toolbar add-on on Firefox, which allows you to: easily validate your XHTML and CSS without uploading to a server; turn style sheets on and off; view the outlines of the XHTML elements on your page so you can accurately see if the elements are laying out on the page as you intend; and use its numerous other useful and time-saving tools Quite simply, if you don’t have the Web Developer Toolbar installed you are probably wasting a lot of development time Also add the Firebug add-on for some handy code debugging tools, and you are ready to work like a pro Firefox and these two add-ons can be downloaded for free at www.getfi refox.com.

Download My Code, Don’t Retype It

Finally, in a book like this, there are bound to be some errors, although a concerted effort has been made to review this book

in great detail before it went to press However, the code is all mine, and while I have tested every line of it, I ask you to do two things First, if you want to use code shown in the book, don’t copy it from the pages Besides being a waste of time as all the code can be downloaded in seconds from the book’s Web site, www.stylinwithcss.com, I will also fi x any errors that are found and update the downloadable fi les

… and Don’t Forget to Write

Second, if you do fi nd errors, please use the email form on the

Stylin’ with CSS site to let me know and I will publish them on the

site I also welcome your comments and suggestions, so do take

a minute to drop me a line after you get through with the book I will try to reply to everyone who writes, and I’ll certainly also try

to answer any questions you may have I have limited time to help solve specifi c code problems, but if you really want to send me CSS

to look at, please embed it in the head of the XHTML document and put any images on your own server with absolute URLs to them;

then email the XHTML document to me and I can just pop the page open and take a quick look

Finally, thanks for buying this book I hope it’s a huge help to you

Trang 17

C H A P T E R 1

XHTML: Giving Structure to Content

Trang 18

S T Y LI N ’ W ITH C S S

S T Y LI N ’ W ITH C S S is all about building standards-compliant Web sites in the most effi cient, streamlined way possible, while making those sites accessible to the widest audience and easy

to update Web standards are simply a set of recommendations

by the World Wide Web Consortium If all browser

manufac-turers and all Web programmers followed them, so the theory

goes, all Web pages would look and behave the same in every browser Nice idea, but hard to realize.

When I wrote the fi rst edition of Stylin’ in late 2004, the Web

standards movement was gaining massive momentum Today, most new Web sites are being programmed to meet Web stan- dards, and the Web is a better place because of it.

The Web standards advocates who drove this movement

have made the Web a better and more predictable place

They worked with browser manufacturers to ensure that new browsers interpret the three primary interface programming

languages (XHTML, CSS, and JavaScript) in the ways

recom-mended by the W3C, instead of each one using custom tags

and features in the self-interest of competitive advantage.

Trang 19

Several other browsers do a good job of interpreting CSS, ing to the W3C recommendations; the latest versions of Firefox and Opera on PC, and Safari and Firefox on Macintosh, all render XHTML styled with CSS2 in a remarkably consistent manner, but Microsoft Internet Explorer 6 (IE6) has numerous unimplemented features and buggy implementations of others.

accord-Microsoft Internet Explorer 7 (IE7), released in October 2006, is

a big improvement with regard to Web standards over IE6, and I had hoped that there would be rapid switchover from IE6 to IE7 However, according to thecounter.com, IE6 was still used by about

50 percent of all Web surfers as of July 2007

Even Today, IDWIMIE

Anyway, as a result of IE6’s refusal to die a rapid death, I still sometimes have to mention a CCS feature and tell you IDWIMIE (pronounced id-wimmy)—It Doesn’t Work In Microsoft Internet Explorer

For some of Internet Explorer’s (and other older browsers)

short-comings, there are workarounds known as hacks—the nonstandard

use of CSS to fool particular browsers into seeing or ignoring certain styles It’s tedious and time-consuming to create hacks, but as long

as IE6 is around, the hacks must continue

For us Web site designers and the visitors to the sites we create, Web standards offer the prospect of sites displaying and behaving consistently in every browser, on every platform We’re not there yet, but the days of every browser supporting a different feature set, with all the resultant inconsistencies that can make cross-browser/cross-platform Web development slow and frustrating, are, it seems, almost over Web standards are clearly here to stay

Every so often I’ll mention CSS2 or

CSS3 These terms simply refer to

a specifi c version of the CSS

stan-dard As with any technology, CSS

continues to be refi ned CSS2 is now

almost fully implemented in most

browsers; CSS3 has been defi ned

for some time, but is supported

only partially by Firefox and Opera

and barely at all by IE7 More on

both later.

Every so often I’ll mention CSS2 or

CSS3 These terms simply refer to

a specifi c version of the CSS

stan-dard As with any technology, CSS

continues to be refi ned CSS2 is now

almost fully implemented in most

browsers; CSS3 has been defi ned

for some time, but is supported

only partially by Firefox and Opera

and barely at all by IE7 More on

both later.

I’ll always indicate if this applies

only to IE6 or to both IE6 and 7.

I’ll always indicate if this applies

only to IE6 or to both IE6 and 7.

Trang 20

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 5

Content, Structure, and Presentation

So, following the W3C’s Web standards recommendations, Stylin’

shows you how to publish content by defi ning its structure with XHTML and then defi ning its presentation with CSS.

1 Content is the collective term for all the text, images, videos,

sounds, animations, and fi les (such as PDF documents) that you want to deliver to your audience

2 XHTML (eXtensible HyperText Markup Language) enables you

to defi ne what each element of your content is Is it a heading

or a paragraph? Is it a list of items, a hyperlink, or an image?

You determine this by adding XHTML markup to your content

Markup comprises tags (the tag name is enclosed in angle brackets < >) that identify each element of your content You

create an XHTML element (hereafter just called an element) by

either surrounding a piece of content with an opening and a closing tag like this

<p>This tag defi nes the text content as a paragraph</p>

or, for content that is not text (an image, in this example), by using a single tag

<img src="images/fi do.gif" alt="a picture of my dog" />

This chapter focuses on XHTML and how to use it, but the most important thing to know right now is this: XHTML defi nes a

document’s structure.

3 CSS (Cascading Style Sheets) enable you to defi ne how each

marked-up element of your content is presented on the page Is that paragraph’s font Helvetica or Times? Is it bold or italicized?

Is it indented or fl ush with the edge of the page? CSS controls the formatting and positioning of each of the content elements

To format the size of the text in a paragraph, I might write

p {font-size: 12px;}

which would make the text 12 pixels high Almost this entire book is dedicated to teaching you CSS, but the most impor-tant thing to know right now is this: CSS defi nes a document’s

presentation.

Strictly speaking, XHTML and CSS

aren’t programming languages, but

mechanisms for marking up and

styling content respectively, so I am

using the term “language” in a

gen-eral way here.

Strictly speaking, XHTML and CSS

aren’t programming languages, but

mechanisms for marking up and

styling content respectively, so I am

using the term “language” in a

gen-eral way here.

This img tag also has two attributes

for the image source and alternative

text respectively—see the sidebar

“What Are Attributes?” to learn more.

This img tag also has two attributes

for the image source and alternative

text respectively—see the sidebar

“What Are Attributes?” to learn more.

Trang 21

S T Y LI N ’ W ITH C S S - CHAP TE R 1

6

What Are Attributes?

Attributes can be added to a tag and can help further defi ne that tag Each attribute comprises two parts: the attribute name and the attribute value, in the format name="value" For example, this image tag

<img src="images/fi do.gif" alt="a picture of my dog" />

has two attributes: the image source, which has the value "images/fi do.gif" that defi nes its relative location on the server, and an alternative text description, which has the value "a picture of my dog" that appears on-screen if the image fails to load, or that could be read aloud by a screen reader Both these attributes are part of the structure of the document.Before Web standards, it was common practice to load up tags with addi-tional presentational attributes, such as text sizes and colors Now, we can move all presentational information into the style sheet and thereby greatly reduce the complexity of our markup and use only attributes that defi ne document structure

Providing a means of separating a document’s structure from its presentation was the core objective in the development of Web standards, and it is key to development of content that is both por-table (can be displayed on multiple devices) and durable (ready for the future)

The Top 10 Benefi ts of Standards-Based Coding

You may be wondering “Why should I bother to change the way I have been marking up pages for years?” Here are 10 great reasons to adopt standards-based coding practices:

1 Deliver to multiple user agents The same piece of marked-up content is readily deliverable in a wide variety of

user agents, the collective name for devices that can read XHTML, such as browsers, handhelds like smartphones, cell phones with browsers, and screen readers that read text for the sight impaired You simply create a different style sheet for each device type, or let the XHTML display as is

2 Improve performance Pages are much lighter (smaller in fi le size) and therefore download faster, because your

content only needs minimal structural markup We can now replace all of the presentational markup we used to load into the tags in every page of a site with a single style sheet As you will see, a single style sheet can defi ne the presentation of an entire site, and the user’s browser only needs to download it once

3 Serve all browsers With a little effort, you can have your pages degrade nicely in older browsers, so all users get

the best experience possible with their available technology

4 Separate content and presentation You can modify, or entirely change, either the content or the presentation

(read: design) of your site without affecting the other

(continued on next page)

Trang 22

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 7

The Times They Are A-Changing

Web standards are now quite widely adopted Designers are moving away from using tables to lay out their pages and using clean struc-tural markup, free of nested tables, spacers, and numerous <br>

(line breaks) and &nbsp; (non-breaking spaces) These techniques were used only to force everything into the right place and had no meaning with respect to the content

Here’s an example of the old way of doing things:

The Way We Were

Take a look at this classic example of how Web sites were coded before Web standards became widely adopted This is a snippet of markup from the Microsoft home page, July 1, 2004

<table cellpadding="0" cellspacing="0" width="100%"

height="19" border="0" ID="Table5">

<tr>

<td nowrap="true" id="homePageLink"></td>

The Top 10 Benefi ts of Standards-Based Coding (continued)

5 Build fl uid pages It’s easier to code for varying quantities of dynamic content within your pages For example,

it’s much easier to create pages that can accommodate varying numbers of items in a given listing or menu of your

e-commerce store

6 Confi rm your code is correct Validation services for XHTML and CSS can be used during development to report

instantly on errors in your coding This provides faster debugging, and the assurance that a page is truly completed

when it both displays correctly on-screen and passes validation

7 Streamline production Production is more effi cient It’s too easy for you (the designer) to be sidetracked into

content management, because you are the only person who knows where the content goes in the mass of

presenta-tional markup You end up being the one to add it—a tedious job and probably not what you were hired to do By

adopting standards-based practices, you can provide simple markup rules to the content team and work in parallel

on the presentational aspects, knowing their content and your design will marry seamlessly down the line

8 Distribute content more easily Distributing your content for third-party use is much easier because the content is

separate from any specifi c presentation rules, and in many cases, simply not feasible otherwise

9 Make it accessible It’s easier to make your site accessible and meet legal requirements, such as the Americans

with Disabilities Act, Section 508, known colloquially as ADA 508

10 Do less work You write less code, and it’s a whole lot quicker and easier to get the results you want and modify

your work over time

Trang 23

S T Y LI N ’ W ITH C S S - CHAP TE R 1

8

<td><span class="ltsep">|</span></td>

<td class="lt0" nowrap="true" onmouseenter="mhHover('localToolbar', 0*2+2, 'lt1')" onmouseleave="mhHover('localToolbar', 0*2+2, 'lt0')">

<a href="http://go.microsoft.com/?LinkID=508110">MSN Home</a>

</td>

<td><span class="ltsep">|</span></td>

<td class="lt0" nowrap="true" onmouseenter="mhHover('localToolbar', 1*2+2, 'lt1')" onmouseleave="mhHover('localToolbar', 1*2+2, 'lt0')">

<a href="http://go.microsoft.com/?linkid=317769">Subscribe</a>

</td>

<td><span class="ltsep">|</span></td>

<td class="lt0" nowrap="true" onmouseenter="mhHover('localToolbar', 2*2+2, 'lt1')" onmouseleave="mhHover('localToolbar', 2*2+2, 'lt0')">

<a href="http://go.microsoft.com/?linkid=317027">Manage Your Profi le</a></td>

characters of code to create the three

links above the picture

The three links

Trang 24

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 9

The essential code is in green—247 characters out of 956, or less than

26 percent The remaining 74 percent is just gooey chocolate sauce Except for the href attributes, everything inside the tags is presen-

tation and could all be ripped out and converted into a few brief

defi nitions in a style sheet The table is not used to display data; its

purpose is solely to line everything up The rest of the code is mostly concerned with making rollovers work Each link requires the follow-ing information: a class to identify it to JavaScript, a forced nowrap

attribute to keep the words on the link together, and two JavaScript

function calls—yeah, on every link (As an aside, rollovers are easy

to create with CSS and require two simple CSS styles, as you will see later.) Note also that a table cell that contains a nested span with a

class is required to display each tiny vertical line between the links

Microsoft has recently made a decent effort to make its site

more standards-compliant, but if your site’s source (sauce?) code

resembles the above, then read on In the chapter on Interface

Components, you will see how to create a similar navigation

ele-ment with no more markup than a simple un-ordered list After

applying a few CSS rules, the result is a lightweight, easy-to-read,

and most of all, semantically meaningful element that works on any XHTML-capable device, regardless of screen size, or even its capa-

bility to read CSS

The Future Just Happened

Today, with so many browsers and other devices standardizing

around XHTML and CSS, noncompliant Web sites are fi nding that

it is diffi cult to deliver their existing content on these newer devices and browsers Have you seen your home page on a handheld com-

puter lately?

Although bringing your current Web site into the modern age may

take a substantial amount of work, you can console yourself that by following the new Web standards, you can do it once and do it right

If you are starting a new site, you can do it right the fi rst time

In Stylin’, you will learn to future-proof your site by separating the

content from the presentation You do this by marking up your

content with XHTML, and then, using a single line of code, you link

these pages to a separate fi le called a style sheet, which contains the

presentation rules that defi ne how the markup should be displayed.The power of this church-and-state separation is that you can cre-

ate different style sheets for browsers, for handheld devices, for

printing, for screen readers used by the visually impaired, and so

Trang 25

S T Y LI N ’ W ITH C S S - CHAP TE R 1

10

on Many of today’s user agents (types of devices) look for their cifi c type of style sheet For example, smartphones such as RIM’s Blackberrry and Palm’s Treo look for a style sheet defi ned for use by

spe-a hspe-andheld device—spe-and if it is present, use it, thus enspe-abling you to provide a modifi ed or entirely different presentation of the same XHTML on these small-screen devices

Each style sheet causes the content to be presented in the best

possible way for that use, but you only ever need one version of

the XHTML content markup As you will see, an XHTML page can automatically select the correct style sheet for each device or environment in which it is displayed In this way, your write-once, use-many content becomes truly portable, fl exible, and ready for whatever presentational requirements the future may bring its way Note, however, that like any great vision of the future, there are still some current realities that we need to deal with

XHTML and How To Write It

Because CSS is a mechanism for styling XHTML, you can’t start using CSS until you have a solid grounding in XHTML And what, exactly, is XHTML? XHTML is a reformulation of HTML as XML—didja get that? Put (very) simply, XHTML is based on the free-form structure of XML, where tags can be named to actually describe the content they contain; for example, <starname>Madonna</starname>.

This very powerful capability of XML means that in XHTML, where the tag set is already defi ned for you, there is both a set of custom tags for your XHTML content and a second document, known as

a DTD (document type defi nition), to explain how to handle those

tags to the device that is interpreting the XHTML By becoming XML-compliant, XHTML has been able to transcend the limitations

of HTML and can be expanded over time, and can be shared as time Web services between other data systems The DOCTYPE tag at the start of every XHTML Web page makes this critical association between the markup and the DTD

real-XML has been almost universally adopted in business, and the fact that the same X (for eXtensible) is now in XHTML emphasizes the unstoppable movement toward the separation of presentation and content

The rest of this chapter is dedicated to the latest, completely reformulated, totally modern, and altogether more fl exible version

of HTML

You can defi ne which type of device

a style sheet relates to using the

link tag’s media attribute.

You can defi ne which type of device

a style sheet relates to using the

link tag’s media attribute.

If you want more than this rather

simplistic description of XML, check

out the XML tutorial at the SpiderPro

Web site (www.spiderpro.com/bu/

buxmlm001.html).

If you want more than this rather

simplistic description of XML, check

out the XML tutorial at the SpiderPro

Web site (www.spiderpro.com/bu/

buxmlm001.html).

Trang 26

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 11

XHTML—The Rules

Correctly written XHTML markup gives you the best chance that your pages will display correctly in a broad variety of devices for years to come The clean, easy-to-write, and fl exible nature of XHTML pro-duces code that loads fast, is easy to understand when editing, and prepares your content for use in a variety of applications

You can easily determine if your site complies with Web standards—

if your markup is well-formed with valid XHTML, and your style sheet is valid CSS.

Well-formed means that the XHTML is structured correctly

accord-ing to the markup rules described in this chapter

Valid means that that page only uses tags that are defi ned in the

DTD (document type defi nition) that is associated with every ern Web page by the page’s DOCTYPE tag (more on DOCTYPEs later) Certain tags that you may have been used to using in the past are now deprecated, meaning they still work but that a different, and usually more semantically correct, tag is now available for this purpose To encourage you to use the newer tags, which unlike dep-recated tags will still work in the future, deprecated tags are fl agged

mod-as errors by the validator You can check to see if your page meets these two criteria by uploading the page onto a Web server and then going to http://validator.w3.org and entering the page’s URL

Press Submit, and in a few seconds you are presented with either a detailed list of the page’s errors or the very satisfying “This Page Is

Valid XHTML 1.0 Strict!” message (Figure 1.2) CSS can be validated

in the same way at http://jigsaw.w3.org/css-validator

FI G U R E 1 2 This nice message from

the W3C validator almost guarantees

that your page will display

meaning-fully on any XHTML-capable device

If you install the wonderful

Developer’s Toolbar into Firefox, you

can easily validate pages on your

local machine without uploading

them to your web server Download

it from http://chrispederick.com/

work/web-developer/

If you install the wonderful

Developer’s Toolbar into Firefox, you

can easily validate pages on your

local machine without uploading

them to your web server Download

it from http://chrispederick.com/

work/web-developer/

Trang 27

S T Y LI N ’ W ITH C S S - CHAP TE R 1

12

Does My Page Have To Validate?

The W3C validator (jigsaw.w3c.com) exists to enable you to ensure your pages are valid (only use elements and butes as defi ned by the DOCTYPE’s DTD) and well-formed (tags are structured correctly) It’s defi nitely good practice to attempt to write pages that pass validation, and some would say that your pages must pass validation What’s undeni-

attri-able is that the validator can instantly fi nd common errors in your code that might otherwise take you hours to fi nd.However, just because a page doesn’t validate doesn’t necessarily mean it won’t display the way you intend in current Web browsers What future devices or other non-browser devices might do with such a page is not so certain

My recommendation is to validate every page you create and take heed of the errors the validator displays Close any tags it determines are left open, for example, and recode tags that it determines are being incorrectly nested (such as

block elements inside inline elements) In short, you do want to ensure that your page is well-formed However, valid is

Looking forward to the email I’m going to get on this one

Here’s the complete (and mercifully, short) list of the coding ments for XHTML compliance:

require-1 Declare a DOCTYPE The DOCTYPE goes before the opening

html tag at the top of the page and tells the browser whether the page contains HTML, XHTML, or a mix of both, so that it can correctly interpret the markup There are three main DOCTYPEs that let the browser know what kind of markup it is dealing with:

Strict: All markup is XHTML-compliant.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Transitional: This states that the markup is a mix of XHTML

and deprecated HTML Many well-established sites are rently using this one, so their old HTML code can exist happily

cur-in the document alongside the XHTML they are now addcur-ing

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

For a list of deprecated tags that you

should abandon and replace with

their XHTML equivalents, refer to the

About.com Web site

(http://web-design.about.com/od/htmltags/a/

bltags_deprctag.htm).

For a list of deprecated tags that you

should abandon and replace with

their XHTML equivalents, refer to the

About.com Web site

(http://web-design.about.com/od/htmltags/a/

bltags_deprctag.htm).

There are other fl avors of

DOCTYPES, and you can read about

them at http://www.oreillynet.com/

pub/a/javascript/synd/2001/08/28/

doctype.html?page=1.

There are other fl avors of

DOCTYPES, and you can read about

them at http://www.oreillynet.com/

pub/a/javascript/synd/2001/08/28/

doctype.html?page=1.

Trang 28

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 13

Frameset: This is the same as transitional but in this case

frames, which are deprecated under XHTML, are OK, too

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"

"http://www.w3.org/TR/html4/frameset.dtd">

It is important to specify a DOCTYPE Browsers that don’t see a DOCTYPE in the markup assume that the site page was coded for browsers developed long before Web standards My recom-mendation is that if you are building a site from scratch, and can therefore avoid deprecated or abandoned tag attributes, such as FONT and COLOR, use the XHTML Strict DOCTYPE listed previously

When encountering a page without a DOCTYPE, many

brows-ers go into what is known as Quirks mode, a

backwards-com-patibility feature supported by Mozilla, Internet Explorer 6 for Windows, and Internet Explorer 5 for Macintosh

In Quirks mode, the browser functions as if it has no knowledge

of the modern DOM (document object model) and pretends it has never heard of Web standards This ability to switch modes depending on the DOCTYPE, or lack thereof, enables browsers

to do the best possible job of interpreting the code of both dards-compliant and noncompliant sites

stan-Note that for some weird reason, the DOCTYPE tag does not need

to be closed with a slash and DOCTYPE is always in caps This entirely contradicts XHTML rules 4 and 7 below Go fi gure

2 Declare an XML namespace Note this line in your new html

tag Here’s an example:

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

When a browser is handling an XHTML page and wants to know what’s in the DTD, which lists and defi nes all the valid XHTML tags, here’s where it can fi nd it: buried away on the servers of the WC3

In short, the DOCTYPE and namespace declarations ensure that the browser interprets your XHTML code as you intended

3 Declare your content type The content type declaration goes

in the head of your document, along with any other meta tags you may add The most common is

<meta http-equiv="Content-type" content="text/html;

charset=iso-8859-1" />

If you copy a DOCTYPE or

namespace from some other site,

make sure that the URL is absolute

(that is, it starts with http:// followed

by a complete path to the

docu-ment) Some sites (including W3C,

of course) host their own DOCTYPE

and namespace fi les, so they can

use relative URLs to them But if you

use these URLs as is, with a different

server that doesn’t host these fi les,

your pages may behave

unpredict-ably because the URLs aren’t

point-ing at anythpoint-ing.

If you copy a DOCTYPE or

namespace from some other site,

make sure that the URL is absolute

(that is, it starts with http:// followed

by a complete path to the

docu-ment) Some sites (including W3C,

of course) host their own DOCTYPE

and namespace fi les, so they can

use relative URLs to them But if you

use these URLs as is, with a different

server that doesn’t host these fi les,

your pages may behave

unpredict-ably because the URLs aren’t

point-ing at anythpoint-ing.

You can learn more about Quirks

mode at the Dive into Mark Web site

(http://diveintomark.org/archives/

2002/05/29/quirks_mode).

You can learn more about Quirks

mode at the Dive into Mark Web site

(http://diveintomark.org/archives/

2002/05/29/quirks_mode).

Because the DOCTYPE (and the XML

namespace and content type

dis-cussed in items 2 and 3) are a pain to

type, they are in the page templates

on the Stylin’ Web site

(www.stylin-withcss.com) You can use these as

a starting point for your own XHTML

documents Just pick whichever

of the three (Strict, Transitional, or

Frames) DOCTYPEs you want to use.

Because the DOCTYPE (and the XML

namespace and content type

dis-cussed in items 2 and 3) are a pain to

type, they are in the page templates

on the Stylin’ Web site

(www.stylin-withcss.com) You can use these as

a starting point for your own XHTML

documents Just pick whichever

of the three (Strict, Transitional, or

Frames) DOCTYPEs you want to use.

Trang 29

S T Y LI N ’ W ITH C S S - CHAP TE R 1

14

This simply states what character coding was used for the ment ISO-8859-1 is the Latin character set, used by all standard

docu-fl avors of English If your next site is going to be in Cyrillic

or Hebrew, you can fi nd the appropriate content types on Microsoft’s site (http://msdn.microsoft.com/workshop/author/dhtml/reference/charsets/charset4.asp)

4 Close every tag, whether enclosing or nonenclosing Enclosing

tags have content within them, like this

<p>This is a paragraph of text inside paragraph tags To

be XHTML-compliant, it must, and in this case does, have

a closing tag.</p>

Nonenclosing tags do not go around text but still must be closed, using space-slash at the end, like this

<img src="images/siamese.jpg" alt="My cat" />

The space before the slash isn’t required in modern browsers, but I always add it as it’s easier to see that the tag is correctly closed

5 All tags must be nested correctly If a tag opens before a

pre-ceding one closes, it must be closed before that prepre-ceding one closes For example:

<p>It’s <strong>very important</strong> to nest tags correctly.</p>

Here, the strong tag is correctly placed inside the <p>; it closes before the containing p tag is closed A tag enclosed inside

another in this way is said to be nested.

This is wrongly nested

<p>The nesting of these tags is <strong>wrong.</p></strong>

Multiple elements can be nested inside a containing element; a list nests multiple li elements inside a single ul or ol element, like this:

Trang 30

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 15

Because CSS relies on proper nesting in order to target styles

to elements, you have to get this right Use the W3C validator for confi rmation that all tags are correctly nested and therefore your document is well-formed

6 Inline tags can’t contain block level tags Block-level elements,

such as p (paragraph) and div (division), automatically organize themselves one under the next down the page If you have two paragraphs, the second paragraph appears by default under the previous one—no line breaks are required By contrast, inline tags, such as a (anchor, a hyperlink) and em (emphasis, usually displayed as italics) occur in the normal fl ow of text, and don’t force a new line

We discuss block and inline elements in detail later in Chapter

4, but for now, just remember that if you nest a block element, such as a paragraph p, inside an inline element, such as a link a,your code won’t validate

Also, some block-level elements can’t contain other block-level elements either; for instance, an h1-6 (heading) tag can’t con-tain a paragraph Besides using validation, you can let common sense be your guide to avoid these problems You wouldn’t put

an entire paragraph inside a paragraph heading when you are writing on paper or in Word, so don’t do illogical things like that

in your XHTML either, and you won’t go far wrong

7 Write tags entirely in lowercase Self-explanatory—no capital

letters at all I’ve always done this myself, but if you haven’t, the days of P are over Now it has to be p

8 Attributes must have values and must be quoted Some tags’

attributes don’t need values in HTML, but in XHTML, all butes must have values For example, if you previously used theselect tag to create a pop-up menu in an HTML form, and wanted to have one menu choice selected by default when the page loaded, you might have written something like this

dis-The equivalent valid XHTML is this

The use of a as the tag name for

a link comes from the fact that a

link that jumps to another location

within the same page is know as an

anchor The same tag can be used

to jump to a different page; an a tag

used for this purpose is now

univer-sally referred to as a link Of course,

there is an XHTML link tag, which

is used to associate a style sheet

with a page, so don’t get confused

here Remember, a “hyperlink” that

the user clicks to jump to a new

location is technically known as an

anchor and always uses the a tag,

even though everyone refers to this

mechanism as a link.

The use of a as the tag name for

a link comes from the fact that a

link that jumps to another location

within the same page is know as an

anchor The same tag can be used

to jump to a different page; an a tag

used for this purpose is now

univer-sally referred to as a link Of course,

there is an XHTML link tag, which

is used to associate a style sheet

with a page, so don’t get confused

here Remember, a “hyperlink” that

the user clicks to jump to a new

location is technically known as an

anchor and always uses the a tag,

even though everyone refers to this

mechanism as a link.

Trang 31

to encode it using an entity An entity is a short string of ters that represents a single character; an entity causes XHTML

charac-to interpret and display the character correctly and not charac-to fuse it with markup The entity for the left angle-bracket/less-than symbol is &lt;—remember lt stands for less than

con-Entities not only help avoid parsing errors like the one just mentioned, but they also enable certain symbols to be dis-played at all, such as &copy; for the copyright symbol (©) Every symbolic entity begins with an ampersand (&) and ends with

a semicolon (;) Because of this, XHTML regards ampersands

in your code as the start of entities, so you must also encode ampersands as entities when you want them to appear in your content; the ampersand entity is &amp;

A good rule of thumb is that if a character you want to use is not printed on the keys of your keyboard (such as é, ®, ©, or £), you need to use an entity in your markup

There are some 50,000 entities in total, which encompass the character sets of most of the world’s major languages, but you can

fi nd a shorter list of the commonly used entities at the Web Design Group site (www.htmlhelp.com/reference/html40/entities).And those are the rules of XHTML markup They are relatively simple, but you must follow them exactly if you want your pages to validate (and you do)

An XHTML Template

There are certain tags that must be in your Web page for it to be valid XHTML As you learned from items 1, 2, and 3 above, you need to tell the browser whether your page is pure XHTML or also

Quoted attribute values don’t have

to be lowercase, but it’s good

prac-tice to write everything lowercase—

then you can’t go wrong The only

time I don’t follow this guideline

is with alt tags, where the attribute

value—a text string—might appear

on-screen.

Quoted attribute values don’t have

to be lowercase, but it’s good

prac-tice to write everything lowercase—

then you can’t go wrong The only

time I don’t follow this guideline

is with alt tags, where the attribute

value—a text string—might appear

on-screen.

Various tools take your old HTML

markup and convert it to XHTML

Of these, HTML Tidy is considered

the best The Infohound site (http://

infohound.net/tidy) has an online

version of HTML Tidy and links to

downloadable versions and

docu-mentation After the conversion is

complete, you always have some

fi nal hand cleanup to do, but HTML

Tidy and others can save you hours

of work.

Various tools take your old HTML

markup and convert it to XHTML

Of these, HTML Tidy is considered

the best The Infohound site (http://

infohound.net/tidy) has an online

version of HTML Tidy and links to

downloadable versions and

docu-mentation After the conversion is

complete, you always have some

fi nal hand cleanup to do, but HTML

Tidy and others can save you hours

of work.

Trang 32

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 17

contains deprecated tags, and what character encoding the page uses No matter what content your page displays, these tags need

to be present You also need tags to indicate the head and body areas

of the page Dreamweaver will generate a “page template” ing all the required elements when you select New from the File menu—ready for you to add your page content You can preset which DOCTYPE appears at the top by selecting: Edit > Preferences:

contain-New Document: Default Document Type (DTD) in your Preferences.

To show you what this template looks like, here’s the required code for a valid and well-formed page that uses the Strict XHTML 1.0 DOCTYPE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

About Title Tags

It’s easy to miss the title of a page because it is displayed at the very top of the browser window, but title tags carry a lot

of weight with search engines The pages that get listed on page one of Google’s results, for example, almost always have

some or all of your search terms present in their titles, which are also displayed as the titles of each of the results Make

sure that your page title contains keywords that your users might use to search with and is written so that it entices

clicks when it appears in search results Don’t waste your title tag with the useless and all-too-common “Welcome to our

Home Page.”

When I use the term “page template”

in this book, I am simply referring

to a block of code such as the one

shown to the right that forms the

basis of an XHTML-compliant page,

and not the notion of page

tem-plates that contain the nonchanging

parts of page layouts as used by

Dreamweaver and content

manage-ment systems.

When I use the term “page template”

in this book, I am simply referring

to a block of code such as the one

shown to the right that forms the

basis of an XHTML-compliant page,

and not the notion of page

tem-plates that contain the nonchanging

parts of page layouts as used by

Dreamweaver and content

manage-ment systems.

This template is in the Stylin’ site

download package For more HTML

and XHTML templates, see the Web

Standards site (www.webstandards.

org/learn/templates/index.html).

This template is in the Stylin’ site

download package For more HTML

and XHTML templates, see the Web

Standards site (www.webstandards.

org/learn/templates/index.html).

Trang 33

S T Y LI N ’ W ITH C S S - CHAP TE R 1

18

Marking Up Your Content

Adopting Web standards means working in new ways Start the development process by thinking about the structure of the con-tent—what it means—rather than its presentation—what it looks like That said, it’s absurd to think you would begin programming without some sense of how the fi nal page is gong to look when

fi nished I’ll usually whip up (i.e., obsess over for days) an Adobe Fireworks comp to get an approval of the design from the client before I start, and I’ll use that comp as a guide to what content needs to be in the markup When actually marking up the page elements (as headings, paragraphs, images, etc.), so that I have something to style with my CSS, my focus is on “what is the most meaningful tag I can wrap around each piece of content?”

Once we cover the workings of CSS in the next chapter, then we can start looking at markup in terms of both using the right tag on each

content element and ensuring that the elements are organized in a

way that makes it easy to target them with your CSS rules

Right now, we are going to focus on the individual XHTML tags and their semantic meaning, so that you can consider any piece of con-tent that will appear on your page and select the most appropriate tag to mark it up As we do this, we can also think about the concept

and paragraphs <p> will obligingly stack down the page with no line breaks required They even have preset margins to create space between them Inline elements have no such margins, and sit side

by side across the page, only wrapping to the next line if there is not enough room for them to sit next to each other

A S I M P LE E X A M P LE O F X H TM L MAR K U P

In this fi rst simple example of an XHTML page, the screenshot shows not only the stacking effect of block level elements, but also that inline elements, in this case <a> (a link) and <strong> (usually displays bold), can appear within block level elements and don’t

create new lines (Figure 1.3 on the next page).

Trang 34

<h1>Here's a level 1 heading</h1>

<h2>Here's a level 2 heading</h2>

<p>This paragraph is very short and contains very little text.</p>

<p>This paragraph is longer and contains not only

<strong>bold text</strong> but also <a href="#">a link</a>

that doesn't really link to anything.</p>

Trang 35

S T Y LI N ’ W ITH C S S - CHAP TE R 1

20

document fl ow into a variety of layouts—multiple columns, for example—without having to pollute the markup with presentational tags and attributes

TH E B R O W S E R ’ S I NTE R N AL S T Y LE S H E E T

One interesting thing to note here is that each element by default has certain styles associated with it As the screenshot shows, h1 head-ings are already styled to be larger type than h2 headings, and para-graph text is styled to be smaller than both of them This is because

a browser has a built-in style sheet that sets each element’s default font size, color (type is black, links are blue, for example), display set-ting (block or inline), and usually many other settings, too

When you use CSS to style an element, you are actually overriding the default settings for that element as set in the browser’s style sheet This makes the job easier, as you only need to change the styles that aren’t already to your liking However, if the browser doesn’t read your style sheet for some reason, these default styles are your fallback, so it’s worth making sure that your marked-up, but unstyled, page displays meaningfully in the browser before you start

on the CSS If it’s well-formed XHTML, the default document fl ow pretty much guarantees it will

A M O R E S T R U C T U R E D X H TM L PAG E

Here’s a more extensive example (Figure 1.4) of a marked-up page

that uses some common XHTML tags and also organizes the tags into logical groups using div tags based on their purpose in the page We will look at more XHTML tags as we go on I don’t want to get into a full-blown rundown of each XHTML tag and its associated attributes here, as it would be a book in its own right, but I will show you examples of many different tags and their uses throughout this book

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml: lang="en">

<head>

<title>A Sample XHTML Document</title>

<meta http-equiv="Content-type" content="text/html;

charset=iso-8859-1" />

For a quick reference of XHTML

tags and attributes, take a look at a

listing at the Cookwood site (run by

another Peachpit author, Elizabeth

Castro, whose books I highly

recom-mend) at http://www.cookwood.

com/html/extras/xhtml_ref.html.

For a quick reference of XHTML

tags and attributes, take a look at a

listing at the Cookwood site (run by

another Peachpit author, Elizabeth

Castro, whose books I highly

recom-mend) at http://www.cookwood.

com/html/extras/xhtml_ref.html.

Highlighted code is the XHTML

tem-plate shown earlier in the chapter

Highlighted code is the XHTML

tem-plate shown earlier in the chapter

Trang 36

<p>Good XHTML markup makes your content portable,

accessible and future-proof Creating XHTML-compliant pages requires following a few simple rules Also, XHTML code

can be easily validated online so you can ensure your code

<li>Declare your content type</li>

<li>Close every tag, enclosing or non-enclosing</li>

<li>All tags must be nested correctly</li>

<li>Inline tags can't contain block level tags</li>

<li>Write tags in lowercase</li>

<li>Attributes must have values and must be quoted</li>

<li>Use encoded equivalents for left brace and

ampersand</li>

</ol>

Trang 37

<p>Here are some useful links from the Web site of the

<acronym title="Word Wide Web Consortium">W<sup>3</sup>C

</acronym> (World Wide Web Consortium), the guiding body of the Web's development.</p>

<ul>

<li><a href="http://validator.w3.org">W3C's XHTML validator</a></li>

<li><a href="http://jigsaw.w3.org/css-validator/">W3C's CSS validator</a></li>

<li><a href="http://www.w3.org/MarkUp/">XHTML Resources

</a></li>

<li><a href="http://www.w3.org/Style/CSS/">CSS Resources</a></li>

Trang 38

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 23

FI G U R E 1.4 This is the above code

rendered in the Firefox browser with

the default browser styles It’s not

beautiful, but it is useable

This page nicely illustrates the inherently structured document fl ow produced by correctly marked-up elements You can see from the code that the markup has been divided with (aptly named) divs into four logical groups: header, content, navigation, and footer The id

attribute of these divs allows us to give each group a name that is unique to that page

While it’s helpful that these div IDs let us see at a glance where we are within the document structure, the primary purpose of organiz-ing our tags within divs with IDs is to enable us to target sets of CSS rules at a specifi c group of tags, rather than the entire document An element type, such as p, can be styled one way within one div and another way within another div Let’s start understanding how this

works by looking at document hierarchy.

The default blue border around the

header graphic indicates that the

image is clickable (the img tag is

enclosed in an a tag), and this rather

ugly border can easily be removed

with CSS, as we will see later

The default blue border around the

header graphic indicates that the

image is clickable (the img tag is

enclosed in an a tag), and this rather

ugly border can easily be removed

with CSS, as we will see later

Class attributes are similar to IDs

in as much as they can be used to

identify groups of tags, but while a

class can appear many times within

a page, an ID can appear only once

We will learn about the correct uses

of classes and IDs in the next

chap-ter Also see the sidebar “Naming

Classes and IDs.”

Class attributes are similar to IDs

in as much as they can be used to

identify groups of tags, but while a

class can appear many times within

a page, an ID can appear only once

We will learn about the correct uses

of classes and IDs in the next

chap-ter Also see the sidebar “Naming

Classes and IDs.”

Trang 39

S T Y LI N ’ W ITH C S S - CHAP TE R 1

24

Naming Classes and IDs

IDs and class attributes are identifi ers you can add to your tags You can add a class or an ID attribute to any tag,

although most commonly, you add them to block-level elements IDs and classes help you accurately target your CSS to

a specifi c element or set of elements I get into the uses for (and differences between) IDs and classes later, but for now, it’s helpful to know that an attribute value must be a single word, although you can make compound words that the browser sees as single words using underscores, such as class="navigation_links"

Because the browser can misinterpret attribute names made of bizarre strings of characters, my advice is to start the word with a letter, not a number or a symbol Because the only purpose of a class or ID is to give an element a name that you can reference in your style sheet (or JavaScript code), the value can be a word of your own choosing That said, it’s good practice to name classes and IDs something meaningful such as class="navigationbar" rather than

class="deadrat" Although the deadrat class might provide a moment of levity during a grueling programming sion, the humor may be lost on you when you are editing your code at some point in the future Don’t save time with abbreviated names either; call the ID "footer" rather than "fr" or you are apt to waste your time (or someone else’s) later trying to fi gure out what you meant Do yourself a favor and take the time to give classes and IDs unambiguous and descriptive names

ses-Document Hierarchy: Meet the XHTML Family

Document hierarchy is the fi nal XHTML concept we’ll look at before

we start looking at CSS The document hierarchy is like a family tree

or an organizational chart that is based on the nesting of a page’s XHTML tags A good way to learn to understand this concept is to take a snip of the body section of the markup we just discussed and strip out the content so that you can see the organization of the tags better Here’s the stripped-down header

Now you can clearly see the relationships of the tags For example,

in the markup, you can see that the body tag contains (or nests) all the other tags You can also see that the div tag (with the ID of

"header") contains two tags: an image tag and a head 3 tag

Dreamweaver’s Code View will

automatically indent nested tags as

shown above (Commands > Apply

Source Formatting) to help you see

the hierarchy more clearly.

Dreamweaver’s Code View will

automatically indent nested tags as

shown above (Commands > Apply

Source Formatting) to help you see

the hierarchy more clearly.

Trang 40

X H TM L : G I V I N G S T R U C T U R E TO C O NTE NT 25

FI G U R E 1 5 shows a conceptual

way to represent a document’s

structure—with a hierarchy diagram

body

div

When examining this hierarchical view (Figure 1.5), we can say

that both the img tag and the h3 tag are the children of the div tag, because it is the containing element of both In turn, the div tag is

the parent tag of both of them, and the img tag and the h3 tag are

siblings of one another because they both have the same parent tag

Finally, the body tag is an ancestor tag of the img and h3 tags, because they are indirectly descended from it In the same way, the img and

h3 tags (and the div, for that matter) are descendants of the body tag

To quote Sly Stone: “It’s a family affair…”

In CSS, you write a kind of shorthand based on these relationships, for example

div#header img {some CSS styling in here}

Such a CSS rule only targets img tags inside of (descended from) the div with the ID of "header" (the # is the CSS symbol for an ID) Other

img tags in the page are unaffected by this rule because they aren’t contained within the "header" div In this way, you can add a border around just this image or set its margin to move it away from sur-rounding elements

We will get into learning to write CSS rules like this in greater detail

in the next chapter, but the important concept to understand is that every element within the body of your document is a descendant

of the body tag, and, depending on its location in the markup, the element could be an ancestor, a parent, a child, or a sibling of other tags in the document hierarchy

By creating rules that use (and often combine) references to IDs, classes, and the hierarchy structure, you have means by which you can accurately dictate which CSS rules affect which XHTML ele-ments, and this is exactly what you will learn to do next

Ngày đăng: 01/04/2021, 15:04

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN