|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
更方便搜索引擎的搜索。用只包含结构化内容的HTML代替嵌套的标签,搜索引擎将更有效地搜索到你的内容,并可能给你一个较高的评价(ranking)。
在之前我们的事情中,以传统切图头脑举行操纵,考究精密,图片规格越小越好,分量越小越好,实在规格巨细无所谓,盘算机一致都按Byte盘算。
客户端每显现一张图片城市向服务器发送哀求,以是,图片越多哀求次数越多,形成提早的大概性也就越年夜。由于一张图片的传输工夫,一般远小于哀求守候的工夫。
典范如文本编纂器,小图标出格多,翻开时一张张跑出来,给用户的感到很欠好。假如能用一张图办理,则不会有这个成绩,好比百度空间、163博客、Gmail都是这么做的,poluoluo.com也倡始如许的操纵办法。
CSSSprites:ImageSlicing’sKissofDeath
Backwhenvideogameswerestillfun(we’retalkingaboutthe8-bitglorydayshere),graphicswereamuchsimplermatterbynecessity.Bitmapped2-dimensionalcharacterdataandbackgroundscenerywasindividuallydrawn,muchliketoday’sresurgentpixelart.Hundredsandlaterthousandsofsmallgraphicscalledspriteswerethebuildingblocksforallthingsvisualinagame.
Asgamecomplexityincreased,techniquesdevelopedtomanagethemultitudeofspriteswhilekeepinggameplayflowing.Onevariationsawspritesbeingpluggedintoamastergrid,thenlaterpulledoutasneededbycodethatmappedpositionsofeachindividualgraphic,andselectivelypaintedthemonthescreen.
Andwhatdoesthishavetodowiththeweb?
Everythingoldisnewagain,andthoughtheriseof3Dgameshasmadespritemapsobsolete,theconcurrentriseofmobiledeviceswith2Dgamingcapabilitieshavebroughtthembackintovogue.Andnow,withabitofmathandalotofCSS,we’regoingtotakethebasicconceptandapplyittotheworldofwebdesign.
Specifically,we’regoingtoreplaceold-schoolimageslicinganddicing(andthenecessaryJavaScript)withaCSSsolution.AndbecauseofthewayCSSworks,we’regoingtotakeitfurther:bybuildingagridofimagesanddevisingawaytogeteachindividualcelloutofthegrid,wecanstoreallbuttons/navigationitems/whateverwewishinasinglemasterimagefile,alongwiththeassociated“before”and“after”linkstates.
HowdoCSSSpriteswork?
Asitturnsout,thebasictoolstodothisarebuiltintoCSS,givenabitofcreativethinking.
Let’sstartwiththemasterimageitself.Dividingarectangleintofouritems,you’llobserveinthismasterimagethatourintended“before"linkimagesareonthetoprow,with“after":hoverstatesimmediatelybelow.There’snocleardivisionbetweenthefourlinksatthemoment,soimaginethateachpieceoftextisalinkfornow.(Forthesakeofsimplicity,we’llcontinuetorefertolinkimagesas“before”imagesandthe:hoverstateas“after”fortherestofthisarticle.It’spossibletoextendthismethodto:active,:focus,and:visitedlinksstatesaswell,butwewon’tgointothathere.)
ThosefamiliarwithPetrStanicek’s(Pixy)FastRolloversmayalreadyseewherewe’regoingwiththis.ThisarticleowesadebtofgratitudetoPixy’sexampleforthebasicfunctionwe’llberelyingon.Butlet’snotgetaheadofourselves.
OntotheHTML.EverygoodCSStrickstrivestoaddalayerofvisualsontopofacleanblockofcode,andthistechniqueisnoexception:- <ulid="skyline"><liid="panel1b"><ahref="#1"></a></li><liid="panel2b"><ahref="#2"></a></li><liid="panel3b"><ahref="#3"></a></li><liid="panel4b"><ahref="#4"></a></li></ul>
复制代码 Thiscodewillserveasabaseforourexample.Light-weight,simplemarkupthatdegradeswellinolderandCSS-disabledbrowsersisalltherage,andit’satrendthat’sgoodfortheindustry.It’sagreatidealtoshootfor.(We’llignoreanytextinsidethelinksforthetimebeing.Applyyourfavoriteimagereplacementtechniquelatertohidethetextyou’llendupadding.)
ApplyingtheCSS
Withthosebasicbuildingblocks,it’stimetobuildtheCSS.Aquicknotebeforewestart—becauseofanIEglitch,we’llbetilingtheafterimageontopofthebeforeimagewhenweneedit,insteadofreplacingonewiththeother.Theresultmakesnorealvisualdifferenceifwelinethemupprecisely,butthismethodavoidswhatotherwisewouldbeanobvious“flicker”effectthatwedon’twant.- #skyline{width:400px;height:200px;background:url(test-3.jpg);margin:10pxauto;padding:0;position:relative;}#skylineli{margin:0;padding:0;list-style:none;position:absolute;top:0;}#skylineli,#skylinea{height:200px;display:block;}
复制代码 Counter-intuitively,we’renotassigningthebeforeimagetothelinksatall,it’sappliedtothe<ul>instead.You’llseewhyinamoment.
TherestoftheCSSintheaboveexamplesetsthingslikethedimensionsofthe#skylineblockandthelistitems,startingpositionsforthelistitems,anditturnsofftheunwantedlistbullets.
We’llbeleavingthelinksthemselvesasempty,transparentblocks(thoughwithspecificdimensions)totriggerthelinkactivity,andpositionthemusingthecontaining<li>s.Ifweweretopositionthelinksthemselvesandeffectivelyignorethe<li>s,we’dstartseeingerrorsinolderbrowsers,solet’savoidthis.
Positioningthelinks
The<li>sareabsolutelypositioned,sowhyaren’ttheyatthetopofthebrowserwindow?Aquirkybutusefulpropertyofpositionedelementsisthatalldescendentelementscontainedwithinthembasetheirabsolutepositionnotoffthecornersofthebrowserwindow,butoffthecornersofthenearestpositionedancestorelement.Theupshotofthisisthatsinceweappliedposition:relative;to#skyline,we’reabletoabsolutelypositionthe<li>sfromthetopleftcornerof#skylineitself.- #panel1b{left:0;width:95px;}#panel2b{left:96px;width:75px;}#panel3b{left:172px;width:110px;}#panel4b{left:283px;width:117px;}
复制代码 So#panel1isn’thorizontallypositionedatall,#panel2bispositioned96pxtotheleftof#skyline’sleftedge,andsoon.Weassignedthelinksadisplay:block;valueandthesameheightasthe<li>sinthepastlisting,sothey’llendupfillingtheircontaining<li>s,whichisexactlywhatwewant.
Atthispointwehaveabasicimagemapwithlinks,butno:hoverstates.Seetheexample.It’sprobablyeasiertoseewhat’shappeningwithbordersturnedon.
Hovers
InthepastwewouldhaveappliedsomeJavaScripttoswapinanewimagefortheafterstate.Insteadourafterstatesareinoneimage,soallweneedisawaytoselectivelypulleachstateoutfortheappropriatelink.
Ifweapplythemasterimagetothe:hoverstatewithoutadditionalvalues,wemakeonlythetopleftcornervisible—notwhatwewant,thoughclippedbythelinkarea,whichiswhatwewant.Weneedtomovethepositionoftheimagesomehow.
We’redealingwithknownpixelvalues;alittlebitofmathshouldenableustooffsetthatbackgroundimageenoughbothverticallyandhorizontallysothatonlythepiececontainingtheafterstateshows.
That’sexactlywhatwe’lldo:- #panel1ba:hover{background:transparenturl(test-3.jpg)0-200pxno-repeat;}#panel2ba:hover{background:transparenturl(test-3.jpg)-96px-200pxno-repeat;}#panel3ba:hover{background:transparenturl(test-3.jpg)-172px-200pxno-repeat;}#panel4ba:hover{background:transparenturl(test-3.jpg)-283px-200pxno-repeat;}
复制代码 Wheredidwegetthosepixelvalues?Let’sbreakitdown:thefirstvalueisofcoursethehorizontaloffset(fromtheleftedge),andthesecondisthevertical.
Eachverticalvalueisequal;sincethemasterimageis400pixelshighandtheafterstatessitinthebottomhalf,we’vesimplydividedtheheight.Shiftingthewholebackgroundimageupby200pxrequiresustoapplythevalueasanegativenumber.Thinkofthetopedgeofthelinkasthestartingpoint,or0.Topositionthebackgroundimage200pixelsabovethispoint,itmakessensetomovethestartingpoint-200px.
Likewise,iftheleftedgeofeachlinkiseffectively0,we’llneedtooffsetthebackgroundimagehorizontallybythewidthofall<li>spriortotheonewe’reworkingwith.Sothefirstlinkdoesn’trequireanoffset,sincetherearenopixelsbeforeitshorizontalstartingpoint.Thesecondlinkrequiresanoffsetthewidthofthefirst,thethirdlinkrequiresanoffsetofthecombinedwidthofthefirsttwolinks,andthelastrequiresanoffsetofthecombinedwidthofallthreepreviouslinks.
It’sabitcumbersometoexplaintheprocess,butplayingaroundwiththevalueswillquicklyshowyouhowtheoffsetswork,andonceyou’refamiliarit’snotallthathardtodo.
Sothereyouhaveit.Single-imageCSSrollovers,degradabletoasimpleunorderedlist.
Buttons
There’snoreasonwhywehavetoleavethelinkstouchingeachother,side-by-sideastheywereinthepreviousexample.Imagemapsmaybeconvenientinsomespots,butwhataboutseparatingeachlinkintoitsownstand-alonebutton?Thatwaywecanaddbordersandmargins,lettheunderlyingbackgroundshowthrough,andgenerallytreatthemasseparatelyasweneedto.
Infact,thebuildingblocksarealreadyinplace.Wereallydon’tneedtomodifyourcodetooradically;themainchangeisincreatinganewbackgroundimagethatdoesn’tcontinuefromlinktolinklikethelastexampledid.Sincewecan’trelyonthe<ul>forplacingtheoriginalbackgroundimage,we’llendupapplyingittoall<li>sinsteadandoffsettingeachthesamewayweoffsettheafterstatesinthepriorexample.
Withanappropriateimageandabitofspacingbetweeneach<li>,we’vegotbuttons.
Notethatinthisexamplewe’veadded1pxborderswhich,ofcourse,counttowardthefinalwidthofthelinks.Thisaffectsouroffsetvalues;we’vecompensatedbyadding2pxtotheoffsetswhereappropriate.
Irregularshapes
Uptillnowwe’vefocusedonlyonrectangular,non-overlappingshapes.WhataboutthemorecompleximagemapsthatimageslicerslikeFireworksandImageReadyexportsoeasily?Relax,we’vegotyoucoveredtheretoo.
We’llstartthesamewayasthefirstexample,byapplyingthebackgroundimagetothe<ul>andturningofflistitembulletsandsettingwidthsandsoforth.Thebigdifferenceiswherewepositionthe<li>s;thegoalistosurroundeachgraphicalelementwithaboxthattightlyhugstheedges.
Again,becauseoftheabilitytouseabsolutepositioningrelativetothetopleftcornerofthe<ul>,we’reabletopreciselyplaceourlinksexactlywherewewantthem.Nowallthat’sleftistosetupthehoverstates.
Worthnotingisthatinthiscase,asinglesetofbeforeandafterimageswasn’tenough.Becauseoftheoverlappingobjects,relyingononlyoneafterstatewouldshowpiecesofsurroundingobjects’afterstates.Infact,itwouldshowpreciselythepiecesthatfallwithinthelink’sborders.(Easiesttojustseeitinaction.)
Howtoavoidthis?Byaddingasecondafterstate,andcarefullyselectingwhichobjectsgowhere.Themasterimageinthiscasehassplitthepurpleandblueobjectsintothefirstafterstate,andthegreen,orangeandyellowobjectsintothesecond.Thisorderallowsboxestobedrawnaroundeachobject’safterstatewithoutincludingpiecesofthesurroundingobjects.Andtheillusioniscomplete.
Benefitsandpitfalls
Acoupleoffinalthoughts.OurnewCSSSpritemethodtestswellinmostmodernbrowsers.ThenotableexceptionisOpera6,whichdoesn’tapplyabackgroundimageonlinkhoverstates.Why,we’renotsure,butitmeansthatourhoversdon’twork.Thelinksstilldo,andifthey’vebeenlabeledproperly,thenetresultwillbeastatic,butusableimagemapinOpera6.We’rewillingtolivewiththat,especiallynowthatOpera7hasbeenaroundforawhile.
TheotherconcernisfamiliartoanyonewhohasspenttimewithFIR.IntherarecasesinwhichusershaveturnedoffimagesintheirbrowsersbutretainedCSS,abigemptyholewillappearinthepagewhereweexpectourimagestobeplaced.Thelinksarestillthereandclickable,butnothingvisuallyappears.Atpresstime,therewasnoknownwayaroundthis.
Thenthere’sfilesize.Thenaturaltendencyistoassumethatafulldouble-sizedimagemustbeheavierthanasimilarsetofslicedimages,sincetheoverallimageareawillusuallybelarger.Allimageformatshaveacertainamountofoverheadthough(whichiswhya1pxby1pxwhiteGIFsavestoaround50bytes),andthemoreslicesyouhave,themorequicklythatoverheadaddsup.Plus,onemasterimagerequiresonlyasinglecolortablewhenusingaGIF,buteachslicewouldneeditsown.PreliminarytestssuggestthatallthisindicatessmallertotalfilesizesforCSSSprites,orattheveryleastnotappreciablylargersizes.
Andlastly,let’snotforgetthatourmarkupisniceandclean,withalltheadvantagesthatgoalongwiththat.HTMLlistsdegradewonderfully,andaproperimagereplacementtechniquewillleavethetextlinksaccessibletoscreenreaders.Replacingthespriteimageryisdeadsimple,sinceallofourdimensionsandoffsetsarecontrolledinasingleCSSfile,andallofourimagerysitsinasingleimage.
原文毗连:http://www.alistapart.com/articles/sprites/
一般来说还需要用Photoshop或FireWorks(以下简称PS或FW)等图片处理软件将需要制作的界面布局简单的构画出来。 |
|