The current style sheet, as given in Listing 18.1, actually eliminates the bars between thecontent cells by not giving them a distinct background color, but you can’t tell that byskimmin
Trang 1.urhc { color: black; vertical-align: top; } A:active { color: black; font-weight: bold; } menubar a:hover { color: white; }
body { font-family: Garamond, Georgia, Times,
“Times New Roman”, serif; } inter { }
.lhs { color: black; } h1, h2, h3, h4 h5, h6, dt, heading { color: black; font-variant: small-caps; } lhrc a:link, lrhc a:visited {
text-decoration: none; font-weight: bolder;
color: black; } urhc H1 { color: white; text-align: center;
border: none; padding: 0% 5%;
margin: 0px; line-height: 75px; } A:link { font-weight: bold; color: #000066;
text-decoration: none; } lrhc { color: black; }
.ulhc img { border: 2px solid white; padding-left: 15px;
padding-right: 15px; } llhc { color: black; }
h1, h2, h3, h4, h5, h6, heading { border-bottom: 1px solid white; } body { background-color: #cca580;
background-image:
url(“/photos/feb2002/arizona/painted-desert_sm.jpg”);
background-position: top right;
background-repeat: no-repeat; } vert { }
A:visited { font-weight: bold; color: #006600;
text-decoration: none; }
If that was a bit hard to follow, don’t feel bad; that was intentional On the Kynn.comsite, I use tables to divide the page into six content cells that can each be styled indepen-dently Vertical and horizontal bars separate these cells, and the bars, as well as theirintersections, can also have styles applied to them
The layout is shown in Figure 18.1, which indicates the classattribute for each cell Theclasses have names like urhcfor “upper right hand corner” and lhsfor “left hand side.”
L ISTING 18.1 Continued
Trang 2The current style sheet, as given in Listing 18.1, actually eliminates the bars between thecontent cells by not giving them a distinct background color, but you can’t tell that byskimming the style sheet.
The style sheet in Listing 18.2 is really the same as before; both produce the same resultswhen applied to the Web page, but the second one is easier to understand Commentsmake clearer what each section of the style sheet does, and the order is much easier tounderstand
L ISTING 18.2 A Better-organized Style Sheet/* k-orderly-18.2.css */
background-position: top right;
18
F IGURE 18.1
The layout of cssin24hours.com, done with tables.
Trang 3.vert { } horiz { } inter { } lhs { color: black; } rhs { color: black; } llhc { color: black; } lrhc { color: black; } /* lower right hand corner */
.lhrc a:link, lrhc a:visited {
text-decoration: none; font-weight: bolder;
color: black; } /* upper right hand corner */
.urhc h1 { color: white; text-align: center;
border: none; padding: 0% 5%;
margin: 0px; line-height: 75px; } /* upper left hand corner */
.ulhc img { border: 2px solid white; padding-left: 15px;
padding-right: 15px; } /* fonts */
body { font-family: Garamond, Georgia, Times,
“Times New Roman”, serif; } /* Distinct headings */
h1, h2, h3, h4 h5, h6, dt, heading { color: black; font-variant: small-caps; } h1, h2, h3, h4, h5, h6, heading
{ border-bottom: 1px solid white; } /* Link styles */
a:link { font-weight: bold; color: #000066;
text-decoration: none; } a:visited { font-weight: bold; color: #006600;
text-decoration: none; } a:active { color: black; font-weight: bold; } /* Menu bar */
.menubar { border: 2px solid white; } menubar a:hover { color: white; } /* Primary content */
.content { position: relative; border: 2px solid white;
padding: 1em 5% 1em; }
L ISTING 18.2 Continued
Trang 4Site-wide Style Sheets
The style sheet given in Listing 18.2 was created to be used on the entire site, notjust on one page The ability to link in an external style sheet makes this an easychoice to apply styles over your entire site by setting each page to use the stylesheet with the <link>tag An example of a Web page on the Kynn.com site,which uses this style sheet, is shown in Figure 18.2; the original page is athttp://kynn.com/nav/causes.html.
18
F IGURE 18.2
The Kynn.com style sheet applied to a Web page.
A style sheet that is referenced from all pages on a site makes it a very simple task
to change the appearance of the entire Web site For example, Figure 18.3 showsthe same page as in Figure 18.2, but with a different style sheet Changing the sin-gle external file altered the look of the whole Web site instantly If you’re curious,you can view this other style sheet at http://www.cssin24hours.com/18/
k-alt.css
A site-wide style sheet can be used to enforce a consistent appearance on the Web site,even if you have multiple Web developers working on the same site Additional stylescan be added in embedded style sheets or in additional linked CSS files that are createdfor each department or business unit For example, the City of Fullerton’s Web site
Trang 5F IGURE 18.3
A different style sheet applied to the Kynn.com site.
F IGURE 18.4
Style sheets set the appearance of the city Web site in Fullerton, California.
Trang 6Validating Your CSS
Everyone makes mistakes, even you and me Mistakes in writing CSS can be benign,producing a minor effect such as putting a block of text in the wrong font, or they can bemuch more serious and prevent people from using your page at all
As you learned in Hour 4, you can validate your HTML using the World Wide WebConsortium’s HTML validator at http://validator.w3.org The W3C provides a freeCSS validation service, as well, for checking your CSS syntax This is located athttp://jigsaw.w3.org/css-validator/.
Trang 7validat-Why Validate?
Validation is a useful strategy for a number of reasons The biggest benefit is that itallows you to spot errors in your style sheet syntax For example, in Figure 18.5, the CSSvalidator noticed a problem with the style sheet The following line can be found in bothListing 18.1 and Listing 18.2:
h1, h2, h3, h4 h5, h6, dt, headingThe error is the punctuation after the h4; it should be a comma, but here I’ve put aperiod That kind of error is hard to spot when you’re just skimming the page In fact, itwas there for months before I noticed it! Did you spot it earlier?
The warnings issued by the CSS validator are quite useful for spotting accidental sions, such as setting a foreground color without a contrasting background color
omis-However, you have to interpret those results carefully The CSS validator can’t fullyaccount for inheritance and transparency in your Web page, and so you’ll need to deter-mine for yourself if a warning is an actual problem
A validator is like a spell-checker or grammar-checker in a word processor They canspot potential problems and you wouldn’t think of submitting a document without check-ing it first, but blind reliance on an automated checker without using human judgment isjust as bad
Summary
When creating any Web pages, whether using CSS or not, it’s important to keep theneeds of your users in mind Providing them with an attractive Web site is not in conflictwith giving them an easy-to-use site In fact, the two approaches are both complementaryand necessary for making a truly great site
Testing plays a major role in any CSS design, and you can’t rely on your own judgmentwhen catching possible mistakes Three important resources are other Web developerswho can give advice about your design efforts, users in informal tests who point out unex-pected errors, and CSS validation services that check your syntax and warn of omissions.Web development using CSS is a balancing act, and the factors you’ll have to weighinclude using CSS for layout, supporting older browsers, and accounting for browserquirks As each site is unique, there’s no universal answer; you’ll need to use your ownjudgment to figure out what works for you
Organizing your style sheets in a sensible manner will make life easier for you and one else who has to read your style sheet Use comments whenever you think of it, andgroup your styles together in natural groupings You’ll thank yourself later; believe me
Trang 8any-Browser Support Report Card
There’s no report card in this hour because no new CSS features were introduced Thestrategies for Web development you learned in this hour can be applied to all style sheets
Q&A
Q Your personal Web site doesn’t use CSS for layout What gives?
A It’s a pretty old design, and when I created it, there were even fewer browsers that
understood positioning CSS If I were doing it from scratch today, Kynn.comwould be done using CSS for layout, using the @importtrick described in Hours
16, “Page Layout in CSS,” and 17, “Advanced CSS Layout,” to avoid Netscape 4problems This is much easier to do on a new site than on an existing one, espe-cially if you’re spending your time writing a book! The CSSin24hours.com sitedoes use CSS for layout because that’s a new site
Workshop
The workshop contains quiz questions and activities to help reinforce what you’velearned in this hour If you get stuck, the answers to the quiz can be found after the ques-tions
Quiz
1 Colors and fonts should be used to(a.) Make the page harder to read, so people spend more time on your site
(b.) Hide content from the real users while tricking search engine spiders
(c.) Present the content in an attractive, usable manner
(d.) Make you seem really cool to all your friends
2 What do you need for effective user testing?
(a.) Nothing Just follow your own instincts because you are a user too
(b.) Five people, five tasks, and five lattes
(c.) A usability lab with one-way mirrors, video cameras, and a million-dollarbudget
18
Trang 93 The validator will point out two errors: the period instead of the comma after the
tdand the unknown property name bakground-color Also, because there is nobackground-colorvalue given to contrast with the colorvalue, a warning will begenerated
Activity
Here’s a list of projects you can undertake to reinforce what you’ve learned this hour:
• Write up five tasks that could be accomplished by a user of a specific Web site.Make sure you have a few you think are easy and a few you think are hard; youmight find yourself surprised in an actual test
• In fact, if you’ve got the time and the inclination, do an informal user test asdescribed earlier this hour The results are always educational, even if they just tellyou that you’re on the right track
• Subscribe to the HWG-Critique mailing list at the HTML Writers Guild, and post asite for review Then, give your own critique in response to someone else’s request.Remember to be both polite and constructive, of course!
• Look at some of the style sheets you’ve worked on, and see if you can reorganizethem to be easier to understand Comments, comments, comments!
• Validate your style sheets, and if they don’t pass, fix them until they do Considereach warning; is it a valid potential problem, or can you safely ignore it?
Trang 1019 Advanced Selectors
20 CSS for Printing
21 Accessibility and Internationalization
22 User Interface and Generated Content
23 CSS and JavaScript
24 CSS and XML
P ART IV
Advanced Cascading Style Sheets
Trang 12H OUR 19
Advanced Selectors
The CSS Level 2 specification introduced a number of additional selectors thatare not yet fully supported by all browsers These advanced selectors greatlyincrease the functionality and power of CSS, allowing rules based on complexrelationships to be written Full support of these new selectors, when available,will greatly extend the utility and power of CSS
In this hour, you’ll learn
• How to create CSS rules that select only those tags that have a specificattribute
• How to create rules based on the values of those attributes
• How to create rules that select direct children of another element andwhy you’d want to do that
• How to select an element that directly follows another element
• Which browsers support these advanced selectors
Trang 13Attribute Selectors
An attribute selector tests for the existence, and possibly the values, of any specific
attributes set on an element You’d use an attribute selector if you wanted all elementswith a certain attribute to be styled a certain way For example,noshadeis an HTMLattribute for the <hr>tag; it means that there shouldn’t be any shading effects applied tothe tag If you wanted all of those <hr>tags to be colored silver, you’d use an attributeselector based on the noshadeattribute The simplest form of attribute selector is simplythe attribute within square brackets, as follows:
element[attribute] { declaration; }
For example:
hr[noshade] { color: silver; }This rule would declare that all <hr>elements with the noshadeattribute should be col-oredsilver.
You can write an attribute selector rule so that it selects all elements with the chosenattribute by using the universal selector (*) For example, you could set a specific rule forall tags that have a titleattribute to indicate which parts of the page will pop up atooltip when you move the mouse over them, as in the following:
*[title] { background-color: yellow; }This will mark with a yellowbackground all tags with titleattributes Because the uni-versal selector is optional, you can also write the rule like this:
[title] { background-color: yellow; }
Workaround for Netscape 4, Internet Explorer 4/5/5.5 (Windows), Internet Explorer 4/5/5.1 (Macintosh)
Only Opera, Netscape 6, and Mozilla support attribute selectors For patibility with other browsers, you should use an explicit class attribute and class selector rule (If you’re using more than one class at once, you may need to add additional <div> or <span> tags for compatibility with Netscape 4.) For example, to make the two attribute selector examples work in Netscape 4, you’ll need to write your HTML like this:
com-<hr class=”unshaded” noshade>
<a href=”summer2001.html” class=”hastooltip”
title=”What I Did for Summer Vacation”>Summer 2001</a>
Your CSS rules would then look like this:
hr[noshade], hr.unshaded { color: silver; }
*[title], hastooltip { background-color: yellow; }
Trang 14Selecting by Attribute Value
In addition to checking for the existence of the attribute, you can also select by attributevalue There are three ways to do this:
element[attribute=”value”] { declaration; } element[attribute~=”value”] { declaration; } element[attribute|=”value”] { declaration; }
The first version designates an exact match; it selects only those elements for which theattribute has the given value The second registers a match if the value in the rule is one
of several values given in the HTML, separated by spaces The third matches the rule’svalue against the HTML’s value and compares the characters before hyphens (This is toallow matching of language groups, which are written as en-us,en-uk, en-au, and soon.) Table 19.1 shows several types of selectors and attribute values and indicateswhether or not each selector would match the HTML
T ABLE 19.1 Testing Attribute Values
CSS Selector HTML Snippet Match?
table[summary=”layout”] <table summary=”layout”> Yes
table[summary~=”layout”] <table summary=”layout”> Yes
table[summary|=”layout”] <table summary=”layout”> Yes
div[class=”bar”] <div class=”foo bar baz”> No
div[class~=”bar”] <div class=”foo bar baz”> Yes
div[class|=”bar”] <div class=”foo bar baz”> No
*[lang=”en”] <span lang=”en”> Yes
*[lang~=”en”] <span lang=”en”> Yes
*[lang|=”en”] <span lang=”en”> Yes
*[lang=”en”] <span lang=”en-us”> No
*[lang~=”en”] <span lang=”en-us”> No
*[lang|=”en”] <span lang=”en-us”> Yes
*[lang=”en”] <span lang=”english”> No
*[lang~=”en”] <span lang=”english”> No
*[lang|=”en”] <span lang=”english”> No
19
Trang 15Let’s look at an example of attribute selectors in action Listing 19.1 is an HTML page sisting of a table of departure times for airline flights I’ve chosen to use the axisattribute
con-on table cells to group similar types of flights Those flights that fly through Saint Louishave been assigned an axisvalue of stlouis, whereas those going through Chicago arelabeled with an axisvalue of ord
L ISTING 19.1 HTML Table Marked Up with the axisAttribute
<! flights-19.1.html >
<html>
<head>
<title>Flights from Los Angeles to New York</title>
<link type=”text/css” rel=”stylesheet”
Workaround for Netscape 4, Internet Explorer 4/5/5.5 (Windows)
As many browsers don’t support attribute value selectors, you will have to use the same tricks with class listed in the previous workaround—creating class selector rules that explicitly identify tags that have the values you need to style.
Trang 16L ISTING 19.2 This Style Sheet Uses Rules Based on the axisAttribute Selector/* flights-19.2.css */
td { color: black;
background-color: white;
} td[axis=”stlouis”]
{ background-color: yellow;
color: navy;
} td[axis=”ord”]
{ background-color: black;
Trang 17You’ve actually been using shorthand versions of some attribute selectors for some timenow; the classandidselectors are actually just special cases of an attribute value selec-tor The following pairs of rules are equivalent:
.apple { color: green; }
*[class~=”apple”] { color: green; }
#banana { color: yellow; }
*[id=”banana”] { color: yellow; }Multiple attribute values can be combined together by simply adding on another attributetest Here’s an example of a rule that selects all table cells that are right aligned and ver-tically aligned to the bottom:
selec-You can use attribute selector rules with a user style sheet to create some very simple but powerful testing tools for Web development For example,
to make anchors visible, create a style sheet, set it as your user style sheet in your browser, and add the following rule:
a[name], [id] { border: 1px dotted red; }
Trang 18Family Relationships
Family-based selectors in CSS choose elements based on the relationships between theHTML tags; these relationships are named after family relationships You’ve already usedone of the family relationship selectors: the descendant selector, which selects elementsdescended from another tag Other relationship selectors include child and adjacent sib-ling selectors
Child Selectors
A child selector is a special case of descendant selectors, which were covered in Hour 5,
“Selectors.” A child selector identifies only those elements that are immediate children ofanother element, not any “grandchildren” or other descendants A child selector is indi-cated by a greater-than symbol (>) between the parent element and the child:
parent > child { declaration; }For example, consider the following snippet of HTML:
<blockquote>
<div class=”opinion”>
<p>I’m voting Green next year.</p>
<p>I’m wearing green, too!</p>
</div>
</blockquote>
Here are some style rules, but only a few of these will be applied to the code sample:
blockquote p { font-size: large; } blockquote > p { font-family: Arial, sans-serif; } opinion > p { font-color: green; }
19
This will put a dotted line around your anchors and anything else with the
id attribute set You can use this same trick to make table borders, form boundaries, field <label> s, and other block elements visible because they’re outlined with a border Here’s a pair of rules to make it very clear which of your images don’t have alt attributes on them:
img { border: 5px solid lime; } img[alt] { border: none; }
For more of these useful user CSS recipes, see an article by Eric Meyer at
http://www.oreillynet.com/pub/a/network/2000/07/21/magazine/css_tool.html
Trang 19not grandchildren, count for child selectors.) The third rule will be applied to the <p>textbecause both paragraphs are direct children of a tag with class=”opinion” So the totaleffect will be two green paragraphs, both in the default font face.
Workaround for Netscape 4, Internet Explorer 4/5/5.5 (Windows), Internet Explorer 4/5/5.1 (Mac)
Many browsers won’t recognize child selectors For compatibility with these older browsers, use descendant selectors; if you’re unable to get the effects you want with just descendants, use class selectors too Here’s how you would rewrite your green quote style sheet rules:
blockquote p { font-size: large; /* same */ } blockquote p.childofblockquote
{ font-family: Arial, sans-serif; } opinion p { font-color: green; }
You’ll notice I added a class called childofblockquote ; I’ll have to add that
to every <p> that is a direct child of a <blockquote> I won’t add it to the <p>
inside the <div> tag because they shouldn’t be in Arial, according to the original style sheet.
Adjacent Sibling Selectors
Two HTML tags are siblings if they have the same parent; they are adjacent siblings ifthe second occurs directly after the first in the source code Here’s some HTML to illus-trate a sibling relationship:
<li>tags are adjacent as well The id=”ang”andli=”nyi”tags are not adjacent
An adjacent sibling selector makes a selection based on two adjacent siblings, but it
applies the declared style only to the second of the two This is very important to ber; you are not selecting the pair, you are selecting only the final one in the list
remem-You write an adjacent sibling rule by listing the first sibling, a plus sign (+), and then thesecond sibling A rule such as the following will turn only the Kim and Nying names blue:
li + li { color: blue; }
Trang 20Adjacent sibling selectors are useful for removing margins, padding, and borders whensiblings are meant to flow together visually An example of this is shown in Listing 19.3.
L ISTING 19.3 A Definition List with Adjacent <dt>and<dd>Elements
border-top: 1px solid black; }
dt:first-child { border-top: none;
Trang 21<dd>World Wide Wide Consortium</dd>
<dd>See also: WAI</dd>
dis-L ISTING 19.3 Continued
Trang 22Although unsupported by all but the newest browsers, advanced selectors add ably to the CSS developer’s toolbox Attribute selectors allow styles to be set based onspecific attribute values or even the existence of an attribute on the tag Relationshipsbetween elements can be expressed in CSS by the child selector, which applies to directchildren of a specific element, and by the adjacent sibling selector, which chooses thesecond of a pair of specified tags
consider-Browser Support Report Card
CSS Feature Grade Notes
Adjacent sibling selectors C– See text
Unfortunately, there is little browser support for any advanced selectors except from thenewest browser versions For this reason, it is suggested that you should avoid usingthem unless you know your audience is using a newer browser Workarounds exist in theform of class attributes, but this is not an elegant solution
Q&A
Q Can I do pattern matching in attribute values? Suppose I want to select all <a>
tags that are mailto links Can I use a[href=”mailto:*”] as my selector?
A Nope The CSS specifications don’t define a way to do this type of pattern
match-ing Future versions of CSS based on XPath and XPointer might allow this, but fornow there is no way to use pattern matching in CSS To make your mailtolinksstand out, set a classattribute on them, and use a classselector
Q If I could use either a child selector or a descendant selector, which should I use? Which should I use if, for example, I want to select all <img> tags within
<a> links?
A In theory, it’s better to use a child selector if you know you’re dealing with a direct
child because it’s quicker for the browser to calculate child selectors It doesn’thave to look over the full tree of the HTML document, just up one level In prac-
19
Trang 23Q Can I combine advanced selectors with simple selectors or other advanced selectors?
A Certainly! This is a valid CSS rule:
.chap > th + td img[alt] { border: 2px solid green; }What would match this? Basically, anything that meets the following criteria:
• An image element
• With an altattribute set (to any value)
• Where that image is a descendant of a table cell
• Assuming that table cell has a table header cell as a sibling
• Which is a direct child of an element in the chapclass
Workshop
The workshop contains quiz questions and activities to help reinforce what you’ve learned
in this hour If you get stuck, the answers to the quiz can be found after the questions
Quiz
1 What does the +symbol indicate, in a selector?
2 Which selector will select the HTML element <h1 align=”right”>Welcome</h1>,and why?
1 The +symbol designates a direct sibling selector
2 It’s kind of a trick question All of them will select the <h1> The first will select itbecauserightis one of the values listed in the attribute (It’s the only value, too.)The second will select it because it’s exactly the value (and the selector’s type isuniversal) The third is also a universal selector, and it will compare values before adash; because there is no dash, it will just compare rightwithright The lastmatches with any value because the <h1>tag has an alignattribute
Trang 243 Here’s one way to zap away those annoying banners:
img[height=”60”][width=”468”] { display: none; }
Activity
To understand more about advanced selectors, look at some of the style sheets you havealready created, and see if they could be improved by replacing class or descendantselectors with adjacent sibling, direct child, or attribute selectors Remember that thesewill work only in recent browsers, so you’ll want to test with one of those
19