来一发CSS Sprite图片处置技能
更方便搜索引擎的搜索。用只包含结构化内容的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)等图片处理软件将需要制作的界面布局简单的构画出来。 只要我们努力,无论是怎样的艰难险阻,成功依然会迎面直击。在刚开始时我觉得dreamweavermxXX很难理解。 Dreamweaver在所见即所得添加链接时,可以在选中文字后在属性栏中的链接栏中直接输入文件的地址即可。 还是在Dreamweaver所见即所得添加链接是,可以选中文字或图片然后按下shift键不放鼠标拖出箭头直接指向文件即可。这是比较简单的也是常用的方之一。 滚动条)层属性--溢出(visible/hidden/scroll/auto) 还可以在Dreamweaver常用工具中选择超级链接,完成相应的填写即可。 技术的学习如同长跑。只要越过极限,就会越跑越轻松。技术的学习其实并不像想象中那么可怕,任何技术都并不高深莫测。 不管老师做怎样的解释,而我却对它感到很是吃力,诸如里面有许多不知道的功能。 还是在Dreamweaver所见即所得添加链接是,可以选中文字或图片然后按下shift键不放鼠标拖出箭头直接指向文件即可。这是比较简单的也是常用的方之一。
页:
[1]