Vous êtes sur la page 1sur 39

To open the about.

htm file:
1. Useyourtexteditorto openabouttxt.htm folderin yourData
fromthetutorial.OS/tutorial
Files.
Savethefileasabout.htm.
yournaneandthe datein thecomment
2. Enter tagat thetopof thefile.
5. Saveyourchanges yourtexteditoropen.
to thefile,butteave
yourWebbrowser
4. Start Figure
andopenabout.htm. J-2showsthecurrent formatofthepage.

TheAbout Web page

.8-boutArcadrum Park Map Water lides Go Karts Roller Coasters

Welcome
Excihng advenhxesawartyou at Arcadrum,yow affordablefamilyfi-rncenter.The park is located 5 milesnorthwestof Derby -
closeto manyofGeorgra'sscenicuronders.Arcadium offers over 50 ndes,:ncludingsome ofthe state'smost excihngroller
coasters andwater rides. There's also plenty offi.rnforthe yor.ugerkrds,includrnglro separateL,rddrepools and specialrides
for thekrds.

fucadiumis opensevendays a week:

. Apr:l 1 up to Memorial Day weekend: 10amto 5pm


. MemonalDay weekendthroughLabor Day: 9am to 11pm
. Theday afterLabor Day tkough October 31: 10m to 5pm
. November1 *rough Mrch 3l : closed

-Arcadium is easy on your budget. Compare our low darlyrates to the brg cha:nparks. You cm chooseto pr.rchasea goid
tichetfor any twenty rides, a plabnm hcLet for thirty rides, or for best value, a firll-day pass to nde as marrytimes as you
want,whereveryou want. Specialoff-seasonand largegroup rates are available.

A n a d i u m . H W 1 2 , E x i t 4 9 l . D e r b y , G A 2 0 0 1 0].( 8 0 0 )J J J - 5 4 3 1

Tomis satisfiedwith the page'scontent,but he wantsyou to work on the appearance.


Hewantsto seemorecolor and the useof differentfontsin the page.He alsowantsyou
toaddphotographs of peopleenjoyingthemselves at the park.Tomwantsa visuallypleas-
ingpagethatwill draw usersinto the siteand givea good impression of the park.
Youdecideto startthis projectby creatingan overallcolor schemefor the page.The
firststepisto learnhow HTML handlescolors.lf you'veworkedwith graphicssoftware,
you've probablymadeyour color choiceswithoutmuchdifficultydue to the interfaces
thatthose applicationsemploy.Theseinterfaces, knownasWYSIWYG(whatyou seeis
whatyouget),allow you to selectcolorsvisually.Selecting colorwith HTML is somewhat
lessintuitive,becauseHTML is a text-based languageand requiresyou to defineyour col-
orsin textualterms.Thiscan be done in two ways:by specifyingeithera color valueor a
colorname.Let'sstartby lookingat color values.

ColorValues
Using
A colorvalueis a numericalexpression that preciselydescribes
a color.To betterunder-
standhownumberscan represent colors,it helpsto reviewsomeof the basicprinciplesof
colortheoryand how they relateto the colorsthat your monitordisplays.
White light is made up of three primary colors (red, green, and blue) mixed at equal
llllllll intensities.By adding only two of the three primary colors we can generatea trio of com-
plementarycolors: yellow, magenta,and cyan (seeFigure3-3).To generatea wider range
of colors, we simply vary the intensityof the red, green, and blue light. For example,
orange is createdfrom a high intensityof red light, a moderate intensityof green light,
a n d a n a b s e n c eo f b l u e l i e h t .

Primarycolor modelfor light

1l
ll
,,,,,

Yourcomputermonitorgenerates colorsby emittingred,green,and blue lightat differ-


Softwareprograms,
ent intensities. suchasyourWeb browser,instructyour monitorto
createcolorsmathematically. by a tripletof numberscalledan
Eachcolor is represented
RGBtriplet,whosevaluesare basedon the strengthof its red,green/and blue compo-
nents.Thistriplethasthe form

rgb(red, green, bTue)

ttl wherered,green,and blue arethe intensityvaluesof the red,green,and blue compo-


nents.The intensityvaluesrangefrom 0 (absence of color)to 255 (highestintensity).
For
example,the RGBtripletfor whiteis (255,255,255),indicating thatred,green,and
blueareequallymixedat the highestintensity. Orangehasthe triplet(255,165,0)
because it results
from a mixture of high-intensity
red,moderate-intensity green,andno
blue.Youcan alsoentereachcomponent value as a percentage,with 100% representing
the highestintensity.In this form, you would specifythe color orange with rgb (1000/',
65%,OV").The percentage form is lesscommonlyusedthan RGB values.RCB triplets
can specify2563(6.7 million)possible colors,which is morecolorsthanthe human
eyecan distinguish.
In mostsoftwareprograms, you makeyour color choicesusingvisualclues,sometimes
withoutbeingawareof underlyingRCBtriplets.Figure3-4 showsa typicalcolordialog
box in which usersmakecolor selections basedon a color'sappearance, with the RCB
valuesappearing alongside the colorselection.
A typicalcolorsdialogbox

Originally, HTMLrequired thatcolorvaluesbe enteredusingthe hexadecimal system.


A hexadecimal is a numberexpressed in base16 ratherthan in the base10 form we use
everyday.In base10 counting,you usecombinationsof 10 characters (0 through9) to
represent numerical values.The hexadecimal systemincludessix extracharacters: A
(for10), B (for11),C (for12),D (for13),E (for14),and F (for15).Forvalues above15,
youusea combination of those16 characters. To represent a numberin hexadecimal
terms, youconvert thevalueto multiplesof 16, plusa remainder. Forexample,16 is
e q u taol ( '6l x 1 ) + 0 / s o i t s h e x a d e c i mr a
e lp r e s e n t a t i o n i s ' 1 0 . ' A v a l u2e1oi sf e q u a l
to(16x 1)+ 5, for a hexadecimal representation of 15. Thenumber255 is equalto
(16x 15)+ 15,or FFin hexadecimal format(remember that F = 15 in hexadecimal). ln
thecase of thenumber255, the first F represents the numberof times16 goesinto 255
(which is15),andthe secondF represents the remainderof 15. A color valuerepre-
sented asa hexadecimal numberhasthe form

*redgreenbJue
g ,r e e n ta n d b l u e a r e t h e h e x a d e c i m avl a l u e s o ft h e r e d , g r e e n , a n d b l u e c o m -
wherered
Thus,thecoloryellowcould be representedeitherby the RGBtriplet(255,255,0)
inthehexadecimalform#FFFF00.
Atthispointyou mightbe wonderingif you haveto becomea mathmajorbeforeyou
$artaddingcolorto yourWeb pages.Fortunately,this is not the case.Youcan specify
in yourWeb pageswith stylesthat useRCBtripletsratherthanthe hexadeci-
colors
form.However, you mayseeHTML codethat setsa color valueto somethinglike
and now you know what that means,even if you can't tell at a glance that it
the color orange.
WhileRCBtriplets candistinguish over16.7millioncolors,the numberof colorsthata
actuallydisplays dependson the user'smonitor.Somemonitorsarecapableof
ingonly256differentcolors,and thusbrowserson thesecomputersare limitedto
r palette,or selection,of colors.When a browserencounters a color not in its
it attemptsto renderthe color usinga processcalleddithering,in which the
combines similarcolorsfrom its paletteto approximatethe originalcolor's
. Dithering can resultin an imagein which individualpixelsstandout,and
fuzzy when compared to the original (seeFigure3-5).
appears
Color dithering

originalimage

dithered image

One way to avoidthis problemis to stickto colorsfrom the safetypalette-a palette


of
216 colorsknownasweb-safecolors,which areguaranteed not to'bu dith"r"d by any
web browser.lntensitiesin the safetypaletteare limitedto the valueso, s1,102, 1s3,
204, and255 (or00, 33, 66,99, CC,and FFin hexadecimar). Thus,a colorvaluesuchas
(51,153,255)would be partof the safetyparette,while a colorvalue
suchas (192,0,22s)
would not.Youcan view the color valuesthat are partof the Safetypaletteby opening
a
demopagefrom your DataFiles.

t: y:"* the colorsof the saferypalerte:


1. Useyourbrowser to opendemo-safety-palette.htm
fromthetutoria[.0J/tutorial
folderin
yourDataFiles.
2. Studythetables
atthebottom ofthepage,shownin Figure
J-6,to verifythatnocolors
showanydithering.

The colors of the Safetypalette

Close
thepagewhenyouarefinished.
yourcolorselections
Bylimiting to the colorsof the safetypalette,you can be assured
yourimages will appearthe sameto all usersregardless of monitorresolution.
because monitorsnow commonlysupporthighercolor resolutions, the needfor
safetypaletteis not asgreatas it once was.

youdon'twantto usecolorvalues,you can alsospecifycolorsby name.HTMLand


the 16 colornamesdisplayedin Figure3-7.You'vealreadyusedsomeof
support
colornamesin previoustutorialsto insertcoloredIinesinto your pages.

The16 basiccolor names

Color Name RGB Tfiplet Hexadecimal Color Name RGB Thiplet Hexadecimal

(0,255,255) OOFFFF (0,0,128) 000080

(0,0,0) 000000 (128,128,0) 808000

(0,0,255) 0000FF (128,0,128) 800080

(255,0,255) FFOOFF (25s,0,0) FF0000

(128,128,128) 808080 (192,r92,192) COCOCO

(0,I 28,0) 008000 (0,128,r28) 008080

(0,25s,0) 00FF00 White '/r55 ,55 t55 t FFFFFF

(128,0,0) 800000 Yellow (2ss,2ss,o) FFFFOO

colorsarenota lot, so mostbrowserssupportan extendedlistof 140 color


Sixteen
including suchcolorsascrimson,khaki,and peachpuff.Whilethisextended color
isnotpartof thespecificationfor eitherHTMLor XHTML,you can feelconfidentthat
users'
browserswill supportit.

the extendedcolor list:


yourbrowserto opendemo_color-names.htm
fromthetutorial.0J/tutorial
folderin
DataFiles.
thelistof 140extended
display
tables colornames, alongwiththeircolorvalues
bothasRGB triplets form(seeFigure
andin hexadecimal 5-8).The16color
byHTML
supported andXHTML arehighlighted
in thetable.Web-safe
colors
are
inboldface.
A partial list of extendedcolor names

rqusnanne 121,255,212 #7FFFD4


tzure 240,255,255 #FOFFFF

reqe 245,245,228 #F5F5DC


lrsque 255,228,1S5 #FFE4C4
rimt {o,e,D ff00000
llanchedElnond 255,235,205 #FFEBCD
luc (r,0,2551 io000fF
tueviolet (138,43,?26) #8A2BE2
(16s,42,42) #452A?A
'wood 84,135
?22,1 #DE9887

5. Closethe pagewhenyouarefinished.

Dependingon the designrequirements of your site,you maysometimesneedto use


colorvaluesto getexactlythe rightcolor;howeverif you know the generalcolorthatyou th:
need,you can usuallyenterthe color namewithouthavingto look up its RGBvalue. br<
Arr
the
Defining Foreground and Background Colors
With HTMLyou can definethe foregroundand backgroundcolorfor eachelementon your
page.Theforeground coloris usuallythecolorof thetextin an element,althoughin thecase
of horizontallines,it definespartof a line'scolor.Thestyleto definethe foregroundcolor is
color: coTor

where coTor is either the color value or the color name. The style to define the background
color is

background-color: coTor

lf you do not definean element's


color,it takesthe colorof the elementthatcontainsit.
Forexample,if you specifyredtext on a graybackgroundfor the Web pagebody,all ele-
mentswithin the pageinheritthatcolorcombinationunlessyou specifydifferentstylesfor
specificelements.
Tomsuggests thatyou changethe textcolor in the Aboutpagefrom the defaultblackto
a shadeof brown.Youdecideto usethe Web-safecolor value(153,102,102). You'llalso
setthe backgroundcofor of the page to white. While mostbrowsersassume white back-
a
groundcolor by default,it'sa good ideato makethisexplicitin casesomeusershavedif-
ferentsettings.Because you'reapplyingthe color changeto the entirepage,you'll addthe
inlinestyleto the bodyelement.

To set the page's foreground and backgroundcolors:


1. Return fitein yourtexteditor.
to theabout.htm
the<body>
2. Locate tagandinsert theinlinestyle:
<body style="coIor: rgb(153,102,102) ; background-color: white">

SeeFigure
3-9.
Settingpageforegroundand backgroundcolors (

< b o d ys t y l e = " i : r r l [ r r : r q- t t ( . 15 : {. 1 r i ] , : l - U l J l [ r , r ' , r: l] r r : r r - r [ r L 1 - c l : lul rirl -r r: i t e "


' stvl e-=
<n "t ext -al i qn : cent er " >
.lrg _src="1ogo { i.t " a l t = " n c c l D I u F r " , / >
<hr ./>
<a hi'ef="abouth . t m " > A b o u t n r c a d i u m < / a > & n b s p ;& n b s p ;& n b s p ;
< a h r e f = " m a ph. t m " > c a r k r a a p < , / a > & n b s p ;& n b s p ;& n b s p ;
< a h r e f = " w a t e r .h t n " > ' $ i a t e FR i d e s < , / a >& n b s p i& n b s p .&; n b s p ;
< a h r e f = " k a r t s .h t m " > G oK a r t s < , / a >& n b s p & ; nbsp& ; nbsp;
< a h r e f = " r i d e s .h t m " > n o I' le r c o a s t e r s < , / a >
</p>

yourchanges
Save to thefile.
orrefresh
Reload about.htm in yourWebbrowser
andverifythatthetextcolorhas
toa medium
changed brown.

Youcanapplyforeground and background colorsto any pageelement.Tomsuggests


thatthe"Welcome" title might look if
better it wasformattedaswhitetexton a medium
brown The
background. brown background would then act as a dividerbetweenthe
Arcadium logoandthe main page body. To change the color,you add an inlinestyleto
thehl elementcontaining the text.

the color schemefor the h1 heading:


change
inyourtexteditor.
toabout.htm
the<h1>tagandinsert
thefollowing in Figure
inlinestyleasshown 3-10.
style="color: white; background-color: rgb( 153, L02 tt02)">

serrng rne corors ror an n-l neaorng


@

-l -l -l
fi1 styl e=' c,:l ,:r : r,ilrit e; Lr4{_r.Llr Ur_{i ru-l_rJ ILrr . | '_l}J!-!_'_' i.i _
! l v L r l , ' t_ ! J 4r? rl , r I >
trielcofle
/h1>

mwould likeyouto change


also thecolorofthehorizontallineatthebottomofthepage
matchthepage'snewcolorscheme
the<hr/> tagatthebottomofthefileandinserttheinlinestyleshownbelow:
cate
rr style="color: rgb( L53,L02,102) ; background-color:
D ( 1 5 3 , 1 0 2L,0 2 r " / >
veyourchanges
to thefile.
about.htm
fresh inyourWebbrowser andverifythatthecolorscheme
fortheh1head-
and
tr the line
horizontal has (see
changed Figure 3-11).

e
I

Window
Reference
default,
browsers displayWeb pagetext in a singlefont, usuallyTimesNew Roman.
You a differentfont for any pageelementusingthe style
canspecify

font-fanily: fonts

wherefonts isa comma-separated listof fontsthatthe browsercan usein the element.Font


namescanbeeitherspecificor generic.A specificfont is a font suchasTimesNew Roman,
orGaramond,
Arial, which is actuallyinstalledon a user'scomputer.A genericfont is a name
general
forthe of a font'sappearance.
description Browsers recognizefivegenericfonts:serif,
monospace,
sans-serif, cursive,and fantasy.Figure3-12showsexamplesof each.Notethat
eachgeneric
fontcanrepresent a wide rangeof designs.

Genericfonts

serif defg defg defg


sans-serif defg defg defg
monospace de fg defg deFg
cursive defg ,41,1" defg
fantasy e"fg detg lDEf,'6

Oneissue with genericfontsis that you cannotbe surewhich font a givenuser'sbrowser


willuse.Forthisreason, HTMLandXHTMLallowyou to specifya listof fonts.Youlistthe
fontsyouwantthe browserto try first,in orderof preference,
specific and then end the Iist
withthegenericfont.lf the browsercannotfind anyof the specificfontsyou list,it substitutes
thegeneric
font.Forexample,to specifya sans-serif fon! you could enterthe followingstyle:

font-fanily: Aria1, Helvetica, sans-serif

Thisstyletellsthebrowserto firstlookfor theArialfont;if Arial is not available,it tells


thebrowserto lookfor Helvetica;if neitherof thosefontsis available,it tellsthe browserto
thegeneric font definedby the user'ssystem.
sans-serif
Toseehowthegenericfontsappearon your browser,a demo pageon text styleshas
beenprepared for you.

viewyourbrowser'sgenericfonts:
Useyourbrowser to openthedemo_text_styles.htm filefromthetutorial.0J/tutorial
ofyourDataFiles.
folder
Thisdemo pagecontainsa collectionofthestylesyou'ilbelearning aboutinthissession,
thePreview
Initially, boxdisplays thesample textin thedefaulttextstyleofyourWeb
browser.Youcanspecifydifferent sampletextbyselecting thedefaulttextandeditingit.
Youcanselect stylevalues
different usingtheinputboxes anddrop-down listboxesonthe
ofthepage.Entering
leftside orselecting "default"in aninputordrop-down listbox
causesthepageto usethedefaultstyle.Pressingthetabkeyactivates a stylechange. The
codeforthenewstyleappears in thepage'slower-right corner.
We'[lworkwiththisdemopagethroughout the restof thesession.
Youmaywantto keep
the pageopenasyouexploreotherstyles.
Trouble? Thisdemopagemaytookslighttydifferentdepending
onyourbrowser. i! 1rol
,fui.r"
It'sgenerallygood practicenot to usemorethantwo differentfont faceswithin a single
page,unlessyou'retryingto createan interesting and strikingvisualeffect.Seriffontsare
bestreadin largeblocksof text like paragraphs.Sans-serif fontscan work well eitheras
paragraph textor as headingsand subheads. You'llapplythis principleto theAboutpage
by changingthe font for the h1 headingand the listof linksto a seriffont.

To changethe fonts for the heading and list of links:


1. Return
toabout.htm inyourtexteditor.
thefirst<p>taginthefileandinsert
2. Locate thefollowing
inline
style:
font-famj-Iy: Arial, Helvetica, sans-serif

Besureto usea semicolon


to separate
thisnewstylefromthetext-align
stylealready
entered.
5. Goto the<h1>tag,andaddthefollowing style:
font-family: Arial, Helvetica, sans-serif
Besure
to usea semicolon thisstylefromtheprevious
to separate youentered.
styles You
maywantto insert lineto makeyourcodemorereadable.
thisstyleona separate Figure
3-'14
shows
therevised code.

Choosingfonts (
< b o d vs t v l e = " c o l o r : r q b ( 1 5 3 . 1 0 2 . 1 0 2 ) : b a c k q r o u n d - c o l o:r w h i t e " >
<'p s i y l a - = " t e x t - a l i q n : - c d n t e i ;f i n r : - F a r n i l t ' : - & . r i a lF, e l , r E : i , - a ,i a n s - r p r i f " >
< i f i r gs r c = " 1 o q o . { i t " a l t = " A R c A D r u M/"> '
<or />
< a h r e f = " a b o u t . h t m " > n b o u t A r c a di u m < / a > & n b s p ;& n b s p ;& n b s p ;
< a h r e f = " m a ph. t m " > P a r kn t a p < , / a& > n b s p& ; n b s p& ; nbsp;
< a h r e f = " w a t e r . h t n " > u a t e r n . i d e s < , / a >& n b s p ; & n b s p ; & n b s p ;
< a h r e f = " k a r t s , h t n " > c o t < a r ts < / a > & n b sp ; & n b sp ; & n b sp ;
< a h r e f = " r i d e s .h t m " > R oIl e r c o a s t e r s < / a >
</p>
< h 1s t y l e = " c o l o r : w h i t e ; b a c k g r o u n d - c o l o rr: g b ( 1 - 5 3 , 1 0 2 , 1 0 2 ) i
i=rrL-Farrj li : H=l?eti :a.,.jd;rj-jErif'l>
.,oriil.

* r

About
ArcadiumParkMap WaterRides GoKarts Roller
Coasters

Youcanalsousethe deprecated<fonb tag to changethe font of a sectionof text. See


windowfor details.
r reference

-
ReferenceWindow
rt for an alemant'q tFvt rrqc fhe qtvle

;:
#tha ge
"ndirg

,rr.n,r-*,*;;
;i*g:*:X-;t* :*:::l
L
element.lf the pagebody is setto a 1Optfont,for example,a paragraph
inthe page setto a font sizeof 0.8emappearsas Bptfont.The ultimatecontaining
isthebrowseritself,which hasits own defaultfont sizefor bodytext.Settingthe
textto 0.8emreducesthe font sizeto 9O"hof the browser's defaultfont size.
Youcanuserelativeunitsto makeyour pagescalable,which allowsthe pageto be
the sameway no matter how a user'soutput device is configured. For example,
usermayhavea largemonitorwith the defaultfont sizefor bodytext setto 1Bpt.
usermayhavea smallermonitorand a defaultfont sizeof 12p1.Youwant your
textto be about50% largerthanthe bodytextfor eitheruser.Althoughyou can't
thedefaultfont sizefor a givenuser'soutputdevice,usinga valueof 1.5emfor the
ensures thatit is sizedappropriately on eithermonitor.Notethatyou can achieve
sameeffectby expressing a font sizeas a percentage defaultfont size.
of an element's
example,thestyle

ze: L50E

the headingto appear 50"/olarger than the default size. Eventhough point size is
most commonly usedunit in desktoppublishing, oftenlead
the benefitsof scalability
designersto optfor the em unit overpointsor otherabsoluteunits.
Thefinalunitof measurement we'll examineis the pixel,which represents a singledot
theoutputdevice.Because the pixel is the mostfundamental unit,for mostlength
, thebrowserassumes that a valueis expressedin pixelsif no unit is speci-
Thus,to setthefont sizeto 20 pixels,you could useeitherof the followingstyles:

: 2Opx
izet 20

Beaware thattheexactsizeof a pixeldependson the outputdevice.Differentdevices


different resolutions, which aretypicallyexpressed in termsof dotsper inch or dpi.
example, a 600dpi printerhas six times more pixels per inchthana typicalcomputer
. Whileyoumightassume thatthiswould causea 100 pixel lengthto appear
whenyouprinta page,browsers adjustpixelsizesto ensurethata printoutmatches
computer screen image. Thus, not all pixelsareequal!
youcanexpress font sizesusingsevendescriptive keywords:xx-small,x-small,
medium, large, x-large,or xx-large. Each browser is configured to displaytext at a
size for each of these kevwords, which enables vou to achieve someuniformitv
browsers.You can also use the relativekeywords "larger" and "smaller"to makea
onesize larger or smaller. For example, if a browser had been configured to display
element'stext in the smallsize, you could move it to the medium sizeby using either
following styles:
ze: medlum
ze: larger

withanalmostdizzyingarrayof possiblefont sizevalues,you'rereadyto apply


knowledge to the listof linksandthe h1 heading.RecallthatTomwantedthe text in
elementsto be smaller. Youdecideto setthe font sizeof the listof linksto O.Bem
thesizeof thebodytext)andthe font sizeof the h1 headingto 1.5em(50%larger
bodytext).

the font size for the heading and list of links:


toabout.htm inyourtexteditor.
styleto thefirst<p>tag.Besureto separate
thefollowing thisnewstylefromthe
oneswitha semicolon.
: 0.8em
Settingthe FontSize
Tom likesthe font change,but feelsthatthe sizesof the Welcomeheadingand the listof
linksaretoo large.He would like you to reducethe font sizesof theseelements.
Thestyle
to changethe font sizeof the textwithin an elementis
font-size z Tength
whereTength is a lengthmeasurement.
Lengths
can be specifiedin four differentways:
. with a unitof measurement
o with a keyworddescription
. as a percentageof the sizeof the containingelement
o with a keywordexpressing the sizerelativeto the sizeof the containingelement
lf you chooseto specifylengthsusingmeasurement units,you can useabsoluteunitsor
relativeunits.Because absoluteand relativeunitscomeup a lot with styles,it'sworthwhile
to spendsometime understanding them.Absoluteunitsdefinea font sizeusingone of five
standardunitsof measurement: mm (millimeters), cm (centimeters), in (inches), pt (points),
I and pc (picas).
millimeters,
Thepointsand picasmeasurements
and centimeters. Forcomparison,
may not be asfamiliarto you as inches,
thereare72 pointsin an inch,12 pointsin
a pica,and 6 picasin an inch.Sizevaluesfor anyof thesemeasurements can be whole
n u m b e r(s0 , 1, 2 . . . ) o r d e c i m a l(s0 . 5 ,1 . 6 , 3 . 9 . . . )F. o re x a m p l ei f, y o uw a n ty o u rt e x tt o b e
112inch in size,you can useanyof the followingstyles(notethatyou shouldnot inserta
spacebetweenthe sizevalueandthe unit abbreviation):

font-size: 0.5in
font-size:36pt
font-size: 3pc

Thesemeasurement unitsaremostusefulwhen you knowthe physicalproperties of the


outputdevice.Of coursethis may not be the casewith a Web pagethatcould be displayed
on a varietyof monitorsizesand resolutions or evensentto a printer.Thisis a fundamental
differencefrom desktoppublishing,in which you usuallyknow on whatdeviceyourcre-
ationis beingrendered.
One approachto retainingthe consistency of Web pagetext is to insteaduserelative
units,which express font sizerelativeto the sizeof a standardcharacter on the output
device(whateverthat may be).Thetwo commontypesettingstandardsare referredto as
"em" and "ex."Theem unit is equalto the width of the capitalletter"M". Theex unit is equal
to the heightof a lowercaseletter"x"(seeFigure3-16.)

Theem and ex units

In a Web pagecontainingseveralfont sizes,a browserusestwo differentmethodsto


determine the sizeof the em unit.Withinan element,the valueof the em unit is based
on the font sizeof the textwithinthatelement.Forexample,if an elementcontains12pt
text,a Iengthof 2em equals24pts.Alternately, if you want usethe em unit to definethe
font sizeitself,thenthe browserbasesthe sizeof the em unit on the font sizeusedin the
T-

Goto the<h1>tag,andaddthefollowing
style: Con
font-size:1.5em Tom {
Figure therevised
3-17shows code. backp
alsov
Settingthe font sizes browr
H]
font sizewill be 807o tasks
referr
tracki
lette
word-

wnere
sizesr
length
tracki
font sizewill be reouc
1.5x normal bodv text
To
text st
4. Saveyourchanges
andthenrefresh
about.htminyourWebbrowser,
verifying
thatthe
fontsizes
have
changed.
Compare Figure
J-18withFigure
3-'15.
To vi
Resizedlist of linksand heading
1. R
2. C
F
5. S
4. C
rl;,;l a1;1;l;lil F - ' : r l l- r l a r : un;ter F d*: -.i i,ir1! FI Er r-]r;tFr:
sp
F

You can also use the deprecated<fonD tag to set the font size for a section of text. See @
the referencewindow for details. Fa

Reference
Window
o To setthe font size,usethe style
font-si-ze z value
where rzaJueis either a unit of length (specifiedin mm, cm, in, pt, pc, em, or ex units),a
keyword (xx-smal[,x-sma[[,small, medium, [arge,x-[arge,or xx-[arge),a percentageof
the default font size,or a keyword describingthe sizerelativeto the sizeof the contain-
ing element (smalleror larger).The defauttfont size unit is the pixet (px).

Deprecated
s
r To set the font sizefor a sectionof text, usethe code:
<font size= " ya-l.ue" >text</font> Anc
where rzaLueis a number from 1 (smallest)to 7 (largest)and text is the text Vou want l i n e so
to size. line-.
ng Spacingand Indentation
feelsthatthetextfor the Welcomeheadinglookstoo crowdedon the mediumbrown
He would like you to spreadit out moreacrossthe width of the page.He
l e,t"t ae nr ,d t h e l e f t e d g e ot hf e
w o u l d l i k e t o s e e m o r e s p a c e b e t w e e n t h e f i r s"tW
background.
HTML andXHTMLsupportstylesthat allow you to performsomebasictypographic
suchaskerningand tracking.Theamountof spacebetweenpairsof lettersis
to asthekerning,while the amountof spacebetweenwordsand phrasesis called
Thestylesto controlan element'skerningand trackingare
ing: rzal ue
ing: vaTue

val,ueisthe sizeof spacebetweenindividuallettersor words.Youspecifythese


withthesameunitsthatyou usefor font sizing.As with font sizes,the defaultunit of
forkerningandtrackingis the pixel(px).Thedefaultvaluefor both kerningand
A positivevalueincreases
ingis0 pixels. the letterand word spacing.A negative value
thespacebetweenlettersand words.
Toseehowmodifyingthesevaluescan affectthe appearance of yourtext,returnto the
demo
styles page.

herningand tracking in action:


tothedemo-text-styles.htmfile in yourWebbrowser.
theResetStylesbuttonandthenchange thetextin theupper-right boxto Family
Parkandpress theTabkey.
drop-down
fromthefont-family
sans-serif
Select listbox.
boxto 52,theletter-spacing
thevalueinthefont-size valueto 6, andtheword-
to 52,
value
therevised
3-19shows text.
viewofthesample

Changingthe kerningand tracking

FunPark
Family Family Fun Park

f@ily: sals-serif; fa\E-'izet 32; fonb-fmily: sans-serif; font-eize: 32; Ietter-


spacbg: 6; dord-spacing: 32;

Anothertypographicfeaturethat you can set is leading,which is the spacebetween


oftext.Thestyleto setthe leadingfor the textwithin an elementis
Lght: Tength
[rtl wheretength is a specific length,or a percentageof the font size of the text on those
lines.lf no unit is specified,
a browserinterprets
lineheightto thefontsize.Thestandard
the numberto represent the ratioof the
ratiois 1.2:1,whichmeansthatthe lineheightis
1.2timesthe font size.lf Tomwantedhistextto be double-spaced, you couldapplythe
followingstyleto the text:

Iine-height: 2

A commontechniqueis to createmulti-linetitleswith largefontsand smallline heightsin


orderto givetitletextmoreimpact.Let'susethe demopageto seehow thisworks.

To view kerning and tracking in action:


1. CticktheResetStylesbutton,deletethetextin thetextInputbox,typeArcadium, press
Enter,typeAmusement Park,andpressTab.
2. Selectsans-serif
fromthefont-family
drop-down listboxandchoosecenterfromthetext-
aligndrop-down listbox.
5. Enter52in thefont-size
inputboxandselectpx fromthefont-size
unitdrop-down listbox,
4. Enter24intheline-height
inputboxandselect
px fromthetine-height
unitdrop-down
listbox,
Figure
J-20shows
howmodifying
thelineheightaffects
theimpact
ofthetitle.

Changingthe line height

Arcadium
AmusementPark
AmusementPark

l,t
font-fili-Ly: sans-serrf; text-a-hgn: center; font- font-fffirIy: sans-serrf; texE-al-ign: center; font-
si.zet 32Dxr saze: 32pxi l-ihe-hei-ght: 2{px;

An additionalway to controltext spacingis to setthe indentation


for the firstlineof a
text block.Thestyleis
text-indentz value

where vaTue is either a lengthexpressedin absoluteor relativeunits, or a percentageof


the width of the text block. For example, an indentationvalue of 5% indentsthe first line
by 5% of the width of the block. The indentationvalue can also be negative,extendingthe
first line to the left of the text block to createa hanging indent. Note that this techniqueis
not well supportedby many browsers.
Now you can use what you've learnedabout spacingto make the changesthat Tomhas
suggested.You'll increasethe kerning of the Welcome headingto 1em. This has the effect
of putting one blank space between each letter.You'll also set the indentationto 1em,
moving the text of the Welcome heading one spaceto the left.
Tochangethe spacing of the heading:
1.Return
toabout.htminyourtexteditor.
2.Addthefollowing
styleto theh1heading(don'tforgetto include
a semicolon
to separate
newstyles
these fromtheprevious styles).
Youmaywishto placethenewstyles ona sepa-
rate
linetomakeyourcodeeasier to read.
SeeFigure3-21.
Ietter-spacing: lem; text-indent: lem

Settingthe kerningand indentation

< h : s1 t-y l E = " c o l r ' r: w l r i t e ; h a i : k q r r - r u n d - c r - or lr : r q h ( - 15 1. l - 0 2. l - 0 i . r:


f o n t - f a m i 1i ' : n r i a l , t t e l u e t i c a , = a n s - = e r i f ; f o r r t - s i z e : l - . 5 e r n "
";'
\ielir'rne
</hr>

5.Saveyourchanges theAboutpageinyourWebbrowser.
andrefresh Verify
thatthespac-
ingoftheWelcome
heading (seeFigure
haschanged J-22).

Revisedspacingin the heading

ReferenceWindow
r Tosetthespacebetweenletters(kerning),
usethe style
'I
Fl-tFr-snec i no: y6] gg

whereyaJueisthespacebetweenindividualletters.Thedefaultis 0 pixels.
o Tosetthespacebetweenwords(tracking),usethe style
word-spacingz vaTue
whereyal ueisthespacebetweenindividualwords.Thedefaultis 0 pixets.
r Tosettheverticalspacebetweenlinesof text (leading),usethe style
line-height z Tength
wherelength is eitherthe length betweenthe lines,a percentageof the font size,or
the ratioof the line height to the font size.The default is a ratio of 1.2.
r Tosetthe indentationof the first [ine, use the style
text-indent: value
wherevalue is the length ofthe indentationexpressedeither as a length or as a per-
centage of the width of the text block.The default is 0 pixels.
whereTength is a specificlength,or a percentage of the font sizeof the text on those
the numberto represent
a browserinterprets
Iines.lf no unit is specified, the ratioof the
line heightto the font size.Thestandardratiois 1.2:1,which meansthatthe line heightis
1.2 timesthe font size.lf Tomwantedhistextto be double-spaced, you couldapplythe
followingstyleto the text:
Iine-height: 2

A commontechniqueis to createmulti-linetitleswith largefontsand smallline heightsin


orderto givetitle text more impact.Let'susethe demo pageto seehow thisworks.

To view kerning and tracking in action:


'1. ClicktheResetStylesbutton,deletethetextin thetextInputbox,typeArcadium, press
Enter,typeAmusement Parh,and pressTab.
2. Setect fromthefont-famity
sans-serif drop-down listboxandchoosecenterfromthetext-
atigndrop-downlistbox.
inputboxandselect
5. Enie,52in thefont-size px fromthefont-size
unitdrop-down listbox,
4. Enter px fromtheline-height
inputboxandselect
24intheline-height unitdrop-down
listbox.
howmodifying
J-20shows
Figure theimpact
thetineheightaffects ofthetitle.

Changingthe line height

Arcadium Arcadium
AmusementPark
AmusementPark

font-fdily: sans-serif; bext-align: center; font_ font-filIly: sans-serif; text-align: centeE; font-
sizet j?pri -Iine-height: 24F',
sizet 32pxi

for the firstlineof a


An additionalway to controltext spacingis to setthe indentation
text block.Thestvleis
text-indenLz vaTue

wherevaTueis eithera lengthexpressed in absoluteor relativeunits,or a percentage


of
the width of the textblock.Forexample,an indentation valueof 5% indentsthe firstline
bv 5ohof the width of the block.The indentation valuecan alsobe negative, extendingthe
firstlineto the leftof the text blockto createa hangingindent.Notethatthistechniqueis
not well supported by manybrowsers.
Now you can usewhat you'velearnedaboutspacingto makethe changesthatTomhas
suggested. You'llincrease the kerningof the Welcomeheadingto 1em.Thishasthe effect
of puttingone blankspacebetweeneachletter.You'llalsosetthe indentation to 1em,
movingthe textof theWelcomeheadingone spaceto the left.
SettingFontStyles,Weights,and other DecorativeFeatures
As you saw in the firsttutorial,browsersoftenapplydefaultfont stylesto particulartypes
of elements.Textmarkedwith an <address> tag,for example,usuallyappearsin italics.
Youcan specifyfont stylesyourselfusingthe style
font-style. type

wheretype is normal,italic,or oblique.Theitalicand obliquestylesaresimilarin appear-


ance,but maydiffersubtlydependingon the font in use.
Youhavealsoseenthat browsersrendercertainelementsin heavierfonts.Forexample,
mostbrowsersrenderheadingsin a boldfacedfont.Youcan controlthe font weightfor
any pageelementusingthe style
font-weightz weight

whereweight is the levelof bold formattingappliedto the text.Youexpressweightsasval-


uesrangingfrom 100to 900, in increments of 100.ln practice,however,mostbrowsers
cannotrenderninedifferentfont weights.Forpracticalpurposes, you can assume that400
represents normal(unbolded)text, 700 is bold text, and 900 represents extra-boldtext.You
can alsousethe keywords"normal"or "bold" in placeof a weightvalue,or you can
expressthe font weight relativeto the containingelement,usingthe keywords"bolder"or
"lighter".
Anotherstyleyou can useto changethe appearance of yourtext is

text-decoration: type

wheretype is none(forno decorative changes), underline,overline,line-through,


or blink.
Youcan apply severaldecorativefeaturesto the sameelement.Forexample,the style

text-decoration: underline overli-ne

placesa line underand overthe text in the element.Notethatthe text-decoration


style
cannotbe appliedto non-textual elements, suchas inlineimages.
To controlthe caseof the textwithin in an element.usethe stvle

text-transformz type
wheretype is capitalize,uppercase/lowercase,or none (to makeno changesto the text
case).Forexample,if you want to capitalizethe first letterof eachword in the element,
you could usethe style

text-transform: capitalize

To displayeach letterin lowercase/you can usethe text-transformvalue"lowercase".


Similarly,
the setting"uppercase" displayseachletterin uppercase.
Finally,you can displaytext in uppercaselettersand a smallfont usingthe style

font-variant2 type

wheretype is normal(thedefault)or smallcaps(smallcapitalletters).Smallcapsareoften


usedin legaldocuments,suchas softwareagreements, in which the capitallettersindicate
the importanceof a phraseor point, but the text is madesmallso asto not detractfrom
otherelementsin the document.
To seethe impactof thesedifferentstyles,you can usethe demo page.
lnsteadof using keywords,you can specify a length or a percentagefor the elementto
be aligned relativeto the surroundingcontent. A positivevalue moves the element up and
a negativevalue lowers the element. For example, the style

vertical-align:50E

raisesthe element by half of the line height of the surroundingcontent,while the style

vertical-align: -100t

d r o p st h e e l e m e n ta n e n t i r el i n e h e i g h tb e l o w t h e b a s e l i n eo f t h e c u r r e n tl i n e .

Combiningall TextFormattingin a SingleStyle


We'vecovereda lot of differenttext and font styles.Youcan combinemostof them intoa
usingthe form
singlestyledeclaration,
font: font-sty7e font-variant font-weight font-size/7ine-height
font-famiTy

where font-style is the font's style, font-variant is the font variant, font-weightis
the weight of the font, f ont-size is the size of the font, Tine-height is the height of
each line, and f ont-f amiTy is the font face. For example, the style

font: italic smal1-caps bold 1-6p|./24pt Arial, sans-serif

displaysthe textof the elementin an italic,bold,andArialor sans-serif font.Thefontsize


is 16pt,andthe spacebetween the lines is 24pt.fhetextwill appear in smallcapitallet
ters.Youdo not have to includeall of the properties
of the font style;
the only required
iesaresizeand font-family.A browserassumesthe defaultvaluefor any omitted
. However,you mustplaceany propertiesthatyou do includein the orderindi-
above. Forexample,the followingwould be a correctstyledeclarationto specifya
bold,monospace
16pt, font:

: bold L6pt monospace

it wouldnot be correctto switchthe order,placingthe font-familyproperty


However,
thestyleandweightproperties:

font: monospace bold 15pt

Tomfeelsthatthe sizeof the addresstext at the bottomof the pageis too large,and he
itwouldlookbefterin a normalsans-serif
feelsthat font ratherthan in italics.Makethese
nowusingthefont style.
changes

the style of the addresselement:


Returntoabout.htmin yourtexteditor.
Addthefollowingstyleto theaddress
elementat thebottomofthefile(besureto sepa-
r rateallstyle
declarations SeeFigure
witha semicolon). 3-25.
font: normal 8pt Arial, llelvetica, sans-serif

Usingthe font style

<addresstyle="text-aliqn; center; frrt : n c " l r : - l F t i : . n - i 1 1 . ' l : l , , E L i i a . s a n : - : - e i f "


mcadi um &-nbs p; &i{r14 I ; &n6sp ;
H$/1 y 2, Exir 4S1&nbsp;&#i49;&nbsp;
D e r b y ,c A 2 0 0 1 0 & n b s p ; & # 1 4 9 ; & n b s p ;
r ( e 6 o s) s s - s + : r
</address >
</bodv>
<7html>

yourchanges
I Save andthenrefresh in yourWebbrowser.
about.htm Verifythatthe
oftheaddress
appearance elementhaschanged.
SeeFigure
3-26.

Formattedaddress
'tig 'f+u
Arca&ura i easylti yru{ ltt{ge-t. }rlrnp*re our'1,;lr' a:ly rates i+ |!i cluanp'ark-s. can ci:a:rselo plrcha;e ;r gold
riJes, or *tr l:eat v';i;t:.e,
ticketfor anytwe*ry ndes^a 1:ia!u:unilicktt for t!'ilri.'*. a fi:L1-daypass t+ r:le a: roal.?timer as 'r,;u
rant,wherever y+uruant.Sp*ciai ,;S:seasotarr.C iargdgt'+"p rirt*s we ztst;Jal:,lt

Are.diiln " H'.'fv,12. f )iit 491 . Oethr. ar&,)AO1{.1, J {AtLri 55t..54:r1


ReferenceWindow

':1

,and,

ii!ffi
Usingthe SpanElement
Tomwantsto makeone morechangeto the font styleson the page.He would likethe
word 'Arcadium"in the firstparagraph to be prominentlydisplayedin bold and perhapsin
Arial or Helveticafont, settingit off from the restof the text in paragraph.
To makethis
change,you firstneeda way of markingthatsingleword within the paragraph. Youcando
thatwith the spanelement.Thesyntaxis
<span>content</ span>

wherecontent is the contentto be marked.Thespanelementis justa marker;browsers


do not formatthe contentunlessyou alsoadd a styleto the element.Forexample,to dis-
playthe word "Arcadium"in Arial or Helvetica,
you would enterthe code
<span style="font-family: Arial, Helvetica, sans-serif">
Arcadium</span>

Thespanelementis an inlineelementand mustbe placedwithin a block-level element,


suchasa paragraph or a heading.HTMLsupportsanothermarker,the div element,which
is a genericblock-level
element.We will talk aboutthe usesof the div elementin a later
tutorial.

To insert and format a span element:


1. Return in yourtexteditor.
to about.htm
2. Locatethefirstoccurrence
ofthewordArcadium intheparagraph belowtheWelcome
headingandenclosethetextinthefollowing
spanelement (seeFigure3-27).
Youmight
wantto placethecodeonitsownseparatelinefor readability.
<span style="font-weight: boldi font-fanily: Arial, Helvetica,
sans-serif " >Arcadium</span>

Creatinga spanelement

<p styl e="text-al i qn: i ustify">


Excitinq adventurei awiit vou ar
. , s p a ns i 1 - e = f o n t - , v e i q i ' t : b o l l ; f o n t - , ' a n i l y : a - i a l , r i e l u e r i i a , 5 J n ! - s e r i f ' l A r c a d i u m i , s F : n ' ,
vour aff-ordable familv fun center. the oark is located 5 miles northwest of
qerby c l o s e t o m a n yo f c e o r q i a ' s s c e n i c w o n d e r s . l r c a d i u m o f f e r s o v e r 5 0 r i d e s ,
i n c l - u d i n q s o r n eo f t h i s t a t e ' s ' m o s t e x c i t i n q r o l l e n . o a s t e r s a n d w a t e r r i d e s .
I h q l ? ' s i l s o p l e n t y o f f u n . f o r t h e y o u n g e r - k i d . s ,i n c l u d i n g t w o s e p a r a t e
K t a o t e o o o t s a n d S n e c t a I r ' t o e sT o r t n e k r d s . < , / b >

5. Saveyourchanges. Youmayclosethetexteditorifyouplanontakinga breakbefore


goingonto SessionJ.2.
4. Reloadabout.htm in yourWebbrowser.
Figure3-28shows theformatappliedto theword
Arcadiuminthefirstpafagraph,
and you will probablyuse
tiltl retrieve.Eachfile formathasitsadvantages and disadvantages,
a combinationof both formatsin your Web pagedesigns.First,let'slook at the advantages
and disadvantages of usingGIF imagefiles.

I Workingwith GIF lmages


I GIF (GraphicsInterchange Format),the mostcommonlyusedimageformaton theWeb,
is compatiblewith virtuallyall browsers. GIFfilesare limitedto displaying256 colors,so
Jl
rtl
they are mostoftenusedfor graphicsrequiringfewercolors,suchas clip art images,line
art, logos,and icons.lmagesthat requiremorecolor depth,suchas photographs, can
appear grainy when saved as CIF There
files. are actually two CIF file formats:GIFBT and
The
GlFBga. GlFBga format supports more features such as interlacing, transparent
colors,
andanimation.
lnterlacingrefersto the way that graphicssoftwaresavesa CIF file. In a noninterlaced
GlF, which is the mostcommonformat,the imageis savedone line at a time,starting
from the top of the graphicand movingdownward.Figure3-29 showsthe progress of a
noninterlaced it
GIFas opens in a Web browser.lf a graphic is large, it mighttakea long
time for the entireimageto appear, which can frustratevisitors to your Web page.

Noninterlaced
GIF

tt,

An interlacedGlF, by contrast,is savedand retrievedin stages.Forexample,everyfifth


line of the imagemightappearfirst,followedby everysixthline,and so forththroughthe
remainingrows.As Figure3-30 shows,an interlacedimagestartsout asa blurryrepresen-
thengraduallycomesintofocus.By contrast,a noninter-
tationof itsfinal appearance,
lacedimageis alwaysa sharpimageas it'sbeingretrieved,but it is incompleteuntil it is
fully loaded.
InterlacedGIF

AninterlacedGIFis an effectiveformatfor a largegraphicthat you want usersto be


toseeasit loads.Userswith slowerconnections get an immediateideaof whatthe
looks
likeandcandecidewhetherto wait for it to come into focus.On the down
interlacing
increasesthe size of a CIF file by anywhere from 3 to 20 kilobytes,
ingon the image.
GIFimage filescanbe large.One way to reducethe sizeof a CIF is to reducethe num-
ofcolors in itscolorpalette.Forexample,if an imagecontainsonly32 differentcol-
youcanusean imageeditingprogramto reducethe paletteto those32 colors,
Itingin a smallerimagefile that loadsfaster.

ngwithTransparent
Colors
feature
of theClF89aformatis the abilityto usetransparent
colors.A transparent
i s a c o l o r t h aits n o t d i s p l a y e dw h e n t h e i m a g e i s v i e w e d i n a n a p p l i c a t i o n .l n p l a c e
color,a browserdisplayswhateveris on the pagebackgrouno.
thetransparent
Theprocess
bywhichyou createa transparent
color dependson the graphicssoftware
areusing.
Manyapplicationsincludethe optionto designate a transparent
color
savingan image,while other packagesinclude a transparentcolor tool, which you
to selectthe color that you want to treat as transparent.
thepast,
Webpagedesigners usedtransparent ClFsas layouttoolsto helpthem
elementson aWebpage.Toaccomplish this,a designerwould createa CIFone
in size,with the colorof the pixel specifiedastransparent.
square Thistypeof image
sometimesreferredto asa spacer.A Web designercould then sizethe spacerin
toposition
objectsin specificlocationson the page.Because the spacerwastrans-
wouldseeonly the positionedobject.With the adventof styles,thereis little
users
forspacers
anymore, but you may stilI seethem in the codefor olderpages.

Animated
ClFs
arealsocommonlyusedto createanimatedimages.An animatedGIF is composed
images
thataredisplayedone afterthe other.Somefilesplaythe framesin rapid
c r e a t i ntgh e i l l u s i o no f m o t i o n , w h i l e o t h e r a n i m a t e dC l F s s i m p l y c y c l e s l o w l y
throughmultipleimagesor messages. Youcaneasilyfind animated GlFson theWeb in
onlinecollections. Youcan alsocreateyour own by installinganimatedCIF software.
MostanimatedCIF softwareallowsyou to controlthe rateat which an animationplays
(asmeasured by framesper second)and to determinethe numberof timesthe animation
repeatsbeforestopping(or setit to repeatwithoutstopping). Youcan alsocombineindi-
vidualGIFfilesintoa singleanimated file and createspecialtransitionsbetweenimages.
AnimatedClFsarea mixedblessing. Because an animated CIFfile is typicallylarger
thana staticGIF imagefile, usinganimatedGlFscan greatlyincrease the sizeof a Web
page.Youshouldalsobe carefulnot to overwhelmuserswith animatedimages. Animated
ClFscan quicklyirritateusersoncethe noveltywearsoff, especiallybecausethereis no
way for usersto turn themoff! LikeotherGIFfiles,animatedGlFsare limitedto 256 col-
ors.Thismakesthem idealfor smalliconsand line art,but not for photographic images.
Recallthatone of the pagesin theArcadiumWeb siteis a splashscreen.Tomwantsto
includesomeinteresting visualeffectson this pagein orderto draw usersintothe site.
Youdecideto investigate whetherthiswould be a good placefor an animatedGIF.Oneof
the graphic designers at Arcadiumhascreatedan animatedGIFof the companylogo.
You'lltry addingthatto the splashscreen.

To insert the animated logo in the Web page:


1. Useyourtexteditor
to opentheindextxt.htm
filefromthetutorial.0S/tutorial
fo]derof
yourDataFiles.
Enter yourname andfhedateinthecomments atthetopofthefileand
it asindex.htm.
save
thetext"ARCADIUM"
2. Replace withthefollowing
tag,asshown
in Figure
3-51.
(img src="1ogoanim.gif" aIt="ARCADIUI.{" />

Insertingthe animatedlogo

<body style="font-famiIy: Arial, Helvetica, sans-serif">


<p stvl e-="text-al i qn: cinter >
. i n r q . s r ; = ' l : g l r r i m . ! l i f " . i l r = ' ' a F a n D T r - r l/f:"
<or ,/>
<span style="colon: ro.1' fnnr-<i>o' lahr' +.ht-weight: bo1d">
nfiordable Fanily Fun
</s pan>
<br /><br />
<a hr ef= " about . htfii " >Ent er nr cadi un</a>
</p>
<,/bodv>
<,/html >

5. Saveyourchangesto thefile.
4. Openindex.htmin yourWebbrowser.
Verifythatthelogodisplays
ananimated
setof
racing
downthetrack.SeeFigureJ-32

Animatedlogo
ingwith JPEGlmages
othermainimagefile formatis the JPECformat.f PEGstandsfor foint Photographic
Group.JPEGs differfrom ClFsin severalways.In the JPEGformatyou can create
thatusethefull 16.7millioncolorsavailablein the color palette.Because
of this,
filesaremostoften usedfor photographsand imagesthat covera wide spectrum

addition,the imagecompression algorithmusedby JPEGfilesyieldsimagefilesthat


ly (thoughnot always)smallerthantheirCIF counterparts. In somesituations,
theGIFformatcreatesa smallerand better-looking image-for example,when an
contains largesectionscoveredwith a singlecolor.As a generalrule,you should
for photosand GlFsfor illustrations
that involveonly a few colors.
cancontrolthe sizeof a JPECby controllingthe degreeof imagecompression
to thefile.Increasing
the compression reducesthe file size,thoughoftenat the
of imagequality.Figure3-33 showsthe effectof compression on a JPEGfile.As
cansee/theincreased compression cutsthe file sizeto a fractionof the original,but
resultingimageis morepoorlydefinedthanthe imagewith low compression.

Theeffectsof compressionon f PEGquality and file size

moderatecompression(10 KB) heavycompression(4 KB)

testing differentcompressionlevelswith imageeditingsoftware,you can reducethe


aJPEC filewhilemaintainingan attractiveimage.Notethat a smallerfile sizedoes
lways mean thata Web pagewill load faster.Becausea browserhasto decompressa
image when it, openinga heavilycompressed
it retrieves imagecan actuallytake
timethan retrieving and displaying a lesscompressed file.
do notsupportanimationor transparent colors.However,a formatcalled
f PEG does createan effect
similar to interlacing,in which the JPECimage
infroma low resolution to a high resolution.Like interlacedClFs,progressiveJPEC
filesare larger than nonprogressive JPECs.

with PNGlmages
formatthat is startingto gain wide acceptanceis the PortableNetwork
graphic
or PNGformat.PNC filesincludemostof the samefeaturesas ClFs(suchas
and transparency)
interlacing, but alsoprovidethe file compression available
like
. Inaddition, the JPEC format, PNC the
supports full 16.7 million colors
colorpalette.
You can also designate severaltransparentcolors in a PNC file,
thanthesinglecolorthat GlFssupport.Theonly problemwith the PNC formatis
The about photo

Ezcinrlgadventurrsalrraity+r"rat Arcadium, T':ur afthrdahleiam:iy fi-rrcenier.Thr park


islocated5 milesnortlnvestof heruy - cl+se tn rrrar:yof Ger.rgra's:c;rric r','+lders.3-r'cadrunr +fiirs over 50 rides,r,qcb.rdul.g
gome of fie rtate'JmDsir:rrrffrq roller l*asterr ,lrid .,E;rterddes. T'h*re'sals,rplrrrry'cf fiirr for d:e yrunger Li<ls,mclu'fuigt','"'l
separatekjdrireporls rfid :J:ecialriCssf,>rtir kjdr.

Aligningan lmage
You showTom the progressyou'vemadeon the Web page.Althoughhe'spleasedwith
theimageof the kids,he doesn'tlike how the imageis positionedon the page.The
layoutincludesa largeblankspacebetweenthe Welcomeheadingand the first
current
paragraph,
Tomwantsyou to wrap the paragraph text aroundthe image.

an Element
Floating
Onewayto achievethis is with the float style.Thesyntaxof the floatstyleis
: position

position is none (the default),left, or right.As shown in Figure3-37, when a


encountersthe float style, it placesthe element on the specifiedmargin and then
thesubsequent content around the element.
The clear stvle

W ffi
Wf;-rch'l
r
m
@r
ffi

lastelementonly displays
when the right marginis clear

whatyou know aboutthe float style,placethe photo on the About pageat the
Using
andusethe clearstyleto ensurethatthe horizontalline at the bottomof the
margin
doesnotmoveup and wrap aroundthe image.

at the photo:
totheabout.htm filein yourtexteditor.
attribute
rt thefollowing intothe<img/> tagfortheaboutphoto:
"float: right"
styleintothe<hr/> tag(besureto separate
thefollowing thisstylefromtheother
witha semicolon).
: right
J-39shows
therevised
code.
lnsertingthe float and clear styles

<o stvl e="text-a l i on: i ustifv"> V


<lmq irc="about. jpd" a'lt="" ityle="flaat: riqlht" ,/>
exc{tino adventuihi awair vou ar
< s p a n s i y l e = " f o n t - w e i q h t : 6 o 1d ; f o n t - f a m i l y : l r i ' la d elveti ca, sans-serif">Arcadi um</span>,
o c1 i,t e H
vou r hhee p a r fkt i s ' l o c a t e d
i . r r a f f 6brrddaabbl lee f a m iilliv f u n c e n iteerr.. T 5 n r i lleeis n o r tthhw
weesst t o f
6erby - close to many-of ceorqia's scenic wonders. lrcadiun offers over 50 rides,
incl-udinq soma of th-e state's-nost excitinq roller coasters and water rides.
There's ilso plenty of fun for the younqer-kids, including two separate
k i d d i e p o o l s a n d s - p e c ia l r i d e s f o r t h e [ i d s . < , / p ;

<p>nrcadium is open seven days a week:</p>


<ul >
<li>lpril l- uo to t,temorial Dav weekend: 10am to 5pm<,/li>
<li>ttbmorial bav weekend thro-urrh Labor Dav: gam tb tipm<,/li>
<li>The day afti:r Labor Day thFouqh octob-er 31: 1oafl to 5prn<,/li>
< l i > t ' t o v e r n b - e1r t h r o u g h t t r a r - c h 3 1 : i l o s e d < , / l i >
</ut>

<n stvle="text-alion: iustifv">Arcadium is easv on vour budqet. compare our'low


dailv-rates to thp-biq-chain-narks. y o u c a n c h - o o s ei o n u r c h i s e a o o l d t i c k e t for
a n y i w e n t y- p ar isdse s , a p T a t i n u m t i c k e t for thirty rides, br for best-value, a
fu1,1-Oay to ridb as many.times as you wa-nt, wherever you want. special off-season
ano rafge qroup fares aTe avar ratrre.</p>

<hr style="colon: rgh(l-53,102,102); background-color: rgb(153,102,102): r:lear: r'jqht" />

4. Saveyourchangesandreopen inyourWebbrowser.
about.htm Figure
3-40shows
the
revised
layout
ofthepage.

Floatingthe imageelement

'Ilir
Exciltqg ad"reuhrri aurill 'ri)L!at ArCadiUm" 'gour idti;rdal:lef'aradvfir: ,:*nter. parh
rs hiatriJ 5 mi!-'r n+rtll',reit oi lrri::y - rlos* io rn*i"1 of ilt.,'rg]a's :cerrir ',1'orrdrrs.
-d"rcadirmil$eri .rr"erfiil i;,tlrs, tuh.i'durgso:ne *ftl:r*:tate'r rrr+ste::cilingrc,llercrartrr:
-*lrJ 'rirtrr n,,J*: Therr'r ail,; pi*ng +i'fi.ur ii,r th* ycrnger k-:,J:,n:*lud:rrgil".J srparnte
itid,Lrel.uri: ar:ri:perr;,1t'i,1tsfbr rh* L:rtJe

l . r r , . 1 1 r r , : c ^ r ' r . . . i r , - r r t . 1 , , . . , 1. . t - , . - e k

' "tipr:ilI r-rpiv hftn,:,ri;r1I)a:, vreriren,i. t1r,*r 1'1liprr


* 1,,,[ertr.rnrJ
]-)avr,i*ekrnd t]r,:'rrEtLLab,rr l)ty: !ara t,: 1lpm
* fl:e ii.ly :,SerLal:r'r f ,a',r",h C,ci+r:er'3 I : 1t-;a:n;+ ilrc
"rugh
r ll+'retr't:r 1 tlr..rughI'far,h li1. r:l+rerl

A-rarlirnn rs e;rsl' rn 1rr,ix1,r.rdg*tll+tLrp;rreriu' l':vr dail.,'iates tn tlt i;ig rharr p*rks.


lj(-,ufi;il'r{i!nr)rr t,;' pr"x-rilas*a g+kl hiir.etl-,rr;nt irverr!1t
nd*s, a i,,laLisir"rm
tlrl:et for t}uty
ridrs. +i tii be:t viiut, a i"rl1-r'l;,r'pa.-s t'r ndi ai nL.r'V hrftpJ as you !"i.rrt. rs'herever lrnu l'naJ"rt.lp*cral ofi'-sea:,:lr andiarge
ff{rur ralc! fte svud;rhin

Arcrr'jiirm . H!'! 12. E:1ii481 . Dnfb,/, +A 2[lit . I (3n0]! ii5..5431

Usingthe AlignAttribute
Forsomeolder browsers,you may needto usethe alignattribute,which is now deprecated,
to fulfillsomeof the sameneedsasthe floatstyle.Thesyntaxof the alignattributeis
<img align="position" />
w h e r e p o s r t r o ni n d i c a t e sh o w y o u w a n t t h e i m a g ea l i g n e dw i t h t h e s u r r o u n d i n gc o n t e n t .
l fy o uw a n tt h e i m a g ep l a c e do n t h e l e f t o r r i g h tm a r g i n ,u s ea l i g n v a l u e so f " l e f I " o r " r i g h t " .
F i g u r3e- 4 1s h o w st h e o t h e rv a l u e so f t h e a l i g n a t t r i b u t e .

Valuesof the alignattribute

Aligns the bottom of the object with the absolute bottom of the surrounding text. The
absolute bottom is equal to the baseline of the text minus the height of the largest
descender in the text.

absmiddle Aligns the middle of the object with the middle of the surrounding text. The absolute
middle is the midpoint between the absolute bottom and text top of the surrounding text.

baseline Aligns the bottom of the object with the baseline of the surrounding text.

bottom Aligns the bottom of the object with the bottom of the surrounding text. The bottom is

!l: P=-llr-:'Iy: t::9:fgl-"j


9 v31-!9 hl "t 19'"-::,':1=l-'l: !'11,
Aligns the object to the left of the surrounding text. Al[ preceding and subsequent text
flows to the right of the object.
middle Aligns the middle of the object with the surrounding text.

right Aligns the object to the right of the surrounding text. All subsequent text ftows to the left
of the obiect.

texttop Aligns the top of the object with the absolute top of the surrounding text. The absolute
top is the baseline plus the height of the largest ascender in the text.

Aligns the object to the right of the surrounding text. Al[ subsequent text flows to the left
of the obiect.

N o t et h a ty o u c a n d u p l i c a t et h e a l i g n v a l u e sw i t h s t y l e sY . o u c a n r e c r e a t et h e e f f e c t so f
t h el e f ta n dr i g h tv a l u e su s i n gt h e f l o a t s t y l e .Y o u c a n d u p l i c a t et h e r e s to f t h e a l i g n v a l u e s
u s i ntgh ev e r t i c a l - a l i gsnt y l ed i s c u s s e di n t h e p r e v i o u ss e s s i o n .
T h e r ies n o g , e n e r aalt t r i b u t et o p r e v e n ta n e l e m e n tf r o m b e i n g d i s p l a y e du n t i l a m a r g i n
i s c l e alrf.y o u n e e dt o p e r f o r mt h i s t a s kf o r o l d e r b r o w s e r sy, o u c a n p l a c e t h e t a g
< b r c l e a r = " p o s i t i o n " / > b e f o r et h e e l e m e n ty o u w a n t c l e a r e d ,w h e r ep o s i t i o n i s
e i t h e" rl e f t "o t " r i g h t " ," a l l " , o r " n o n e " . T h i s t a g c r e a t e sa l i n e b r e a ko n l y a f t e rt h e s p e c i -
f i e dm a r g i n i s c l e a r .N o t e t h a t l i k e t h e a l i g n a t t r i b u t e t, h i s a t t r i b u t eh a s b e e n d e p r e c a t e d .

ReferenceWindow
o Tofloatanelement
on the left or right margin,usethe style
float: position
whereposit:onis none (the default),left, or right,
r Todisplay an elementin the first availablespacewhere the specifiedmargin is clear of
elements,
floating use the style
clear: position

Deprecated
o Toalignaninlineimagewith the left or right pagemargin,add the followingattribute
tothe<img/> tag:
a l i g n = " p o s : . t i o n"
where positron is either left or right.
r Todisplay an elementin the first availablespacewhere the specifiedmargin is clear of
otherelements, enterthe fo[[owingtag before the element:
<br clear="position', />
where position is left, right, atl, or none.
SettingMargins
Wrappingthe contentaroundthe imagehassolvedthe problemof the largewhitespace
in the middle of the About page.However,Tomfeelsthat the text crowdsthe phototoo
much,and would Iikeyou to slightlyincreasethe marginbetweenthe photoand thetext.
Fourstylescontrolthe sizeof an element's
top, right,bottom,and left margins:
margin-topz Tength
margin-righLz Tength
margin-bottom: lengrth
margin-leftz Tength

whereTength is one of the unitsof lengthdiscussed in the previoussession


or a percent-
ageof the width of the containingelement.Youcan alsousethe keyword"auto",which
enablesthe browserto determinethe marginsize.As with font sizes,the defaultunit isthe
pixel.To createa 2-pixelmarginto the leftand rightof an element,and a 1-pixelmargin
aboveand below you would usethe style
margin-top: 1; margin-right: 2; margin-bottom: L; margin-left: 2

A marginvaluecan alsobe negative. Web pagedesigners can usenegativemarginsto


createinterestingoverlayeffectsby forcingthe browserto renderone elementon top of
another.Notethat somebrowsersdo not supportnegativemarginsand usingthem may
leadto unpredictableresults.
Thefour marginstylescan be combinedinto a singlestyleusingthe format
margin: top right bottom Teft

where top, right, bottom, and left are the sizesof the top, right, bottom, and left margins.
(lf you havetrouble rememberingthis order,just think of moving clockwisearound the element
startingwith the top margin.)lf you include only three values in the margin style,they are
applied to the top, righg and boftom margins.lf you specifyonly two values,a browserapplies
the first value to both the top and bottom margins,and the secondvalue to both the left and
rightmargins.lf you specifyonly a singlevalue,a browserappliesit to all four margins.
Tom suggeststhat you set the size of the left margin to 1 5 pixels and the size of the
bottom margin to 5 pixels.The top and right margins can be set to O pixels.

To set the image margins:


1. Return
totheabout.htmfiteinyourtexteditor.
styletothe<img/> tagfortheabout
2. Addthefollowing (see
photo Figure
J-42):
margin:00515
Besureto separate
thisstylefromtheotherstyles
witha semicolon.

Settingthe marginsize
<o stvle="text-aliun: iustifv">
<imgirc="about.jpd" alt="" ity'le="float: right; margirr: 0 0 5 l-5",/>
Excitino adventuibi awair vou at
<spansfyle="font-weiqht: 6o1d; font-family: nria1, Helvetica, sans-serif">Arcadiunr</span>,
voirr aff-ordable familrT fun cenier. The Eark is locited 5 milei northwest of
berby - close to many-ofGeorqia's scenic wonders,lrcadium offers over 50 rides,
inclfidinq sone of th-e state's-nrost excitinq roller coasters and water rides.
There's 51so plenty of fun for the younqer-kids, including two separate
kiddie pools and s-pecialrides for ttre [ius.<,rpi

Saveyourchanges
to thefileandreopen in yourWebbrowser.
about.htm Verifythatthere
isnowmorespace
separating thephotofromthesurrounding
content.
to set
styles margins for your entire Web page. Tom has looked at
. o u c a n u s et h e m a r g i n
Y o uc a na l s os e t m a r g i n sf o r e l e m e n t so t h e r t h a n i n l i n e i m a g e sY
the splashscreenand
rlt
suggests that the animated logo might look better if it was further down the page.You can
accomplish t h i s b y i n c r e a s i n t
g h e p a g e ' s
t o p m a r g i n .

Tosetthe pagemargin:
fileinyourtexteditor.
1.Gototheindex.htm
tagatthetopofthefile,insertthefollowing
the<body>
2.Within 3-45:
In Figure
style,asshown
margin-top: 100

a semicolon,
toinsert
Besure thisstylefromtheotherstyledeclarations.
separating

Settingthe top pagemarginfor index.htm

<bltlvsrvle=,,font_faflily:Ar.iJl,HelVEtira,sans_serif'''j''>
. a' t r v l o = " t e r t a l i q n : - ; r n t' e r ' .
,.iirg..rc="logoariirn.;1if a l r , " a R c A D I tt , t ' . / :
<frr ./ >
<spai style="color: red: forrt size: lBFt; fDnt uPiqht: bold">
ffirrdable ramily run
<,/tFani
:br -/><br r/:,- I
ri fief = abrut. htttt">EntEr trcaliuill-i,/'e:'
,/,p,
<,/trtrtr./:
< , / n t ml >

yourchanges
5,Save index.htm
to thefileandreopen Verify
inyourWebbrowser. thatthe
have
contents beenshifteddownthepage.

Forolderbrowsersyou can use the deprecatedattributesvspaceand hspace.The vspace


setsthe verticalspaceabove and below the inline image.The hspaceattributesets
attribute
thehorizontalspaceto the left and right of the image.Thereare no presentationalattributes
thatallowyouto specifythe size of individual margins.

Window
Reference
r Tosetthesizeof the marginsaroundan element,usethe styles
margin-top: length
margin-rightz Tength
margin-bottom: Tength
nargin-left z Tength
wherelengthisa unitof length,a percentage element,
of the width of the containing
orthekeyword"auto"(thedefault),whichenables the browserto setthe marginsize.
o Tocombinea[[marginstylesin a singlestyle,use
margin: top right bottom Teft
top,right, battomtandJeft arethe marginsof the top, right,bottom,and left
where
youinclude
edges.lf onlythreevalues,the marginsare appliedto the top, right,and
boitom.Iiyouspecify onlytwo values,the firstvalueis apptiedto the top and bottom
' valueto the right and left edges.If youspecifyonlyonevalue,it
anJthesecond
edges,
to allfouredges.
isapplied

Tosetthemarginaroundan inlineimage,add the followingattributesto the <img /> tag:


v s p a c e = " L e n g"t hh s p a c e = "T e n g t h "
where thevspaceattributesetsthe margin size above and below the image, and the
hspace attributesetsthe margin sizeto the teft and right of the image. All Tenqth
values aremeasured in pixels.
Setting the lmage Size
By default,browsersdisplayan imageat its savedsize.Youcan specifya differentsizeby
to the <img/> tag:
addingthe followingattributes

width="value" height="va7ue"

wherethe width and heightvaluesrepresent the dimensions of the imagein pixels.


Changingan image'sdimensions within the browser does not affectthe file size.lf you
want to decrease the sizeof an image, you should do so using an imageeditingapplica-
tion so thatthe image'sfile size is reduced in addition to its dimensions. Because of the
way that browsers work with inline images, it is a good idea to specify
the height and
width of an imageevenif you'renot tryingto changeitsdimensions. When a browser
encounters an inlineimage,it calculates the image size and then usesthis information to
lay out the page. lf you includethe dimensions of the image, the browser does not have to
performthat calculation,reducingthe time requiredto renderthe page.Youcan obtain
the heightandwidthof an imageas measured in pixelsusingan imageeditingapplica-
tion suchasAdobePhotoshop, or with Windows Explorer.
Thelogoimageslogo.gifand logoanim.gif are 5'17pixelswide by 119 pixelshigh,
and the photo about.jpgis 210 pixels wide by 280 pixelshigh.Add thisinformation to
eachof the <img/> tagsin the about.htmand index.htm files.

To set the image dimensions:


filein yourtexteditor.
to theabout.htm
1. Return
the<img/> tagforthetogo.gif
2. Within graphic,insert width="517"
theattributes

the<img/> tagfortheabout.jpg
5. Within graphic,
insert width="210"
theattributes
Youmaywantto place
height="280". theseattributes
ona separate your
lineto make
Figure
codemorereadable. 5-44shows
therevisedcode.

Settingthe imagesize
< b o d v s t v l e = " c o lo r : r q b ( 1 5 3 .l - 0 2 . 1 0 2 1 : b a c k q r o u n d - c ool r : w h i t e " >
<p siyle-="text-align:-cdntei; fbnt-iirmily:-Arial, Helvetica, sans-serif;
T0nr-51 ze: u. aefl >
< i m g s r c = " 1 o g o . g i f " a 1 t = " n R c A D r u t t " l d id t h = " 5 1 - r " h E i g l r t = " 1 1 E " / >
<nr / >
<a href="about. htm">About lrcadi um</a> &nbsp; &nbsp; &nbsp;
< a h r E f = " m a F .h t m " > P a r k M a p < / a > & n b s p ; & n b s p ; & n b s p ;
< a h r e f = " w a t e r . h t m " > t ia t e r t i d e s < / a > & n b s p ; & n b s p ; & n b s p ;
< a h r e f = " k a r t s . h t m " > G o t < a r t s < / a > & n b s p ;& n h s p ;& n b s p ;
<a href="ri des. htn">Rol I er coasters<./a:
<./p>

< h 1 s t v- l e = " c o l o r : w h i t e ; b a c k q r o u n d - c o l o r : r q b ( l - 5 1 , 1 - 0 2 , 1 0 2 ) ;
font-fafli ly: nri a'lI nelveti ca, sans-serif; 1 - .5 e m ;
I etter-spati ng: l-eril; text-i ndent : 1em">
wel come
<./nL>

<n stvle="text-al ic1n: i ustifv">


< i m-q i r c = " a b o r t . i p- d " a1t="" ityle="fIoat: right; margin: 0 o 5 1-5"
u i d t l - , =" 2 1 0 " h E i q t r t = " : t o " 7 >

4. Saveyourchangesto thefileandreopen about.htm inyourWebbrowser.Thepageshould


appearasbefore.
5. Return
to theindex.htm fiteinyourtexteditor.
the<img/> forthetogoanim.gif
6. Within graphic,insert width="S17"
theattributes
height="119".
7. Saveyourchanges andreopen index.htminyourWebbrowser. youshould
Onceagain,
notseea changeinthepagelayout.

Vous aimerez peut-être aussi