Responsive Web Design - What It Is And How To Use It

文章推薦指數: 80 %
投票人數:10人

Responsive Web design is the approach that suggests that design and development should respond to the user's behavior and environment based ... Skiptomaincontent Jumptoalltopics Startreadingthearticle Jumptolistofallarticles32minreadCoding, CSS, ResponsiveDesign, MediaQueriesShareonTwitter, LinkedInAboutTheAuthorVitalyFriedmanlovesbeautifulcontentanddoesn’tliketogiveineasily.Whenheisnotwriting,he’smostprobablyrunningfront-end&UX… Moreabout Vitaly ↬EmailNewsletterYour(smashing)email Weeklytipsonfront-end&UX.Trustedby176.000folks. Learndesign,coding,video,motiongraphics&more. Buildin-demandskillslikeUX,UIandHCI—NorthwesternonlineMSinInfo.Design&Strategy SmartInterfaceDesignChecklists TheFundamentalsofUXWritingWorkshop SmartInterfaceDesignPatterns,withVitalyFriedmanQuicksummary ↬ Almosteverynewclientthesedayswantsamobileversionoftheirwebsite.It’spracticallyessentialafterall:onedesignfortheBlackBerry,anotherfortheiPhone,theiPad,netbook,Kindle—andallscreenresolutionsmustbecompatible,too.Inthenextfiveyears,we’lllikelyneedtodesignforanumberofadditionalinventions.Whenwillthemadnessstop?Itwon’t,ofcourse.Almosteverynewclientthesedayswantsamobileversionoftheirwebsite.It’spracticallyessentialafterall:onedesignfortheBlackBerry,anotherfortheiPhone,theiPad,netbook,Kindle—andallscreenresolutionsmustbecompatible,too.Inthenextfiveyears,we’lllikelyneedtodesignforanumberofadditionalinventions.Whenwillthemadnessstop?Itwon’t,ofcourse.InthefieldofWebdesignanddevelopment,we’requicklygettingtothepointofbeingunabletokeepupwiththeendlessnewresolutionsanddevices.Formanywebsites,creatingawebsiteversionforeachresolutionandnewdevicewouldbeimpossible,oratleastimpractical.Shouldwejustsuffertheconsequencesoflosingvisitorsfromonedevice,forthebenefitofgainingvisitorsfromanother?Oristhereanotheroption?WhatisResponsiveWebdesign?ResponsiveWebdesignistheapproachthatsuggeststhatdesignanddevelopmentshouldrespondtotheuser’sbehaviorandenvironmentbasedonscreensize,platformandorientation.Thepracticeconsistsofamixofflexiblegridsandlayouts,imagesandanintelligentuseofCSSmediaqueries.AstheuserswitchesfromtheirlaptoptoiPad,thewebsiteshouldautomaticallyswitchtoaccommodateforresolution,imagesizeandscriptingabilities.Onemayalsohavetoconsiderthesettingsontheirdevices;iftheyhaveaVPNforiOSontheiriPad,forexample,thewebsiteshouldnotblocktheuser’saccesstothepage.Inotherwords,thewebsiteshouldhavethetechnologytoautomaticallyrespondtotheuser’spreferences.Thiswouldeliminatetheneedforadifferentdesignanddevelopmentphaseforeachnewgadgetonthemarket.FurtherReadingonSmashingMag:ResponsiveWebDesignTechniques,ToolsandStrategiesTheStateOfResponsiveWebDesignDesignProcessInTheResponsiveAgeTechniquesForGracefullyDegradingMediaQueriesAussieHosting’sListofResponsiveWebHostsMoreafterjump!Continuereadingbelow ↓MeetSmashingOnlineWorkshopsonfront-end&UX,withpracticaltakeaways,livesessions,videorecordingsandafriendlyQ&A.Ondesignsystems,UX,webperformanceandCSS/JS.WithBradFrost,StephanieTroethandsomanyothers.Jumptoonlineworkshops ↬TheConceptOfResponsiveWebDesignEthanMarcottewroteanintroductoryarticleabouttheapproach,ResponsiveWebDesign,forAListApart.Itstemsfromthenotionofresponsivearchitecturaldesign,wherebyaroomorspaceautomaticallyadjuststothenumberandflowofpeoplewithinit:"Recently,anemergentdisciplinecalled“responsivearchitecture”hasbegunaskinghowphysicalspacescanrespondtothepresenceofpeoplepassingthroughthem.Throughacombinationofembeddedroboticsandtensilematerials,architectsareexperimentingwithartinstallationsandwallstructuresthatbend,flex,andexpandascrowdsapproachthem.Motionsensorscanbepairedwithclimatecontrolsystemstoadjustaroom’stemperatureandambientlightingasitfillswithpeople.Companieshavealreadyproduced“smartglasstechnology”thatcanautomaticallybecomeopaquewhenaroom’soccupantsreachacertaindensitythreshold,givingthemanadditionallayerofprivacy."TransplantthisdisciplineontoWebdesign,andwehaveasimilaryetwholenewidea.WhyshouldwecreateacustomWebdesignforeachgroupofusers;afterall,architectsdon’tdesignabuildingforeachgroupsizeandtypethatpassesthroughit?Likeresponsivearchitecture,Webdesignshouldautomaticallyadjust.Itshouldn’trequirecountlesscustom-madesolutionsforeachnewcategoryofusers.Obviously,wecan’tusemotionsensorsandroboticstoaccomplishthisthewayabuildingwould.ResponsiveWebdesignrequiresamoreabstractwayofthinking.However,someideasarealreadybeingpracticed:fluidlayouts,mediaqueriesandscriptsthatcanreformatWebpagesandmark-upeffortlessly(orautomatically).ButresponsiveWebdesignisnotonlyaboutadjustablescreenresolutionsandautomaticallyresizableimages,butratheraboutawholenewwayofthinkingaboutdesign.Let’stalkaboutallofthesefeatures,plusadditionalideasinthemaking.AdjustingScreenResolutionWithmoredevicescomevaryingscreenresolutions,definitionsandorientations.Newdeviceswithnewscreensizesarebeingdevelopedeveryday,andeachofthesedevicesmaybeabletohandlevariationsinsize,functionalityandevencolor.Someareinlandscape,othersinportrait,stillothersevencompletelysquare.AsweknowfromtherisingpopularityoftheiPhone,iPadandadvancedsmartphones,manynewdevicesareabletoswitchfromportraittolandscapeattheuser’swhim.Howisonetodesignforthesesituations?Inadditiontodesigningforbothlandscapeandportrait(andenablingthoseorientationstopossiblyswitchinaninstantuponpageload),wemustconsiderthehundredsofdifferentscreensizes.Yes,itispossibletogroupthemintomajorcategories,designforeachofthem,andmakeeachdesignasflexibleasnecessary.Butthatcanbeoverwhelming,andwhoknowswhattheusagefigureswillbeinfiveyears?Besides,manyusersdonotmaximizetheirbrowsers,whichitselfleavesfartoomuchroomforvarietyamongscreensizes.MortenHjerdeandafewofhiscolleaguesidentifiedstatisticsonabout400devicessoldbetween2005and2008.Belowaresomeofthemostcommon:Sincethenevenmoredeviceshavecomeout.It’sobviousthatwecan’tkeepcreatingcustomsolutionsforeachone.So,howdowedealwiththesituation?PartoftheSolution:FlexibleEverythingAfewyearsago,whenflexiblelayoutswerealmosta“luxury”forwebsites,theonlythingsthatwereflexibleinadesignwerethelayoutcolumns(structuralelements)andthetext.Imagescouldeasilybreaklayouts,andevenflexiblestructuralelementsbrokealayout’sformwhenpushedenough.Flexibledesignsweren’treallythatflexible;theycouldgiveortakeafewhundredpixels,buttheyoftencouldn’tadjustfromalargecomputerscreentoanetbook.Nowwecanmakethingsmoreflexible.Imagescanbeautomaticallyadjusted,andwehaveworkaroundssothatlayoutsneverbreak(althoughtheymaybecomesquishedandillegibleintheprocess).Whileit’snotacompletefix,thesolutiongivesusfarmoreoptions.It’sperfectfordevicesthatswitchfromportraitorientationtolandscapeinaninstantorforwhenusersswitchfromalargecomputerscreentoaniPad.InEthanMarcotte’sarticle,hecreatedasampleWebdesignthatfeaturesthisbetterflexiblelayout:Theentiredesignisalovelymixoffluidgrids,fluidimagesandsmartmark-upwhereneeded.Creatingfluidgridsisfairlycommonpractice,andthereareanumberoftechniquesforcreatingfluidimages:HidingandRevealingPortionsofImagesCreatingSlidingCompositeImagesForegroundImagesThatScaleWiththeLayoutFormoreinformationoncreatingfluidwebsites,besuretolookatthebook“FlexibleWebDesign:CreatingLiquidandElasticLayoutswithCSS”byZoeMickleyGillenwater,anddownloadthesamplechapter“CreatingFlexibleImages.”Inaddition,Zoeprovidesthefollowingextensivelistoftutorials,resources,inspirationandbestpracticesoncreatingflexiblegridsandlayouts:“EssentialResourcesforCreatingLiquidandElasticLayouts.”Whilefromatechnicalperspectivethisisalleasilypossible,it’snotjustaboutpluggingthesefeaturesinandbeingdone.Lookatthelogointhisdesign,forexample:Ifresizedtoosmall,theimagewouldappeartobeoflowquality,butkeepingthenameofthewebsitevisibleandnotcroppingitoffwasimportant.So,theimageisdividedintotwo:one(oftheillustration)setasabackground,tobecroppedandtomaintainitssize,andtheother(ofthename)resizedproportionally.Above,theh1elementholdstheillustrationasabackground,andtheimageisalignedaccordingtothecontainer’sbackground(theheading).ThisisjustoneexampleofthekindofthinkingthatmakesresponsiveWebdesigntrulyeffective.Butevenwithsmartfixeslikethis,alayoutcanbecometoonarroworshorttolookright.Inthelogoexampleabove(althoughitworks),theidealsituationwouldbetonotcrophalfoftheillustrationortokeepthelogofrombeingsosmallthatitbecomesillegibleand“floats”up.FlexibleImagesOnemajorproblemthatneedstobesolvedwithresponsiveWebdesignisworkingwithimages.Thereareanumberoftechniquestoresizeimagesproportionately,andmanyareeasilydone.Themostpopularoption,notedinEthanMarcotte’sarticleonfluidimagesbutfirstexperimentedwithbyRichardRutter,istouseCSS’smax-widthforaneasyfix.img{max-width:100%;}Aslongasnootherwidth-basedimagestylesoverridethisrule,everyimagewillloadinitsoriginalsize,unlesstheviewingareabecomesnarrowerthantheimage’soriginalwidth.Themaximumwidthoftheimageissetto100%ofthescreenorbrowserwidth,sowhenthat100%becomesnarrower,sodoestheimage.Essentially,asJasonGrigsbynoted,“Theideabehindfluidimagesisthatyoudeliverimagesatthemaximumsizetheywillbeusedat.Youdon’tdeclaretheheightandwidthinyourcode,butinsteadletthebrowserresizetheimagesasneededwhileusingCSStoguidetheirrelativesize”.It’sagreatandsimpletechniquetoresizeimagesbeautifully.Notethatmax-widthisnotsupportedinIE,butagooduseofwidth:100%wouldsolvetheproblemneatlyinanIE-specificstylesheet.OnemoreissueisthatwhenanimageisresizedtoosmallinsomeolderbrowsersinWindows,therenderingisn’tasclearasitoughttobe.ThereisaJavaScripttofixthisissue,though,foundinEthanMarcotte’sarticle.Whiletheaboveisagreatquickfixandgoodstarttoresponsiveimages,imageresolutionanddownloadtimesshouldbetheprimaryconsiderations.Whileresizinganimageformobiledevicescanbeverysimple,iftheoriginalimagesizeismeantforlargedevices,itcouldsignificantlyslowdownloadtimesandtakeupspaceunnecessarily.FilamentGroup’sResponsiveImagesThistechnique,presentedbytheFilamentGroup,takesthisissueintoconsiderationandnotonlyresizesimagesproportionately,butshrinksimageresolutiononsmallerdevices,soverylargeimagesdon’twastespaceunnecessarilyonsmallscreens.Checkoutthedemopagehere.Thistechniquerequiresafewfiles,allofwhichareavailableonGithub.First,aJavaScriptfile(rwd-images.js),the.htaccessfileandanimagefile(rwd.gif).Then,wecanusejustabitofHTMLtoreferenceboththelargerandsmallerresolutionimages:first,thesmallimage,withan.rprefixtoclarifythatitshouldberesponsive,andthenareferencetothebiggerimageusingdata-fullsrc.Thedata-fullsrcisacustomHTML5attribute,definedinthefileslinkedtoabove.Foranyscreenthatiswiderthan480pixels,thelarger-resolutionimage(largeRes.jpg)willload;smallerscreenswouldn’tneedtoloadthebiggerimage,andsothesmallerimage(smallRes.jpg)willload.TheJavaScriptfileinsertsabaseelementthatallowsthepagetoseparateresponsiveimagesfromothersandredirectsthemasnecessary.Whenthepageloads,allfilesarerewrittentotheiroriginalforms,andonlythelargeorsmallimagesareloadedasnecessary.Withothertechniques,allhigher-resolutionimageswouldhavehadtobedownloaded,evenifthelargerversionswouldneverbeused.Particularlyforwebsiteswithalotofimages,thistechniquecanbeagreatsaverofbandwidthandloadingtime.Thistechniqueisfullysupportedinmodernbrowsers,suchasIE8+,Safari,ChromeandOpera,aswellasmobiledevicesthatusethesesamebrowsers(iPad,iPhone,etc.).OlderbrowsersandFirefoxdegradenicelyandstillresizeasonewouldexpectofaresponsiveimage,exceptthatbothresolutionsaredownloadedtogether,sotheendbenefitofsavingspacewiththistechniqueisvoid.StopiPhoneSimulatorImageResizingOnenicethingabouttheiPhoneandiPodTouchisthatWebdesignsautomaticallyrescaletofitthetinyscreen.Afull-sizeddesign,unlessspecifiedotherwise,wouldjustshrinkproportionallyforthetinybrowser,withnoneedforscrollingoramobileversion.Then,theusercouldeasilyzoominandoutasnecessary.Therewas,however,oneissuethissimulatorcreated.WhenresponsiveWebdesigntookoff,manynoticedthatimageswerestillchangingproportionallywiththepageeveniftheywerespecificallymadefor(orcouldotherwisefit)thetinyscreen.Thisinturnscaleddowntextandotherelements.(Image:ThinkVitamin|Websitereferenced:8FacesBecausethisworksonlywithApple’ssimulator,wecanuseanApple-specificmetatagtofixtheproblem,placingitbelowthewebsite’ssection.ThankstoThinkVitamin’sarticleonimageresizing,wehavethemetatagbelow:Settingtheinitial-scaleto1overridesthedefaulttoresizeimagesproportionally,whileleavingthemasisiftheirwidthisthesameasthedevice’swidth(ineitherportraitorlanscapemode).Apple’sdocumentationhasalotmoreinformationontheviewportmetatag.CustomLayoutStructureForextremesizechanges,wemaywanttochangethelayoutaltogether,eitherthroughaseparatestylesheetor,moreefficiently,throughaCSSmediaquery.Thisdoesnothavetobetroublesome;mostofthestylescanremainthesame,whilespecificstylesheetscaninheritthesestylesandmoveelementsaroundwithfloats,widths,heightsandsoon.Forexample,wecouldhaveonemainstylesheet(whichwouldalsobethedefault)thatwoulddefineallofthemainstructuralelements,suchas#wrapper,#content,#sidebar,#nav,alongwithcolors,backgroundsandtypography.Defaultflexiblewidthsandfloatscouldalsobedefined.Ifastylesheetmadethelayouttoonarrow,short,wideortall,wecouldthendetectthatandswitchtoanewstylesheet.Thisnewchildstylesheetwouldadopteverythingfromthedefaultstylesheetandthenjustredefinethelayout’sstructure.Hereisthestyle.css(default)content:/*Defaultstylesthatwillcarrytothechildstylesheet*/ html,body{ background... font... color... } h1,h2,h3{} p,blockquote,pre,code,ol,ul{} /*Structuralelements*/ #wrapper{ width:80%; margin:0auto; background:#fff; padding:20px; } #content{ width:54%; float:left; margin-right:3%; } #sidebar-left{ width:20%; float:left; margin-right:3%; } #sidebar-right{ width:20%; float:left; }Hereisthemobile.css(child)content:#wrapper{ width:90%; } #content{ width:100%; } #sidebar-left{ width:100%; clear:both; /*Additionalstylingforournewlayout*/ border-top:1pxsolid#ccc; margin-top:20px; } #sidebar-right{ width:100%; clear:both; /*Additionalstylingforournewlayout*/ border-top:1pxsolid#ccc; margin-top:20px; }MediaQueriesCSS3supportsallofthesamemediatypesasCSS2.1,suchasscreen,printandhandheld,buthasaddeddozensofnewmediafeatures,includingmax-width,device-width,orientationandcolor.NewdevicesmadeafterthereleaseofCSS3(suchastheiPadandAndroiddevices)willdefinitelysupportmediafeatures.So,callingamediaqueryusingCSS3featurestotargetthesedeviceswouldworkjustfine,anditwillbeignoredifaccessedbyanoldercomputerbrowserthatdoesnotsupportCSS3.InEthanMarcotte’sarticle,weseeanexampleofamediaqueryinaction:Thismediaqueryisfairlyself-explanatory:ifthebrowserdisplaysthispageonascreen(ratherthanprint,etc.),andifthewidthofthescreen(notnecessarilytheviewport)is480pixelsorless,thenloadshetland.css.NewCSS3featuresalsoincludeorientation(portraitvs.landscape),device-width,min-device-widthandmore.Lookat“TheOrientationMediaQuery”formoreinformationonsettingandrestrictingwidthsbasedonthesemediaqueryfeatures.Onecancreatemultiplestylesheets,aswellasbasiclayoutalterationsdefinedtofitrangesofwidths—evenforlandscapevs.portraitorientations.BesuretolookatthesectionofEthanMarcotte’sarticleentitled“Meetthemediaquery”formoreexamplesandamorethoroughexplanation.Multiplemediaqueriescanalsobedroppedrightintoasinglestylesheet,whichisthemostefficientoptionwhenused:/*Smartphones(portraitandlandscape)-----------*/ @mediaonlyscreen and(min-device-width:320px) and(max-device-width:480px){ /*Styles*/ } /*Smartphones(landscape)-----------*/ @mediaonlyscreen and(min-width:321px){ /*Styles*/ } /*Smartphones(portrait)-----------*/ @mediaonlyscreen and(max-width:320px){ /*Styles*/ }ThecodeaboveisfromafreetemplateformultiplemediaqueriesbetweenpopulardevicesbyAndyClark.Seethedifferencesbetweenthisapproachandincludingdifferentstylesheetfilesinthemark-upasdescribedinhisbook“HardboiledWebDesign.”CSS3MediaQueriesAboveareafewexamplesofhowmediaqueries,bothfromCSS2.1andCSS3couldwork.Let’snowlookatsomespecifichow-to’sforusingCSS3mediaqueriestocreateresponsiveWebdesigns.Manyoftheseusesarerelevanttoday,andallwilldefinitelybeusableinthenearfuture.Themin-widthandmax-widthpropertiesdoexactlywhattheysuggest.Themin-widthpropertysetsaminimumbrowserorscreenwidththatacertainsetofstyles(orseparatestylesheet)wouldapplyto.Ifanythingisbelowthislimit,thestylesheetlinkorstyleswillbeignored.Themax-widthpropertydoesjusttheopposite.Anythingabovethemaximumbrowserorscreenwidthspecifiedwouldnotapplytotherespectivemediaquery.Noteintheexamplesbelowthatwe’reusingthesyntaxformediaqueriesthatcouldbeusedallinonestylesheet.Asmentionedabove,themostefficientwaytousemediaqueriesistoplacethemallinoneCSSstylesheet,withtherestofthestylesforthewebsite.Thisway,multiplerequestsdon’thavetobemadeformultiplestylesheets.@mediascreenand(min-width:600px){ .hereIsMyClass{ width:30%; float:right; } }Theclassspecifiedinthemediaqueryabove(hereIsMyClass)willworkonlyifthebrowserorscreenwidthisabove600pixels.Inotherwords,thismediaquerywillrunonlyiftheminimumwidthis600pixels(therefore,600pixelsorwider).@mediascreenand(max-width:600px){ .aClassforSmallScreens{ clear:both; font-size:1.3em; } }Now,withtheuseofmax-width,thismediaquerywillapplyonlytobrowserorscreenwidthswithamaximumwidthof600pixelsornarrower.Whiletheabovemin-widthandmax-widthcanapplytoeitherscreensizeorbrowserwidth,sometimeswe’dlikeamediaquerythatisrelevanttodevicewidthspecifically.Thismeansthatevenifabrowserorotherviewingareaisminimizedtosomethingsmaller,themediaquerywouldstillapplytothesizeoftheactualdevice.Themin-device-widthandmax-device-widthmediaquerypropertiesaregreatfortargetingcertaindeviceswithsetdimensions,withoutapplyingthesamestylestootherscreensizesinabrowserthatmimicsthedevice’ssize.@mediascreenand(max-device-width:480px){ .classForiPhoneDisplay{ font-size:1.2em; } }@mediascreenand(min-device-width:768px){ .minimumiPadWidth{ clear:both; margin-bottom:2pxsolid#ccc; } }FortheiPadspecifically,thereisalsoamediaquerypropertycalledorientation.Thevaluecanbeeitherlandscape(horizontalorientation)orportrait(verticalorientation).@mediascreenand(orientation:landscape){ .iPadLandscape{ width:30%; float:right; } }@mediascreenand(orientation:portrait){ .iPadPortrait{ clear:both; } }Unfortunately,thispropertyworksonlyontheiPad.WhendeterminingtheorientationfortheiPhoneandotherdevices,theuseofmax-device-widthandmin-device-widthshoulddothetrick.Therearealsomanymediaqueriesthatmakesensewhencombined.Forexample,themin-widthandmax-widthmediaqueriesarecombinedallthetimetosetastylespecifictoacertainrange.@mediascreenand(min-width:800px)and(max-width:1200px){ .classForaMediumScreen{ background:#cc0000; width:30%; float:right; } }Theabovecodeinthismediaqueryappliesonlytoscreenandbrowserwidthsbetween800and1200pixels.Agooduseofthistechniqueistoshowcertaincontentorentiresidebarsinalayoutdependingonhowmuchhorizontalspaceisavailable.Somedesignerswouldalsoprefertolinktoaseparatestylesheetforcertainmediaqueries,whichisperfectlyfineiftheorganizationalbenefitsoutweightheefficiencylost.Fordevicesthatdonotswitchorientationorforscreenswhosebrowserwidthcannotbechangedmanually,usingaseparatestylesheetshouldbefine.Youmightwant,forexample,toplacemediaqueriesallinonestylesheet(asabove)fordevicesliketheiPad.Becausesuchadevicecanswitchfromportraittolandscapeinaninstant,ifthesetwomediaquerieswereplacedinseparatestylesheets,thewebsitewouldhavetocalleachstylesheetfileeverytimetheuserswitchedorientations.PlacingamediaqueryforboththehorizontalandverticalorientationsoftheiPadinthesamestylesheetfilewouldbefarmoreefficient.Anotherexampleisaflexibledesignmeantforastandardcomputerscreenwitharesizablebrowser.Ifthebrowsercanbemanuallyresized,placingallvariablemediaqueriesinonestylesheetwouldbebest.Nevertheless,organizationcanbekey,andadesignermaywishtodefinemediaqueriesinastandardHTMLlinktag: JavaScriptAnothermethodthatcanbeusedisJavaScript,especiallyasaback-uptodevicesthatdon’tsupportalloftheCSS3mediaqueryoptions.Fortunately,thereisalreadyapre-madeJavaScriptlibrarythatmakesolderbrowsers(IE5+,Firefox1+,Safari2)supportCSS3mediaqueries.Ifyou’realreadyusingthesequeries,justgrabacopyofthelibrary,andincludeitinthemark-up:css3-mediaqueries.js.Inaddition,belowisasamplejQuerysnippetthatdetectsbrowserwidthandchangesthestylesheetaccordingly—ifoneprefersamorehands-onapproach: $(document).ready(function(){ $(window).bind("resize",resizeWindow); functionresizeWindow(e){ varnewWindowWidth=$(window).width(); //Ifwidthwidthisbelow600px,switchtothemobilestylesheet if(newWindowWidth<600){$("link[rel=stylesheet]").attr({href:"mobile.css"});}//Elseifwidthisabove600px,switchtothelargestylesheetelseif(newWindowWidth>600){ $("link[rel=stylesheet]").attr({href:"style.css"}); } } }); TherearemanysolutionsforpairingupJavaScriptwithCSSmediaqueries.Rememberthatmediaqueriesarenotanabsoluteanswer,butratherarefantasticoptionsforresponsiveWebdesignwhenitcomestopureCSS-basedsolutions.WiththeadditionofJavaScript,wecanaccomodatefarmorevariations.FordetailedinformationonusingJavaScripttomimicorworkwithmediaqueries,lookat“CombiningMediaQueriesandJavaScript.”ShowingorHidingContentItispossibletoshrinkthingsproportionallyandrearrangeelementsasnecessarytomakeeverythingfit(reasonablywell)asascreengetssmaller.It’sgreatthatthat’spossible,butmakingeverypieceofcontentfromalargescreenavailableonasmallerscreenormobiledeviceisn’talwaysthebestanswer.Wehavebestpracticesformobileenvironments:simplernavigation,morefocusedcontent,listsorrowsinsteadofmultiplecolumns.ResponsiveWebdesignshouldn’tbejustabouthowtocreateaflexiblelayoutonawiderangeofplatformsandscreensizes.Itshouldalsobeabouttheuserbeingabletopickandchoosecontent.Fortunately,CSShasbeenallowingustoshowandhidecontentwitheaseforyears!display:none;Eitherdeclaredisplay:nonefortheHTMLblockelementthatneedstobehiddeninaspecificstylesheetordetectthebrowserwidthanddoitthroughJavaScript.Inadditiontohidingcontentonsmallerscreens,wecanalsohidecontentinourdefaultstylesheet(forbiggerscreens)thatshouldbeavailableonlyinmobileversionsoronsmallerdevices.Forexample,aswehidemajorpiecesofcontent,wecouldreplacethemwithnavigationtothatcontent,orwithadifferentnavigationstructurealtogether.Notethatwehaven’tusedvisibility:hiddenhere;thisjusthidesthecontent(althoughitisstillthere),whereasthedisplaypropertygetsridofitaltogether.Forsmallerdevices,thereisnoneedtokeepthemark-uponthepage—itjusttakesupresourcesandmightevencauseunnecessaryscrollingorbreakthelayout.Hereisourmark-up:LeftSidebarContent|RightSidebarContent

MainContent

ALeftSidebar

ARightSidebar

Inourdefaultstylesheetbelow,wehavehiddenthelinkstothesidebarcontent.Becauseourscreenislargeenough,wecandisplaythiscontentonpageload.Hereisthestyle.css(default)content:#content{ width:54%; float:left; margin-right:3%; } #sidebar-left{ width:20%; float:left; margin-right:3%; } #sidebar-right{ width:20%; float:left; } .sidebar-nav{display:none;}Now,wehidethetwosidebars(below)andshowthelinkstothesepiecesofcontent.Asanalternative,thelinkscouldcalltoJavaScripttojustcanceloutthedisplay:nonewhenclicked,andthesidebarscouldberealignedintheCSStofloatbelowthecontent(orinanotherreasonableway).Hereisthemobile.css(simpler)content:#content{ width:100%; } #sidebar-left{ display:none; } #sidebar-right{ display:none; } .sidebar-nav{display:inline;}Withtheabilitytoeasilyshowandhidecontent,rearrangelayoutelementsandautomaticallyresizeimages,formelementsandmore,adesigncanbetransformedtofitahugevarietyofscreensizesanddevicetypes.Asthescreengetssmaller,rearrangeelementstofitmobileguidelines;forexample,useascriptoralternatestylesheettoincreasewhitespaceortoreplaceimagenavigationsourcesonmobiledevicesforbetterusability(iconswouldbemorebeneficialonsmallerscreens).Touchscreensvs.CursorsTouchscreensarebecomingincreasinglypopular.Assumingthatsmallerdevicesaremorelikelytobegiventouchscreenfunctionalityiseasy,butdon’tbesoquick.Rightnowtouchscreensaremainlyonsmallerdevices,butmanylaptopsanddesktopsonthemarketalsohavetouchscreencapability.Forexample,theHPTouchsmarttm2tisabasictouchscreenlaptopwithtraditionalkeyboardandmousethatcantransformintoatablet.Touchscreensobviouslycomewithdifferentdesignguidelinesthanpurelycursor-basedinteraction,andthetwohavedifferentcapabilitiesaswell.Fortunately,makingadesignworkforbothdoesn’ttakealotofeffort.TouchscreenshavenocapabilitytodisplayCSShoversbecausethereisnocursor;oncetheusertouchesthescreen,theyclick.So,don’trelyonCSShoversforlinkdefinition;theyshouldbeconsideredanadditionalfeatureonlyforcursor-baseddevices.Lookatthearticle“DesigningforTouchscreen”formoreideas.Manyofthedesignsuggestionsinitarebestfortouchscreens,buttheywouldnotnecessarilyimpaircursor-basedusabilityeither.Forexample,sub-navigationontherightsideofthepagewouldbemoreuser-friendlyfortouchscreenusers,becausemostpeopleareright-handed;theywouldthereforenotbumporbrushthenavigationaccidentallywhenholdingthedeviceintheirlefthand.Thiswouldmakenodifferencetocursorusers,sowemightaswellfollowthetouchscreendesignguidelineinthisinstance.Manymoreguidelinesofthiskindcanbedrawnfromtouchscreen-basedusability.AShowcaseOfResponsiveWebDesignBelowwehaveafewexamplesofresponsiveWebdesigninpracticetoday.Formanyofthesewebsites,thereismorevariationinstructureandstylethanisshowninthepairsofscreenshotsprovided.Manyhaveseveralsolutionsforavarietyofbrowsers,andsomeevenadjustelementsdynamicallyinsizewithouttheneedforspecificbrowserdimensions.Visiteachofthese,andadjustyourbrowsersizeorchangedevicestoseetheminaction.ArtEqualsWorkisasimpleyetgreatexampleofresponsiveWebdesign.Thefirstscreenshotbelowistheviewfromastandardcomputerscreendimension.Thewebsiteisflexiblewithbrowserwidthsbytraditionalstandars,butoncethebrowsergetstoonarroworisotherwiseswitchedtoadevicewithasmallerscreen,thenthelayoutswitchestoamorereadableanduser-friendlyformat.Thesidebardisappears,navigationgoestothetop,andtextisenlargedforeasyandsimpleverticalreading.WithThinkVitamin,weseeasimilarapproach.Whenonasmallerscreenorbrowser,thesidebarandtopbarareremoved,thenavigationsimplifiesandmovesdirectlyabovethecontent,asdoesthelogo.Thelogokeepsitsgenerallookyetismodifiedforamoreverticalorientation,withthetaglinebelowthemainicon.Thewhitespacearoundthecontentonlargerscreensisalsomorespaciousandinteresting,whereasitissimplifiedforpracticalpurposesonsmallerscreens.8Faces’websitedesignisflexible,rightdowntoastandardnetbookortabletdevice,andexpandsincontentquantityandlayoutwidthwhenviewedonwiderscreensorexpandedbrowsers.Whenviewedonnarrowerscreens,thefeaturedissueontherightiscutout,andthecontentbelowisshortenedandrearrangedinlayout,leavingonlytheessentialinformation.TheHicksdesignwebsitehasthreecolumnswhenviewedonaconventionalcomputerscreenwithamaximizedbrowser.Whenminimizedinwidth,thedesigntakesonanewlayout:thethirdcolumntotherightisrearrangedabovethesecond,andthelogomovesnexttotheintroductorytext.Thus,nocontentneedstoberemovedforthesmallersize.Forevennarrowerscreensandbrowserwidths,thesidecontentisremovedcompletelyandasimplifiedversionismoveduptop.Finally,thefontsizechangeswiththescreenandbrowserwidth;asthebrowsergetsnarrower,thefontsizethroughoutgetssmallerandremainsproportional.Hereisagreatexampleofaflexibleimage.Theimageinthisdesignautomaticallyresizesaftercertain“break”points,butinbetweenthosewidthchanges,onlythesidemarginsandexcesswhitespacearealtered.Onsmallerscreensandminimizedbrowsers,thenavigationsimplifiesandthecolumnsofnavigationatthetopfalloff.Atthedesign’ssmallestversion,thenavigationsimplifiestojustadrop-downmenu,perfectforsavingspacewithoutsacrificingcriticalnavigationlinks.ThewebsiteforGarretKeizerisfullyflexibleinwiderbrowsersandonlargerscreens:thephoto,logoandotherimagesresizeproportionally,asdotheheadingsandblockareasfortext.Atafewpoints,somepiecesoftextchangeinfontsizeandgetsmallerasthescreenorbrowsergetsnarrower.Afteracertainbreakpoint,thelayouttransformsintowhatweseeinthesecondscreenshotbelow,withasimplelogo,introductorytextandasimpleverticalstructurefortheremainingcontent.Withfourrelativelycontent-heavycolumns,it’seasytoseehowthecontentherecouldeasilybesquishedwhenviewedonsmallerdevices.Becauseoftheeasyorganizedcolumns,though,wecanalsocollapsethemquitesimplywhenneeded,andwecanstackthemverticallywhenthespacedoesn’tallowforareasonablehorizontalspan.Whenthebrowserisminimizedortheuserisonasmallerdevice,thecolumnsfirstcollapseintotwoandthenintoone.Likewise,thehorizontallinesforbreakpointsalsochangeinwidth,withoutchangingthesizeorstyleofeachline’stitletext.OntheCSSTrickswebsite,likemanyothercollapsibleWebdesigns,thesidebarswithexcesscontentarethefirsttofalloffwhenthescreenorbrowsergetstoonarrow.Onthisparticularwebsite,themiddlecolumnorfirstsidebartotheleftwasthefirsttodisappear;andthesidebarwiththeadsandwebsiteextrasdidthesamewhenthebrowsergotevennarrower.Eventually,thedesignleavestheposts,useslesswhitespacearoundthenavigationandlogoandmovesthesearchbartobelowthenavigation.Theremaininglayoutanddesignisasflexibleascanbebecauseofitssimplicity.Asonecansee,themainnavigationhereisthesimplelayoutoft-shirtdesigns,spanningbothverticallyandhorizontallyacrossthescreen.Asthebrowserorscreengetssmaller,thecolumnscollapseandmovebelow.Thishappensateachbreakpointwhenthelayoutisstressed,butinbetweenthebreakpoints,theimagesjustchangeproportionallyinsize.Thismaintainsbalanceinthedesign,whileensuringthatanyimages(whichareessentialtothewebsite)don’tgetsosmallthattheybecomeunusable.TenbyTwentyisanotherdesignthatdoesnotresorttochanginglayoutstructureatallaftercertainbreakpoints,butrathersimplifiesresponsiveWebdesignbymakingeverythingfullyflexibleandautomaticallyresizing,nomatterwhatthescreenorbrowserwidth.Afterawhile,thedesigndoesstressabitandcouldbenefitfromsomerearrangementofcontent.Butoverall,theimageresizingandflexiblecontentspacesallowforafairlysimplesolutionthataccommodatesawiderangeofscreensizes.Onwidescreensandbrowsers,allofthecontentonthissimplydesignedwebsiteiswellorganizedintocolumns,sidebarandsimplenavigationuptop.It’safairlystandardandefficientlayout.Onsmallerscreens,thesidebaristhefirsttodropoff,anditscontentismovedbelowthebookpreviewsandessentialinformation.Beinglimitedinspace,thisdesignpreservesitsimportanthierarchy.Whereasonawiderscreenwe’dlooklefttoright,onanarrowerscreenwe’dtendtolookfromtoptobottom.Contentontherightismovedbelowcontentthatwouldappearontheleftonawiderscreen.Eventually,whenthehorizontalspaceisfullylimited,thenavigationissimplifiedandstackedvertically,andsomerepeatedorinessentialelementsareremoved.Thisdesignfeaturesacomplexlayoutthatlooksinspiredbyaprintstyle.Whenviewedonastandardwidecomputerscreen,moreportfoliopiecesarefeaturedandspannedhorizontallyacrossthepage.Asonemovesdownthepage,moregraphicsandimageryspanthespace.Onasmallerscreen,theportfoliopieceiscutdowntoone,andtheneventuallyleftoutaltogetherforverysmallscreensandnarrowbrowsers.Thevisualizationsbelowcollapseintofewercolumnsandmorerows,andagain,somedropoffentirelyforverysmallscreens.Thisdesignshowsacreativeandintelligentwaytomakeanot-so-commonlayoutworkresponsively.Thisdesignhasthreemainstagesatwhichthedesignandlayoutcollapseintoamoreuser-friendlyform,dependingonhowwidethescreenorbrowseris.Themainimage(featuringtype)isscaledproportionallyviaaflexibleimagemethod.Each“layoutstructure”isfullyflexibleuntilitreachesabreakingpoint,atwhichpointthelayoutswitchestosomethingmoreusablewithlesshorizontalspace.Thebottomfourcolumnseventuallycollapseintotwo,thelogomovesabovethenavigation,andthecolumnsofnavigationbelowaremovedontoporbeloweachother.Atthedesign’snarroweststage,thenavigationissuper-simplified,andsomeinessentialcontentiscutoutaltogether.Thislayoutdoesnotchangeatall;nocontentisdroppedorrearranged;andthetextsizedoesnotchangeeither.Instead,thisdesignkeepsitsoriginalform,nomatterwhatthechangeinhorizontalandverticalspace.Instead,itautomaticallyresizestheheaderimageandtheimagesforthenavigation.Thewhitespace,marginsandpaddingarealsoflexible,givingmoreroomasthedesignexpandsandshrinks.ThisisperhapsthesimplestexampleofaresponsiveWebdesigninthisshowcase,butalsooneofthemostversatile.Theonlypieceinthelayoutthatchangeswiththebrowserwidthistheblogpost’sdate,whichmovesabovethepost’stitleortotheside,dependingonhowmuchhorizontalspaceisavailable.Beyondthis,theonlythingthatchangesisthewidthofthecontentareaandthemarginspaceontheleftandright.Everythingiscentered,soasenseofbalanceismaintainedwhateverthescreenorbrowserwidth.Becauseofthisdesign’ssimplicity,switchingbetweenbrowserandscreenwidthsisquickandeasy.HarryRobertsshowsthatresponsivedesigncanalsohavequitehumbleuses.Iftheuserhasalargeviewport,thewebsitedisplaysthreecolumnswithanavigationmenufloatingontheleft.Foruserswithaviewportbetween481pxand800px,anarrowversionisdisplayed:thenavigationjumpstothetopofthesiteleavingtheareaforthecontentcolumnandthesidebar.Finally,theiPhoneviewdisplaysthesidebarunderthecontentarea.HarryalsowroteadetailedarticleabouttheCSSstylesheaddedtothestylesheetinhisarticle“Mediaqueries,handierthanyouthink”.AniceexampleofhowacoupleofsimpleCSSadjustmentscanimprovethewebsite’sappearanceacrossvariousdevices.ThislastdesignbyBryanJamesshowsthatresponsiveWebdesignneednotapplyonlytostaticHTMLandCSSwebsites.DoneinFlash,thisonefeaturesafull-sizedbackgroundimageandisflexibleuptoacertainwidthandheight.Asaresultofthedesignstyle,onscreensthataretoosmall,thebackgroundimagegetsmostlyhiddenandthecontentcanbecomeillegibleandsquished.Insteadofjustlettingitbe,though,amessagepopsupinformingtheuserthatthescreenistoosmalltoadequatelyviewthewebsite.Itthenpromptstheusertoswitchtoabiggerscreen.Onecandiscussifthedesignsolutionisgoodorbadintermsofusability,buttheexampleshowsthatFlashwebsitescanrespondtouser'sviewport,too.ConclusionWeareindeedenteringanewageofWebdesignanddevelopment.Fartoomanyoptionsareavailablenow,andtherewillbefartoomanyinthefuturetocontinueadjustingandcreatingcustomsolutionsforeachscreensize,deviceandadvancementintechnology.Weshouldratherstartaneweratoday:creatingwebsitesthatarefuture-readyrightnow.Understandinghowtomakeadesignresponsivetotheuserdoesn’trequiretoomuchlearning,anditcandefinitelybealotlessstressfulandmoreproductivethanlearninghowtodesignandcodeproperlyforeverysingledeviceavailable.ResponsiveWebdesignandthetechniquesdiscussedabovearenotthefinalanswertotheever-changingmobileworld.ResponsiveWebdesignisamereconceptthatwhenimplementedcorrectlycanimprovetheuserexperience,butnotcompletelysolveitforeveryuser,deviceandplatform.Wewillneedtoconstantlyworkwithnewdevices,resolutionsandtechnologiestocontinuallyimprovetheuserexperienceastechnologyevolvesinthecomingyears.Besidessavingusfromfrustration,responsiveWebdesignisalsobestfortheuser.Everycustomsolutionmakesforabetteruserexperience.WithresponsiveWebdesign,wecancreatecustomsolutionsforawiderrangeofusers,onawiderrangeofdevices.Awebsitecanbetailoredaswellforsomeoneonanoldlaptopordeviceasitcanforthevastmajorityofpeopleonthetrendiestgadgetsaround,andlikewiseasmuchforthefewuserswhoownthemostadvancedgadgetsnowandintheyearstocome.ResponsiveWebdesigncreatesagreatcustomexperienceforeveryone.AsWebdesigners,weallstriveforthateverydayoneveryprojectanyway,right?FurtherResourcesforResponsiveWebDesignDesigningforaResponsiveWebwithHeuristicMethods,DesignReviverExamplesOfFlexibleLayoutsWithCSS3MediaQueries,ZoeMickleyGillenwaterTheBigWebShow#9:ResponsiveWebDesign,5by5StudiosHowtoUseCSS3MediaQueriestoCreateaMobileVersionofYourWebsite,SmashingMagazineApplication:RapidPrototypingofAdaptiveCSSandResponsiveDesign,ProtoFluidHandcraftedCSS:MoreBulletproofWebDesign,DanCederholm(printedbook)FlexibleWebBook,ZoeMickleyGillenwater(printedbook)(al)(vf)ExploremoreonCodingCSSResponsiveDesignMediaQueriesSmashingNewsletterTipsonfront-end&UX,deliveredweeklyinyourinbox.Justthethingsyoucanactuallyuse.Front-End&UXWorkshops,OnlineWithpracticaltakeaways,livesessions,videorecordingsandafriendlyQ&A.TypeScriptin50LessonsEverythingTypeScript,withcodewalkthroughsandexamples.Andotherprintedbooks.


請為這篇文章評分?