Syntax for changing capitalization
This style declaration uses the text-transform property:
selector {text-transform: value;}
The value of the text-transform property may be one of the following:
✓ capitalize: Capitalizes the first character in every word
✓ uppercase: Renders all letters of the text of the specified element in
uppercase
✓ lowercase: Renders all letters of the text of the specified element in
lowercase
✓ none: Keeps the value of the inherited element
41 trang |
Chia sẻ: tlsuongmuoi | Lượt xem: 2239 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Getting Creative with Colors and Fonts, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
185 Chapter 11: Getting Creative with Colors and Fonts
Figure 11-6: All hyperlinks are bolded.
Syntax for applying italic
This style declaration uses the font-style property:
selector {font-style: value;}
The value of the font-style property may be one of the following:
✓ italic: Renders the text in italics (a special font that usually slopes to
the right)
✓ oblique: Renders the text as oblique (a different slanted version of a
normal font; seldom if ever used for font definitions)
✓ normal: Removes any italic or oblique formatting
Markup for applying italic
The following example assigns an italic font style to the first-level heading:
body {color: #808000; font-family: Verdana, sans-serif; font-size: 85%;}
h1 {color: teal; font-family: “MS Trebuchet”, Arial, Helvetica, sans-serif;
text-transform: uppercase; font-style: italic; font-weight: 800;
font-size: 2em; line-height: 30pt; text-align: center;}
Changing capitalization
You use the text-transform property to set capitalization in your document.
18_9780470916599-ch11.indd 185 11/30/10 10:42 AM
D
ow
n
lo
a
d
f
ro
m
W
o
w
!
e
B
o
o
k
<
w
w
w
.w
o
w
e
b
o
o
k.
co
m
>
186 Part III: Taking Precise Control Over Web Pages and Styles
Syntax for changing capitalization
This style declaration uses the text-transform property:
selector {text-transform: value;}
The value of the text-transform property may be one of the following:
✓ capitalize: Capitalizes the first character in every word
✓ uppercase: Renders all letters of the text of the specified element in
uppercase
✓ lowercase: Renders all letters of the text of the specified element in
lowercase
✓ none: Keeps the value of the inherited element
Markup for changing capitalization
The following example renders the first-level heading in uppercase (shown in
Figure 11-7):
body {color: black; font-family: Arial, sans-serif; font-size: 85%;}
a {font-weight: bold;}
a:link {color: olive; text-decoration: underline;}
a:visited {color: green; text-decoration: none;}
h1 {font-family: “Trebuchet MS”, verdana, geneva, arial, helvetica, sans-
serif;
font-size: 2em; line-height: 2.5em; color: teal; text-transform: uppercase;
text-align: center}
Figure 11-7: The first-level heading is rendered in all uppercase.
18_9780470916599-ch11.indd 186 11/30/10 10:42 AM
187 Chapter 11: Getting Creative with Colors and Fonts
Getting fancy with the text-decoration property
The text-decoration property allows for text formatting that’s a tad cra-
zier. It isn’t used often.
Syntax for text decoration
This style declaration uses the text-decoration property:
selector {text-decoration: value;}
The value of the text-decoration property may be one of the following:
✓ underline: Underlines text
✓ overline: Renders the text with a line over it
✓ line-through: Renders the text with a line through it
✓ blink: Blinks the text onscreen
Are you sure you want blinking text?
• blink isn’t supported by all browsers.
• blink can be dreadfully annoying and distracting.
✓ none: Removes any text decoration
Markup for text decoration
The following example changes the link when the mouse hovers over it. In
this case, it turns off any underlining for a link:
body {color: #808000; font-family: Verdana, sans-serif; font-size: 85%;}
a:link {color: olive; text-decoration: underline;}
a:visited {color: olive; text-decoration: underline;}
a:hover {color: olive; text-decoration: none;}
The Catchall Font Property
Many font properties can be summarized in one style declaration by using
the shorthand font property. When it’s used, only one style rule is needed
to define a combination of font properties:
selector {font: value value value;}
18_9780470916599-ch11.indd 187 11/30/10 10:42 AM
188 Part III: Taking Precise Control Over Web Pages and Styles
The value of the font property is a list of any values that correspond to the
various font properties:
✓ The following values must be defined in the following order although
they don’t have to be consecutive:
• font-size (required)
• line-height (optional)
• font-family (required)
The font-family value list must end with a semicolon.
Use commas to separate multiple font family names. For example, you
can use the following style declaration to create a specific style for para-
graph text that specifies font-size, line-height, and font-family in that
(required) order:
p {font: 1.5em bold 150% Arial, Helvetica, sans-serif;}
✓ The following values are optional and may occur in any order within the
declaration. Individual values are separated by spaces:
• font-style
• font-variant
• font-weight
For example, you can use the following style declaration to create a specific
style for a first-level heading that mixes the optional values in among the
required ones (font-style and font-weight before line-height and font-family in
this case, with font-size and font-variant omitted):
h1 {font: italic bold 150% Arial, Helvetica, sans-serif;}
18_9780470916599-ch11.indd 188 11/30/10 10:42 AM
Part IV
Scripting and (X)HTML
19_9780470916599-pp04.indd 189 11/30/10 12:25 AM
In this part . . .
Here, we introduce and describe the types of script-ing languages that work on Web pages, and dig
lightly into JavaScript — by far the most popular of all
Web-scripting languages. Scripting languages help static,
unchanging Web pages become active, dynamic docu-
ments that can solicit and respond to user input.
Next, you dig more deeply into working with forms so you
can understand how to solicit — and deal with — input
from your users. The following chapter shows how to
embed third-party services and information — such as
Flickr, Twitter, Google Maps, and YouTube — to make
your pages more dynamic and interesting while leveraging
the work of others.
The next chapter shows you ways to put JavaScript to
work in your Web pages. You pick up the basic concepts
and techniques for creating dynamic HTML (sometimes
called DHTML) and using client-side JavaScripts and pre-
fabricated code to perform basic tasks, such as displaying
date and time information, counting site visitors, or tabu-
lating current statistics. Part IV concludes with an over-
view of Web-based content management systems (CMS),
including WordPress, Joomla!, and Drupal.
19_9780470916599-pp04.indd 190 11/30/10 12:25 AM
Chapter 12
Top 20 CSS Properties
In This Chapter
▶ Digging into backgrounds and borders
▶ Fiddling with fonts, spacing, and positioning
▶ Managing text color and line-height
▶ Linking up with pseudo classes
▶ Making the most of online CSS resources
As you can see in Chapters 9–11, there’s an awful lot you can do with Cascading Style Sheet (CSS) markup to manage and control how Web
pages behave inside users’ browsers. In this chapter, we single out a small
subset of 20 specific CSS properties that you’re most likely to encounter —
and use — on even fairly simple Web pages. Of course, we know this won’t
be enough for real Web-heads, or even aspiring ones, so this chapter also
includes a tasty set of nonpareil CSS references where you can dig up more
details and learn about other properties to your heart’s content.
Eric A. Meyer not only wrote the Foreword for this book, but he’s also
authored numerous gems of his own on the subject of CSS. Be sure to check
out his many CSS-related titles, especially the invaluable Smashing CSS:
Professional Techniques for Modern Layout (Wiley).
Background Properties
As a CSS concept, background refers to numerous properties (six in all)
introduced with CSS 1.0 to manage what goes behind elements on display in
a Web page. Table 12-1 lists all the background properties, after which we
provide examples and details for two of the properties. To read more about
background properties and other CSS markup, visit the “Best CSS Resources”
section at the end of this chapter for additional information and useful tips.
20_9780470916599-ch12.indd 191 11/30/10 12:25 AM
192 Part IV: Scripting and (X)HTML
Table 12-1 Background Properties
Property Description
background Shorthand placeholder for all background
properties
background-attachment Determines whether background image
remains fixed or scrolls with the page
background-color Sets background color for related element
background-image Supplies background image for related ele-
ment as URL
background-position Sets starting position for background image
background-repeat Determines how background image repeats
on page
background-color
The background-color property allows you to establish a solid color for an
element’s background, including any associated padding and border settings
that go with it. Colors may be assigned by name, as described and illustrated
on the online Cheat Sheet at www.dummies.com/cheatsheet/html (aqua,
black, blue, fuchsia, and so forth) or by hex code number. (Color values and
hex code numbers are discussed in more detail in Chapter 11.)
In the code for the Web page displayed in Figure 12-1, we set the text color
for the body element to olive (#808000) for text. We then define a basic
style rule for the default level one (h1) heading shown at the top with a
gray background-color, and black text. The second heading uses a class
instance named alt-h1 to set large margins, padding, and borders to create
a large silver background area around the text and an indent to the left.
Visit the Web site for this book at www.dummieshtml.com, and then check
the listings for Chapter 12 for easy access to all source code used to pro-
duce screenshots in this book (find links for figures by number: 12-1, 12-2,
and so on).
background-image
Use the background-image property to use an image instead of a solid
color as the background for an element. We take the code from Figure 12-1,
make alt-h1 text italic, and replace background-color: silver; with
background-image: url(texture.jpg);, where a photographic texture
is the background (see Figure 12-2).
20_9780470916599-ch12.indd 192 12/2/10 10:47 PM
193 Chapter 12: Top 20 CSS Properties
Figure 12-1: A general style rule defines h1
appearance, further refined by instance alt-h1.
When using images as background, repetitive textures or relatively quiet
abstract images work best, particularly if you want users to be able to read
foreground text.
Figure 12-2: This time, the alt-h1 instance
picks up a photo as the background.
Border and Outline Properties
Borders and outlines define the edges and help to make boundaries around
elements visible. You’ll find all kinds of controls for individual edges as
well as for color, style, and width. To keep the jargon straight, a border falls
20_9780470916599-ch12.indd 193 11/30/10 12:25 AM
194 Part IV: Scripting and (X)HTML
just inside the edge of an element box, whereas an outline includes that
edge. Table 12-2 lists the various border and outline properties along with a
description of what they do.
Table 12-2 Border and Outline Properties
Property Description
border Shorthand for all border properties
border-bottom Sets all bottom border properties
border-bottom-color Sets bottom border color
border-bottom-style Sets bottom border style
border-bottom-width Sets bottom border width
border-color Sets color for all four borders
border-left Sets all left border properties
border-left-color Sets left border color
border-left-style Sets left border style
border-left-width Sets left border width
border-right Sets all right border properties
border-right-color Sets right border color
border-right-style Sets right border style
border-right-width Sets right border width
border-style Sets style for all four borders
border-top Sets all top border properties
border-top-color Sets top border color
border-top-style Sets top border style
border-top-width Sets top border width
border-width Sets width for all four borders
outline Sets all outline properties
outline-color Sets outline color
outline-style Sets outline style
outline-width Sets outline width
20_9780470916599-ch12.indd 194 11/30/10 12:25 AM
195 Chapter 12: Top 20 CSS Properties
border
For CSS, border is a shorthand property: That is, it combines width, style, and
color in a single declaration. Each of these three components applies to the
top, right, bottom, and left edges of an element box, in that order. Here’s a
mnemonic: We use TRBL — that’s right, trouble — as shorthand for the order
of top, right, bottom, and left.
This single CSS property actually permits as many as 12 subsidiary proper-
ties to be set at the same time. In the example shown in Figure 12-3, we sur-
round paragraphs with thin dashed purple lines, thereby addressing width
(thin), color (purple), and style (dashed) in a single declaration. Although
you can control settings for each such characteristic per edge (in TRBL
order), it’s seldom necessary to do so.
Figure 12-3: Paragraphs get a thin purple
dashed outline on this page.
Feel free to explore other border and outline properties as you see fit. There
are quite a few of them, so give yourself some time to learn and play.
Dimension
Dimension properties define size information — namely, height and width —
to control where elements are placed on a Web page. In addition to basic
height and width, maximum and minimum values for such properties can
also be set. Sometimes called “min-max” properties, using these can be help-
ful to ensure that display areas are always at least as large as some minimum
value to make sure visual information doesn’t get lost. Min-max can be espe-
cially useful when text or images must float on a page. (Also check out the
CSS overflow, overflow-clip, clip, and visibility properties later
in this chapter, in Chapter 20, and on www.dummieshtml.com to see how to
handle odd, unexpected, or unwanted floating behavior.) Table 12-3 provides
a listing of dimension properties.
20_9780470916599-ch12.indd 195 11/30/10 12:25 AM
196 Part IV: Scripting and (X)HTML
Table 12-3 Dimension Properties
Property Description
height Sets element height
max-height Sets maximum element height
max-width Sets maximum element width
min-height Sets minimum element height
min-width Sets minimum element width
width Sets element width
height and width
We handle both height and width in a single example, where the image
(img) element is sized to occupy 10 percent of a paragraph for each of these
properties. This resizes the image to occupy no more than 10 percent of
the horizontal dimension of the browser’s display window, where height is
maintained to preserve the original aspect ratio (see Figure 12-4). Height and
width can also be specified using various absolute units of measure (pixels,
points, picas, ems, and so forth). Min-max values make sure that elements
never get too big or too small.
Figure 12-4: Use height and width properties to set element
size and preserve aspect ratio.
These properties are best played within an editor, along with resizing your
browser window, to best understand how things work.
20_9780470916599-ch12.indd 196 11/30/10 12:25 AM
197 Chapter 12: Top 20 CSS Properties
Fonts and Font Properties
CSS not only allows you to manage font properties galore, it also allows you
to associate fonts with specific (X)HTML elements, and even define arbitrary
sequences of fonts to use for those elements.
If you want to reference a font whose name includes any embedded spaces,
enclose that name in double quotation marks (not smart quotes) so that
browsers can identify and use them if available on their host machines.
As you can see in Table 12-4, the shortcut font property covers a huge range
of values, so dig into this carefully and master to use it!
Table 12-4 Font Properties
Property Description
font Shortcut for all font properties
font-family Sets font family (generic or by name)
font-size Sets font size (using typical units of measure)
font-style Sets font style (normal, italic, oblique)
font-variant Turns small caps on or off (small-caps, normal)
font-weight Sets font weight (bold, bolder, lighter, 100-900)
font-family
Use the font-family property to select fonts by name from your users’
installed collection. You can assign multiple comma-separated values (CVSs)
to this property in CSS markup. The browser will use the first match it finds,
starting from the leftmost specification. Always end a string of font speci-
fications with a generic font name, such as serif or sans-serif, so that
a local system can always use a default selection should all else fail (or be
absent). In Figure 12-5, we select Arial as our level one heading font, and we
use Lucida Console as our body (paragraph) font, but also show off a variety
of fonts including also Arial Black, Book Antiqua, Tahoma, Times New Roman,
Comic Sans, and Cooper Black.
20_9780470916599-ch12.indd 197 11/30/10 12:25 AM
198 Part IV: Scripting and (X)HTML
Figure 12-5: Fonts on display include heavy black fonts (Cooper and
Arial) plus other serif and sans serif choices.
font-weight
The font-weight property determines how light or heavy type is drawn
on a page. In our example in Figure 12-6, we identify all the named font-
weights as well as all the recognizable numeric font-weight values. Notice
that you really can’t tell much difference between bold and bolder, and that
the numeric values don’t show uniform gradations either. For most page
designers, bold is bold enough, and numbers 200–500 and 600–900 appear
interchangeable. Font designers often build black versions of font faces (for
example, Arial Black or Cooper Black), which might be better used with its
plain-vanilla counterpart (Arial or Cooper) to create heavier font weights or
more weight variations.
font-size
The font-size property is the setting that manages how big or small a font
looks onscreen. For truly small type, use points (pt) for sizing; most normal
paragraph fonts are usually 10pt to 12pt. Fonts smaller than 6pt are hard to
see onscreen. Sizing fonts in whole ems can get out of hand pretty quickly.
You can use the source page for the example shown in Figure 12-7 to conduct
your own font-sizing experiments pretty quickly, if you like.
20_9780470916599-ch12.indd 198 11/30/10 12:25 AM
199 Chapter 12: Top 20 CSS Properties
Figure 12-6: Although font weights are many, there isn’t
much difference onscreen.
Figure 12-7: Usable font sizes must be big enough to see,
and small enough not to overwhelm the page.
20_9780470916599-ch12.indd 199 11/30/10 12:25 AM
200 Part IV: Scripting and (X)HTML
Spacing Properties: Margin and Padding
Margins define space around the edges for block elements that background
colors don’t fill. Padding defines space around the edges for block elements
that background colors do fill. Table 12-5 holds these properties. Although
we discuss these two shorthand properties and their constituent properties
separately in the text that follows, we combine them in a single example in
Figure 12-8 to better compare and contrast them and also to show how they
work together. We also include borders to show where element box outlines
reside as well.
Table 12-5 Margin and Padding Properties
Property Description
margin Shortcut for all margin properties (TRBL)
margin-bottom Sets element bottom margin
margin-left Sets element left margin
margin-right Sets element right margin
margin-top Sets element top margin
padding Shortcut for all padding properties (TRBL)
padding-bottom Sets element bottom padding
padding-left Sets element left padding
padding-right Sets element right padding
padding-top Sets element top padding
margin
Like padding, margin is a shortcut property, where the constituent values
address TRBL (as we discuss earlier: top, right, bottom, and left) edges, in
that order. If you supply a single value for margin, it applies to all four edges
alike. Thus, for example, the CSS margin: 0.5em; is identical to margin-
top: 0.5em; margin-right: 0.5em; margin-bottom: 0.5em;
margin-left: 0.5em;.
padding
Like margin, padding is a shortcut property, where the constituent values
address TRBL edges, in that order. If you supply a single value for padding,
it applies to all four edges alike. Here again, the CSS padding: 0.5em; is
20_9780470916599-ch12.indd 200 11/30/10 12:25 AM
D
ow
n
lo
a
d
f
ro
m
W
o
w
!
e
B
o
o
k
<
w
w
w
.w
o
w
e
b
o
o
k.
co
m
>
201 Chapter 12: Top 20 CSS Properties
identical to padding-top: 0.5em; padding-right: 0.5em; padding-
bottom: 0.5em; padding-left: 0.5em;.
Close inspection of the figure shows that padding extends the text box around
the element, including the background. Using margin, on the other hand,
moves the edges of the text box away from the edge of the parent text box so
that content is indented all the way around. The combination of the two (see
the final pair of elements in Figure 12-8) extends the background around the
elements (padding) and moves the edges to accommodate their margins.
Figure 12-8: Margin and padding at work separately and together.
Positioning
Positioning controls (see Table 12-6) define where elements appear on a page,
how elements relate to one another, and how text flows (or doesn’t) around
various elements. The TRBL properties (top, right, bottom, and left) come
into play here, and elements may be positioned absolutely (with reference to
the origin, or upper-left corner of the page) or relatively (with reference to
whatever element encloses them).
HTML source code for all of the figures in this chapter (and the rest of the
book) are available at www.dummieshtml.com. There, you can find the rel-
evant source in the Chapter 12 section (labeled Figure 12-1, Figure 12-2, and
so on).
20_9780470916599-ch12.indd 201 11/30/10 12:25 AM
202 Part IV: Scripting and (X)HTML
Table 12-6 Positioning Properties
Property Description
bottom Sets bottom margin edge for positioned box
clear Blocks element edges to other floating elements
clip Clips absolutely positioned element
cursor Selects type of cursor for display
display Selects what box type an element should generate
float Turns box float on or off
left Sets left margin edge for positioned box
overflow Controls how content overflows an element box
overlow-clip Controls how content overflows an element box
position Selects positioning type for an element
right Sets right margin edge for a positioned box
top Sets top margin edge for a positioned box
visibility Turns element visibility on or off
z-index Assigns stack order for an element (numeric)
float
Use float to direct how text flows around an element. Floating has been
around ever since the days when various Web browsers provided nonstan-
dard HTML “extensions” to permit page designers to “float” images to the
right- or left-hand side of a Web page. CSS makes this standard, and applies it
equally to text blocks (such as paragraphs or lists) and to images. float can
take the values left, right, or none (the default) as we show in Figure 12-9.
Notice that both left and right float push atop the background for the h1
headings in Figure 12-9. (We show you how to fix this in the upcoming sec-
tion, “clear.”) This illustrates that managing float (and where img elements
get placed in paragraphs) can be important. Our final paragraph with no float
shows how graphics can plop onto the page wherever they’re called: That’s
not ideal, either, even if it doesn’t overlap with other elements on the page.
z-index
When you start positioning multiple elements on a page (as we did in Chapter
10 with a menu and a photograph), overlap can occur, and may sometimes
even be desirable. The z-index adds a third dimension for positioning,
along the lines of depth as in 3D coordinates (x, y, and z). On a Web page, the
20_9780470916599-ch12.indd 202 11/30/10 12:25 AM
203 Chapter 12: Top 20 CSS Properties
z-index value is purely relative. It’s used to manage display order, so higher
values sit “closer” to the front of the screen, and lower ones sit closer to the
back. In other words, when drawing boxes in which elements sit, a browser
gives precedence to those with higher numbers when some boxes with
lower numbers occupy the same space. In Chapter 10, we show how to use
z-index with a menu and a photo, and explain in the markup for Figure 10-4
that a negative z-index goes behind everything with a positive z-index.
For a quick illustration, check it out!
Figure 12-9: Float settings make it easy to move
items inside text blocks, but also show why
other positioning tools are absolutely necessary.
Exercise caution when using z-index, and make certain it’s defined for your
CSS menu (or anything else with dynamic properties that might overlap an
embedded object when performing a function call). Furthermore, an unde-
fined z-index can cause display issues when using CSS with Flash. Flash
often includes a default z-index in its action-script that may conflict.
clear
To solve the problem illustrated in Figure 12-9, where the images floated into
the heading backgrounds in the second and third paragraphs, using clear
enables designers to prevent such impingement. clear can take these
values: left, right, both, and none (the default). Because overlap occurs
after an image and text flows from left to right, adding clear: right; to
image markup fixes this problem, as shown in Figure 12-10.
20_9780470916599-ch12.indd 203 11/30/10 12:25 AM
204 Part IV: Scripting and (X)HTML
Figure 12-10: Use clear to enforce the margin
around an element.
cursor
Using the cursor property changes the appearance of the mouse cursor in
a Web browser as it hovers over specific elements. Numerous values can
be assigned to this property, so experiment to see how they look in various
browsers and whether you can use them to good effect. Figure 12-11 uses
four texture images, each with a different cursor so you can see how this
looks for yourself onscreen. (It’s hard to show dynamic behavior in a book,
so we made a collage of screenshots from the same underlying page.)
CSS supports as many as 17 different cursor styles, so be sure to spend some
time experimenting with different values that the cursor property can take.
Text
Some people might argue that text properties are the most important ele-
ments in the CSS collection. We don’t want to fight about this, for sure, but
instead recommend that you dig into Table 12-7 to see what’s available for
controlling text appearance and behavior while it’s on display using CSS. We
think you’ll be amazed, but we hope you’ll also be pleased.
20_9780470916599-ch12.indd 204 11/30/10 12:25 AM
205 Chapter 12: Top 20 CSS Properties
Figure 12-11: A composite of multiple
screenshots shows various cursor styles.
Table 12-7 Text Properties
Property Description
color Sets text color of text (name or hex code)
direction Specifies text/writing direction (ltr or rtl)
letter-spacing Manages space between characters in text
line-height Sets line height
text-align Sets horizontal alignment (left, right, justify,
center)
text-decoration Specifies decoration added to text
text-indent Sets indent for first line in a text-block
text-shadow Sets text shadow effect added
text-transform Controls text capitalization
vertical-align Sets vertical element alignment
white-space Manages space between words in text
word-spacing Manages space between words in text
20_9780470916599-ch12.indd 205 11/30/10 12:25 AM
206 Part IV: Scripting and (X)HTML
color
Use color to, um, establish color for text within elements, where colors
may be assigned by using names or hex codes. (See the online Cheat Sheet at
www.dummies.com/cheatsheet/html for a sizable list of such names and
values.) We show this capability throughout Chapters 9–11, and this chapter
as well, so we don’t illustrate it here.
line-height
The line-height property sets the height for the inline boxes (those allo-
cated for each line of text) in a text block of some kind. Use line-height as
an easy way to expand or compress the space between lines of text, as the
example in Figure 12-12 shows.
Figure 12-12: Various line heights show the
effects of varying this property.
20_9780470916599-ch12.indd 206 12/2/10 10:47 PM
207 Chapter 12: Top 20 CSS Properties
Pseudo Classes
Pseudo classes in CSS may seem a little strange at first: They take some get-
ting used to because they modify (X)HTML elements. That explains why Table
12-8 starts each pseudo class name with a colon (it acts as a delimiter with
the element it modifies, and it signals the presence of a CSS pseudo class).
Generally, pseudo classes serve to make content on Web pages more dynamic
and interactive, as you’ll discover when you get comfortable with them.
Table 12-8 CSS Pseudo Classes
Pseudo Class Description
:active Adds a style to an activated element
:after Adds content following an element
:before Adds content preceding an element
:first-child Adds a style to first child element inside another element
:first-letter Adds a style to first character in a text sequence
:first-line Adds a style to first line in a text sequence
:focus Adds a style to element with keyboard input focus
:hover Adds a style to element as you mouse over it
:lang Adds a style to any element with a specific language
attribute
:link Adds a style to unvisited link
:visited Adds a style to visited link
By far, the most widely used pseudo classes apply to (X)HTML links. In the
example in the next section, we combine :hover, :link, and :visited to
show how this works (and looks).
:hover, :link, and :visited
The pseudo classes :hover, :link, and :visited all apply to hyperlinks.
✓ :hover comes into play when the mouse cursor hovers over a hyperlink.
✓ :link applies style to a hyperlink that has not yet been visited.
✓ :visited applies style to a hyperlink that has been visited.
20_9780470916599-ch12.indd 207 11/30/10 12:25 AM
208 Part IV: Scripting and (X)HTML
All these behaviors are readily visible in the code created for Figure 12-13.
In our example, we change font-variant for visited links to small caps, and
use the linethrough (strikethrough) text decoration. Unvisited links use a
larger font with an underline. When you hover over a link, it turns bold and
red, and the cursor changes from a pointer to a hand.
Figure 12-13: Link-related pseudo classes change
the appearance of hyperlinks in response to
visitation state and mouse activity.
Best CSS Resources
The following collection of Web sites offers some outstanding references on
CSS and its proper use on well-crafted Web pages. The very first reference
from W3Schools.com is terrific, and provided much of the raw material on
which Tables 12-1 through 12-8 were based.
W3Schools.com
www.w3schools.com/css/css_reference.asp
This is a great online resource that offers CSS definitions and usage, related
pages, browsers supported, examples, and even the ability to “try it yourself”
in a controlled environment (beats fiddling HTML documents manually) at
www.w3schools.com/css/tryit.asp?filename=trycss_background.
20_9780470916599-ch12.indd 208 11/30/10 12:25 AM
209 Chapter 12: Top 20 CSS Properties
Firebug
This is by far the best browser resource for debugging and figuring out why
in the world your CSS or HTML pages aren’t behaving like you think they
should. Using this Firefox plugin, you can select elements on a page and see
which CSS properties are currently assigned, by file (if you have multiple
style sheets) or even by specific line in the source document. You can also
instruct this tool to temporarily add or ignore CSS declarations, which makes
it very easy to experiment with and debug your CSS markup.
Eric Meyer’s Reset
This URL above is a great example of a reset style sheet. A reset style sheet
seeks to reduce browser inconsistencies for settings that include default
line heights, margins, font sizes in headings, and so on. The general reason-
ing behind reset is discussed in Meyer’s May 2007 blog post entitled “Reset
Reloaded” (
reset-reloaded). Reset styles appear quite often in CSS frameworks, and
Meyer’s original “meyerweb reset” was incorporated into the Blueprint
home page (www.blueprintcss.org), among many others. Reset style
sheets are definitely worth learning about as well as applying to your own
Web design efforts. If you click the preceding link, you’ll see a text listing of
the entire reset.css style sheet.
Spoon Browser Sandbox
www.spoon.net/browsers
Unfortunately, CSS sometimes displays differently in different browsers.
To avoid designing what you think is a really great site only to discover
that everything gets jumbled in some other browser you didn’t try out, use
this site. Right now, Spoon Browser Sandbox is PC-only, but it allows you
to remotely launch Web browsers that aren’t even installed on your com-
puter. Use it to see what your pages look like in multiple versions of Internet
Explorer, Firefox, Opera, Chrome, and Safari.
W3C CSS Validation Service
Check CSS and (X)HTML documents with style sheets with this fine, free,
online tool. Point it at publicly accessible Web pages, upload files to it, or
drop code into a text box to check its contents.
20_9780470916599-ch12.indd 209 11/30/10 12:25 AM
210 Part IV: Scripting and (X)HTML
Web-Developer’s Handbook
www.alvit.de/handbook
This site is almost overkill, featuring a really big directory of CSS links and
general links related to Web design. Numerous sections on CSS cover daily
reading, showcases and galleries, tools and services, specifications, and
lots, lots more. Give yourself some time to chew through this compendium;
there’s an amazing amount of good stuff to masticate here!
YSlow
https://addons.mozilla.org/en-US/firefox/addon/5369
Drawing from a set of rules used on high-performance Web pages, YSlow ana-
lyzes Web pages to suggest ways to improve their performance. YSlow is a
Firefox add-on for the Firebug Web development tool. It grades Web pages by
using one of three predefined rulesets or a user-defined ruleset. In addition,
YSlow also offers suggestions to improve page performance, summarizes
page components, displays page statistics, and provides performance analy-
ses such as Smush.it and JSLint.
20_9780470916599-ch12.indd 210 11/30/10 12:25 AM
Chapter 13
Scripting Web Pages
In This Chapter
▶ Exploring what JavaScript can do for your Web pages
▶ Arranging content
▶ Opening new windows
▶ Checking user input
▶ Exploring more uses for JavaScript
When used in conjunction with your HTML markup, scripts — small programs that you add to your Web page — help your Web pages
respond to user actions. Scripts create the interactive and dynamic effects
you see on the Web, such as images that automatically change when visitors
move mouse pointers over them, additional browser windows that pop up
when a page loads, and animated or interactive navigation bars.
Because scripts are mini-programs, they’re often written in a programming
language called JavaScript. If you’re unfamiliar with the term, JavaScript may
sound like a Hollywood screenplay doused with coffee. However, it is actually
a scripting language built right into all popular Web browsers.
Fortunately, because of the Nobel Prize–worthy invention of “copy and
paste,” you don’t need to be a technoguru to add scripting to your Web sites.
The Web has many sites that feature canned JavaScript elements that you
can freely copy and then paste right into your Web page. (Chapter 14 lists
several of the best JavaScript sites.)
Many good Web page editors (such as Adobe Dreamweaver and Adobe
Fireworks) include built-in tools to help you create scripts — even if you
don’t know anything about programming.
In this chapter, you explore how scripting works inside your Web page by
dissecting three sample scripts written in JavaScript. If you’re interested in
learning more about JavaScript and how it works, please check out JavaScript
For Dummies, 5th Edition, by Emily Vander Veer, for more information and to
dive a little deeper into the JavaScript language itself.
21_9780470916599-ch13.indd 211 11/30/10 12:25 AM
212 Part IV: Scripting and (X)HTML
Finding Out What JavaScript
Can Do for Your Pages
Adding scripts to your Web site is much like those reality-TV makeover
shows that transform a house or a person’s appearance into something
completely new and wonderful. The same is true with JavaScript. You can
transform a plain, dull Web page into an interactive and dynamic Web extrav-
aganza to bring joy to your visitors for years to come. (Okay, maybe we’re
exaggerating just a tad, but you get the point.)
For example, if you visit Dummies.com (www.dummies.com) and click the
blue Search button next to the Start Exploring box without entering a term to
search on, the browser displays a nice warning box that reminds you to enter
a search term before you actually search, as shown in Figure 13-1.
Figure 13-1: The search term is empty — that is, missing.
A short script verifies whether you entered a search term before the engine
runs the query:
✓ If you enter a search term, you don’t see the warning.
✓ If you don’t enter a search term, the script built into the page prompts
the dialog box to appear.
21_9780470916599-ch13.indd 212 11/30/10 12:25 AM
213 Chapter 13: Scripting Web Pages
This bit of scripting makes the page dynamic, which means that it adds pro-
grammed functionality to your Web pages, allowing them to respond to what
users do on the page (for example, filling out a form or moving the mouse
pointer over an image). When you add scripts to your page, the page inter-
acts with users and changes its display or its behavior in response to what
users do.
The page URL doesn’t change, and another browser window doesn’t open
when you try to search on nothing. The page responds to what you do with-
out sending a request back to the Web server for a new page. This is why the
page is considered dynamic.
If you try this trick without using a script (that is, without dynamic func-
tionality), the browser would send the empty search string back to the Web
server. Then the server would return a warning page reminding the user to
enter a search term. All the work would be done on the Web server instead
of in the Web browser. This is slower because the request must first go to
the server, and then the server must transmit the warning page back to your
browser — and thus the server feels much less fluid to the user. It’s much
better to just click a button on the page and have an alert pop up instantly to
help the user.
In the following sections, we showcase three common ways in which
JavaScript can be used in your Web pages.
JavaScript is not Java
In the late 1990s, the originators of the
JavaScript scripting language wanted to ride
the coattails of the massive popularity of the
Java programming language, so they gave it
a catchy name — JavaScript. However, when
they made this decision, they also introduced a
lot of confusion given the similarity of the two
names. To clarify, the full-featured Java pro-
gramming language isn’t a scripting language
on the Web. Java is a descendent of the C and
C++ programming languages. Programmers
can create Java applications that can run on
Windows, Macintosh, Linux, and other com-
puter platforms:
✓ On the client side, Java is used to create
applets (small programs that download
over the Net and run inside Web browsers).
Because Java is designed to be cross-
platform, these applets should run identi-
cally on any Java-enabled browser.
✓ On the server side, Java is used to create
many Web-based applications.
21_9780470916599-ch13.indd 213 11/30/10 12:25 AM
214 Part IV: Scripting and (X)HTML
Don’t worry about the details of the JavaScript code in the following exam-
ples. Just focus on how JavaScript scripts can be pasted into your Web page
to work alongside your HTML markup.
Using JavaScript to Arrange
Content Dynamically
JavaScript can be used with Cascading Style Sheets (CSS; covered in Chapters
9–12) to change the look of a page’s content in response to a user action.
Here’s an example: Two writers share a blog named Backup Brain (www.
backupbrain.com). One of the writers prefers small, sans serif type, and
the other one finds it easier to read larger, serif type, so the blog has buttons
that change the look of the site to match each person’s preference. Of course,
site visitors can use the buttons to switch the look of the type, too, and the
site remembers the visitor’s choice for future visits by setting a cookie (a
small preference file written to the user’s computer). Figure 13-2 shows the
two looks for the page.
Figure 13-2: Change how text displays.
21_9780470916599-ch13.indd 214 11/30/10 12:25 AM
D
ow
n
lo
a
d
f
ro
m
W
o
w
!
e
B
o
o
k
<
w
w
w
.w
o
w
e
b
o
o
k.
co
m
>
215 Chapter 13: Scripting Web Pages
JavaScript and CSS create this effect by switching between two style sheets:
✓ The sans serif style sheet, sansStyle.css
✓ The serif style sheet, serifStyle.css
Listing 13-1 shows the source code for an example page that contains the
switching mechanism shown in Figure 13-2:
✓ When a user clicks the Sm Sans button on the page, the
styleSwitcher.js script referenced in the element runs
and switches the active style sheet to sansStyle.css. (.js is the file
extension that’s used with JavaScript files, as in the src value for the
script element in Listing 13-1.)
✓ When the user clicks the Lg Serif button, the same script switches to the
serifStyle.css style sheet.
Listing 13-1: Style Switching
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“”>
Style Changer
<link href=”sansStyle.css” rel=”stylesheet” rev=”stylesheet”
title=”default” />
<link href=”serifStyle.css” rel=”alternate stylesheet”
rev=”alternate stylesheet” title=”serif” />
@import url(“complexStyle.css”);
<script src=”styleSwitcher.js” language=”javascript1.5”
type=”text/javascript”>
Change your font:
<input type=”button” class=”typeBtn” value=”Sm Sans”
onclick=”setActiveStylesheet(‘default’)” />
<input type=”button” class=”typeBtn2” value=”Lg Serif”
onclick=”setActiveStylesheet(‘serif’)” />
Replace this paragraph with your own content.
21_9780470916599-ch13.indd 215 11/30/10 12:25 AM
216 Part IV: Scripting and (X)HTML
You can see the example page for yourself at www.javascriptworld.com/
js5e/scripts/chap16/ex6/index.html.
This example relies on several different files (HTML, CSS, and JavaScript).
You can download all these files, if you’d like, from www.javascriptworld.
com/js5e/scripts/index.html.
The Font Style Changer files appear in the Chapter 16.
Working with Browser Windows
JavaScript can tell your browser to open and close windows.
You’ve probably seen an annoying version of this trick: advertising pop-up
windows that appear when you try to leave a site. (Let’s not go there.) This
technology can be used for good as well as evil, though. For example, you
can preview a set of big image files with small thumbnail versions. Clicking a
thumbnail image can perform such actions as
✓ Opening a window with a larger version of the image.
✓ Opening a page with a text link that opens a window with an illustration
of that text, as shown in Figure 13-3.
Figure 13-3: When you click the link, a pop-up window appears with
a picture in it.
21_9780470916599-ch13.indd 216 11/30/10 12:26 AM
217 Chapter 13: Scripting Web Pages
The code required to do this sort of pop-up window is fairly straightforward,
as Listing 13-2 shows with its invocation of the window.open function.
Listing 13-2: Pop-up Windows
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“”>
Opening a Window
function newWindow() {
catWindow = window.open(“images/pixel2.jpg”, “catWin”,
“width=330,height=250”)
}
The Master of the House
Click on His name to behold He Who Must Be Adored
Pixel
Pop-up windows are no longer a best practice and should be used with cau-
tion. Overuse of pop-up windows can backfire on you. Many Web sites use
pop-up windows to deliver ads, so users are becoming desensitized (or hos-
tile) to them and simply ignore them (or install software that prevents them).
Also, some Web browsers — such as Firefox, Safari, and Internet Explorer —
automatically block pop-up windows by default these days. Before you add
a pop-up window to your site, be sure that it’s absolutely necessary. Then,
alert your visitors that you’ll be using pop-ups so they can instruct their Web
browsers to permit them to appear.
Soliciting and Verifying User Input
A common use for JavaScript is to verify that users have filled out all the
required fields in a form before the browser actually submits the form to
the form processing program on the Web server. Listing 13-3 places a form-
checking function, checkSubmit, in the element of the HTML
page and references it in the onsubmit attribute of the element.
21_9780470916599-ch13.indd 217 11/30/10 12:26 AM
218 Part IV: Scripting and (X)HTML
Listing 13-3: Form Validation
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“”>
Linking scripts to HTML pages
function checkSubmit ( thisForm ) {
if ( thisForm.FirstName.value == ‘’ ) {
alert(‘Please enter your First Name.’);
return false;
}
if ( thisForm.LastName.value == ‘’ ) {
alert(‘Please enter your Last Name.’);
return false;
}
return true;
}
<form method=”post” action=”/cgi-bin/form_processor.cgi”
onsubmit=”return checkSubmit(this);”>
First Name:
Last Name:
This script performs one of two operations if either form field isn’t filled in
when the user clicks the Submit button:
✓ It instructs the browser to display a warning to let the user know that he
forgot to fill in a field.
✓ It returns a value of false to the browser, which prevents the browser
from submitting the form to the form processing application.
If the fields are filled in correctly, the browser displays no alerts and returns
a value of true, which tells the browser that the form is ready for the Web
server. Figure 13-4 shows how the browser displays an alert if the first name
field is empty.
21_9780470916599-ch13.indd 218 11/30/10 12:26 AM
219 Chapter 13: Scripting Web Pages
Figure 13-4: A good use of JavaScript is to validate form data.
Although this example only verifies whether users filled out the form fields,
you can create more advanced scripts that check for specific data formats,
such as using @ signs in e-mail addresses and using only numbers in phone
number fields.
When you create forms that include required fields, we recommend that you
always include JavaScript field validation to catch missing data before the
script finds its way back to the server. Visitors get frustrated when they take
the time to fill out a form only to be told to click the Back button to provide
missing information. When you use JavaScript, the script catches any missing
information before the form page disappears, which allows users to quickly
make changes and try to submit again.
But Wait . . . There’s More!
You can do much more with JavaScript. The following list highlights several
common uses of the scripting language:
✓ Detect whether a user has a browser plug-in installed that handles multi-
media content
✓ Build slide shows of images
✓ Automatically redirect the user to a different Web page
✓ Add conditional logic to your page so that if the user performs a certain
action, other actions are triggered
✓ Create, position, and scroll new browser windows
✓ Create navigation bars and change the menus on those bars dynamically
✓ Automatically put the current date and time on your page
✓ Combine JavaScript and CSS to animate page elements
21_9780470916599-ch13.indd 219 11/30/10 12:26 AM
220 Part IV: Scripting and (X)HTML
An innovative use of JavaScript occurs in Gmail, the free Web-based e-mail
service from Google, which you can find at www.gmail.com. Gmail uses
JavaScript to load an entire e-mail user interface into the user’s browser,
which makes Gmail much more responsive to user actions than most other
Web-based mail programs. Gmail uses JavaScript to keep to an absolute mini-
mum the number of times the page has to fetch additional information from
the servers. By doing much of the processing in the user’s browser, the Gmail
Web application feels more like an e-mail program that runs on your com-
puter. Figure 13-5 shows the JavaScript-powered Gmail interface. It’s a great
example of the power of JavaScript.
Figure 13-5: The Gmail interface is powered by JavaScript.
Server-side scripting
JavaScript is a scripting language that runs
inside the browser, but there are other script-
ing languages that run on the server side, such
as Perl, ASP (Active Server Pages), PHP (PHP
Hypertext Preprocessor, an (X)HTML embedded
scripting language), Python, .NET, and others.
Programs written in these languages reside
on the server and are called by the Web page,
usually in response
Các file đính kèm theo tài liệu này:
- Getting Creative with Colors and Fonts.pdf