Fluid Grids An A List Apart Article
Fluid Grids An A List Apart Article
Fluid Grids An A List Apart Article
279
IllustrationbyKevinCornell
FluidGrids
byEthanMarcotteMarch03,2009
PublishedinCSS,HTML,GraphicDesign,Layout&Grids,ResponsiveDesign
Earlylastyear,Iworkedontheredesignofarathercontentheavywebsite
(http://www.w3.org/QA/2008/06/about_the_love_w3org_redesign.html).Design
requirementswerefairlylight:theclientaskedustokeeptheorganizationsexistinglogoandto
improvethedensetypographyandincreaselegibility.So,earlyoninthedesignprocess,wespenta
sizableamountoftimeplanningawelldefinedgridforalibraryofcontentmodules.
Overthepastfewyears,thissortofthinkinghasbecomemorecommon.Thankstotheadvocacyof
MarkBoulton(http://www.markboulton.co.uk/),KhoiVinh
(http://subtraction.com/2007/03/18/ohyeeaahh),andothers,weveseenaresurgenceofinterest
inthetypographicgrid,andhowtouseitontheweb.Andfrankly,theideasbeenasmashhit:a
(http://960.gs/)million(http://www.blueprintcss.org/)CSS
(http://developer.yahoo.com/yui/grids/)frameworks(http://csswizardry.com/typogridphy/)
havebloomed,withsundry(http://www.puidokas.com/portfolio/gridfox/)tools
(http://developer.yahoo.com/yui/grids/builder/)tocomplementthem,eachbuilttomakegrid
baseddesignevenmoreaccessibletotheaveragedesigner.Andwhynot?Afterafewminutesof
griddythinking,thebenefitsbecomeclear:designersgainarational,structuredframeworkfor
organizingcontentandusersgainwellorganized,legiblesites.
However,ourclienthadonelast,heartstoppingrequirement:thedesignhadtobefluidandresize
withthebrowserwindow.Normally,thiswouldcausemetorejoicebothnoisilyand
embarrassingly.Fluidlayoutsareanundervaluedcommodityinwebdesign.Theyputcontrolof
ourdesignsfirmlyinthehandsofourusers(http://www.alistapart.com/articles/dao/)andtheir
browsinghabits.Theyvealsoutterlyfailedtoseizetheimaginationofwebdesigners.
Minimumscreenresolution:alittlewhitelie
Insteadofexploringthebenefitsofflexiblewebdesign,werelyonalittlewhitelie:minimum
screenresolution.Thesethreewordscontainapowerfulmagic,underthecoverofwhichwechurn
outfixedwidthlayoutafterfixedwidthlayout,perhapsrevisitingadesigneveryfewyearsto
bumpupthewidthonceitsjudgedsafeenoughtodoso.Minimumscreenresolutionletsus
designforacontrivedsubsetofuserswhoseeourdesignasgodandPhotoshopintended.These
usersalwaysbrowsewithamaximized1024768window,andareneverrunning,say,anOLPC
laptop(http://laptop.org/en/laptop/),orlookingatthewebwithamonitorthatsmorethanfour
yearsold.Ifauserdoesntmeettherequirementsofminimumscreenresolution,well,then,its
thescrollbarforthem,isntit?
Ofcourse,whenIwascodingthesite,Ididnthavetheluxuryofwritingadiatribeontheevilsof
fixedwidthdesign.Instead,Iwasleftwithasoberingfact:whileweddesignedarathercomplex
gridtoservetheclientscontentneeds,theclientandbyextension,theclientsuserswasasking
forafluidlayout.AsalmostallofthegridbaseddesignsIcouldlistoffatthattimewererigidly
fixedwidth,Iwasleftwithapricklyquestion:howdoyoucreateafluidgrid?
Asitturnsout,itssimplyamatterofcontext.
DoIreallyhavetothankIEforthis?
Facedwithaninsurmountableproblem,IdidwhatIdobest:avoiditaltogether.Temporarily
puttingasidethequestionofhowtogetagridtobehaveinanonfixedlayout,IcodedthestuffI
knew:stylesfirstforcolorandbackgrounds,andthenforsettingthetype.
YoumayalreadyknowaboutInternetExplorerswelldocumentedproblemwithresizingfontsset
inpixelsorrather,itsutterrefusaltodoso
(http://www.simplebits.com/notebook/2008/03/25/ie8.html).Setaparagraphin16pxGeorgia,
andnomatterhowmuchtheusertriestoincreaseordecreasethesizeofthetext,itremainsat
16pxinIE.IE7andonwarddoallowtheusertoscaletheentirepage,butsimpleresizingofpx
basedfontsisstilllargelyverboteninInternetExplorer.Sotogiveourusersthemostflexibility,we
standardssavvydesignershaveusuallyoptedtosidestepthepixelentirely,andhavetakentosizing
typewithrelativeunits,betheykeywords(http://www.w3.org/TR/CSS21/fonts.html#valuedef
absolutesize),percentages(http://www.w3.org/TR/CSS21/syndata.html#valuedef
percentage),ormypersonalfavorite,ems
(http://www.alistapart.com/articles/howtosizetextincss/).
Ifyouveeverworkedwithrelativeunits(http://www.w3.org/TR/CSS21/syndata.html#length
units)suchastheem,youknowthatitsallaboutcontext:inotherwords,theactualsizeofan
elementsemiscomputedrelativetothe fontsize ofitsparentelement.Forexample,letssay
wereworkingfromthefollowingdesigncomp:
Anexampleofsomebasictextsizedusingpixels.
Nothingfancy:someparagraphssetin16pxHelvetica,anunorderedlistthatsbeenslightly
downsizedto14px,andan h1 atthetopin24pxGeorgia.Sexy,no?
Whatsdoublysexyisthatonesimpleruleallowsustogetmostofthisinplace
(/d/fluidgrids/examples/type/initial.html):
body{
font:normal100%Helvetica,Arial,sansserif;
}
targetcontext=result
2416=1.5
Sotheheaderis1.5timesthedefaultbodysize,or1.5em,whichwecanplugdirectlyintoour
stylesheet.
h1{
fontfamily:Georgia,serif;
fontsize:1.5em;/*24px/16px=1.5em*/
}
Tosizethelisttotheemequivalentof14px,wecanusethesameformula.Assumingagainthatthe
body s fontsize isroughly16px,wesimplydividethattargetbythecontext:
1416=0.875
Andwereleftwithavalueof0.875em,whichwecanagaindropintoourCSS.
ul{
fontsize:0.875em;/*14px/16px=0.875em
*/
}
Withthosetworules,oursamplepage(/d/fluidgrids/examples/type/sizes.html)islookingalot
closertothecomp,andwillbepracticallypixelperfectaftersomeslightcleanup
(/d/fluidgrids/examples/type/polished.html).Allwiththehelpofour targetcontext=
result formula.
Soafterafewhoursspentcleaninguprelativetypestylingforourclient,IrealizedIdstumbled
upontheanswer.Ifwecouldtreatfontsizesnotaspixels,butasproportionsmeasuredagainst
theircontainer,wecoulddothesamewiththedifferentelementsdrapedacrossourgrid.
Afterall,itsnotTheGoldenPixel
Asbefore,letsstartwithafairlyunsexystraightforwardlayout:
Ourbasicpagelayout.(/d/fluidgrids/img/compfull.gif)
Sure,ourdesign(/d/fluidgrids/img/compfull.gif)isprettymodest.Butthosesimplestylesare
drapedoverawelldefinedgrid(/d/fluidgrids/img/compgrid.gif):namely,sevencolumnsof
124pxeach,separatedby20pxwidegutters,allofwhichtotalsuptoawidthof988px.Buthey,
letsforgetaboutthosenastypixels.Proportionsarethenewblack,right?Letsgetfluid,baby.
Ourbasicpage,withthegridoverlaiduponit.(/d/fluidgrids/img/compgrid.gif)
Tostart,letstreatourcomplikeanyother,fixedorfluid:beforewestartcoding,letslookatthe
design,andassessthedifferentcontentareas(/d/fluidgrids/img/compareas.gif).Thankfully,its
aprettyshortinventory.
Definingourdifferentcontentareas.(/d/fluidgrids/img/compareas.gif)
Onthehighestlevel(/d/fluidgrids/img/compareas.gif),wevegotatitleatthetop,acontentarea
thatspreadsacrosssixcolumns,andsomecontextualinformationintheleftmostcolumn.From
thisdiagram,wecanfleshoutsomeskeletonmarkupthatkeysintoourcontentinventory,both
structurallyandsemantically:
<divid="page">
<h1>TheRatioRevolutionWillNotBeTelevised</h1>
<divclass="entry">
<h2>AnyoneelsetiredofHelvetica?</h2>
<h3class="info">A<ahref="#">Blog</a>Entry:</h3>
<divclass="content">
<divclass="main">
<p>Maincontentgoeshere.Loremipsum
etc.,etc.</p>
</div><!/end.content>
<divclass="meta">
<p>Postedonetc.,etc.</p>
</div><!/end.meta>
</div><!/end.main>
</div><!/end.entry>
</div><!/end#page>
Andwithsometyperulesapplied,wevegotarespectablelookingstartingpoint
(/d/fluidgrids/examples/grid/initial.html).However,the #page containerdoesnthaveany
constraintsonit,soourcontentwillsimplyreflowtomatchthewidthofthebrowserwindow.Lets
trytoreininthoselonglinelengthsabit:
#page{
margin:40pxauto;
padding:01em;
maxwidth:61.75em;/*988px/16px=61.75em
*/
}
Weveusedmarginsandpaddingtoventilateourdesign
(/d/fluidgrids/examples/grid/bounded.html)abit,andestablishagutterbetweenitandthe
windowedges.Butinthelastlineofourrule,wereusingavariantofour fontsize formulato
definethemaximumwidthofourdesign.Bydividingthecompswidthof988pxbyourbase font
size of16px,wecanseta maxwidth inemstoapproximatethepixelbasedwidthfromour
mockup,whichwillpreventthepagefromexceedingouridealof988px.Butsinceweveusedems
tosetthisupperlimit,the maxwidth willscaleupastheuserincreasesherbrowserstextsizea
niftylittletrickthatevenworksinolderversionsofInternetExplorer,ifasmallCSSpatch
(http://www.cameronmoll.com/archives/000892.html)isapplied.
Sowithourdesignproperlycordonedoff,letsbeginworkingoneachelementinourdesign
inventory,beginningwiththepagestitle.Inthecomp,itspansfivecolumnsandtheirfourgutters,
withatotalwidthof700px.Itsalsoremovedfromthelefthandedgeofthepagebyone
column/gutterpair,makingforanice144pxoffset.Andifwewereworkinginafixedwidthdesign,
ourjobwouldbeprettystraightforward:
h1{
marginleft:144px;
width:700px;
}
Sincewereworkinginafluidcontext,though,fixedmeasurementsdontquitecutit.AndasIwas
workingonrelativefontsizing,thatswhenithitme:everyaspectofthegridandtheelementslaid
uponitcanbeexpressedasaproportionrelativetoitscontainer.Inotherwords,asinourtype
resizingexercise,werelookingnotjustatthedesiredsizeoftheelement,butalsoatthe
relationshipofthatsizetotheelementscontainer.Thiswillallowustoconvertour
designspixelbasedwidthsintopercentages,andkeeptheproportionsofourgridintactasit
resizes.
Inshort,wellhaveafluidgrid.
Everythingoldisnewagain
So,howdowebegin?
targetcontext=result
Thatsright:itsthereturnofourtrustytypeformula.Wecanusethesameproportionalanalysisto
transformpixelbasedcolumnwidthsintopercentagebased,flexiblemeasurements.Sowere
workingfromatargetvalueof700pxforthepagestitlebutitscontainedwithinadesignedwidth
of988px.
Convertingourpixelbasedtitletopercentages.
Asaresult,wesimplydivide700px(thetarget)by988px(thecontext)likeso:
700988=0.7085
h1{
width:70.85%;/*700px/988px=0.7085
*/
}
Canwedothesamewithourtargetmarginof144px?Oh,Idosolovealeadingquestion:
144988=0.14575
Onceagain,wecantakethat0.14575,or14.575%,andaddthatdirectlytoourstyleruleasavalue
forthetitles marginleft :
h1{
marginleft:14.575%;/*144px/988px=0.14575
*/
width:70.85%;/*700px/988px=0.7085
*/
}
Andvoil(/d/fluidgrids/examples/grid/header.html).Bymeasuringthetitlesmarginandwidth
inrelationtoitscontainer,wevesuccessfullytranslatedtheratiosfromourgridintoCSSfriendly
percentages.Thetitlesproportionswillalwaysremainintact,evenasitreflowstofitthesizeofthe
browserwindow.
Wecanevenperformthesamesimpledivisiontowrapupthelayoutfortheentryitself,sizedat
844pxinourcomp,withsome124pxwidemarginaliatotheleftofit.Fortheentry:
844988=0.85425
Andfortheinformationalcolumn:
124988=0.12551
Thesetwoquickdivisionsnetussomepercentagesthatwecandropintoourstylesheet,fleshing
outourlayoutevenmore:
.entryh2,
.entry.content{
float:right;
width:85.425%;/*844px/988px=0.85425
*/
}.entry.info{
float:left;
width:12.551%;/*124px/988px=0.12551
*/
}
}
Andwiththat,ourfluidgridshapesupabitfurther(/d/fluidgrids/examples/grid/entry.html).
Changingthecontext
Sofarwevegotthebigcontentareassorted,butweveyettotouchtheinnerarea.Currently,the
blogentrysmaincopyanditscontextualinfooccupythefullwidthoftheentry,andarestackedon
topofeachother.Butinourinitialcomp(/d/fluidgrids/img/compfull.gif),themaincopyinside
theblogentryonlyspannedfivecolumns,withtheancillaryinfoslottedneatlyintotherightmost
column.
Sharpreaderswillhavenoticedthat,asitscurrentlydesigned,theentrysbodyisthesamewidth
asthepagestitle(700px),andthemarginaliaisthesamewidthastheleftmostcolumnwestyled
earlier(124px).Sowhilewereworkingwithsomedimensionswevepreviouslycalculated,wecant
reusethesameformulas:thecontexthaschanged.
Sincewereworkinginsideanewcontainer,weneedtouseitswidthasourcontext.
700844=0.82938
Andforour124pxwidecolumnontheright,wecanusethesamereferencepoint:
124844=0.14692
Wecannowtakeeachofthesemeasurements,andplugthemintoourCSS:
.entry.main{
float:left;
width:82.938%;/*700px/844px=0.82938
*/
}.entry.meta{
float:right;
width:14.692%;/*124px/844px=0.14692
*/
}
Andwiththatwevefinishedourwork,ourfluidgridcomplete
(/d/fluidgrids/examples/grid/final.html).
Anoteonrounding
AsyoumayguessfromthelackofCSSpatchesabove,Ivehadveryfewcrossbrowserissueswith
thistechnique.IwouldhighlyrecommendJohnResigsexcellentarticleonSubPixelProblemsin
CSS(http://ejohn.org/blog/subpixelproblemsincss/).Itexplainshowdifferentbrowsers
handlepercentagebasedwidths,andthemechanicsbywhichtheyreconcilesubpixel
measurements.
AsJohnexplainsinhisarticle,ifmodernbrowsersarepresentedwithfour25%wideelements
withina50pxwidecontainer,theycantactuallyrendertheelementsat12.5pxinstead,mostwill
roundthecolumnsdownorupasbestfitsthelayout.InternetExplorer,asithappens,willsimply
roundallofthosesubpixelvaluesup,whichbreakslayouts.
Ifyoureworkingwithsufficientlygenerousmarginsinyourgrid,thisshouldntbeanissue.Butif
IEcausesunduewrappingwithyourpercentagebasedcolumns,reducingthetargetvaluebyone
pixelcanhelp.Soif,forexample,ourlefthandmarginaliawastoowideforIE(InternetExplorer),
youmightchangeyourcalculationfrom:
124988=0.12551
toalowertargetof123px:
123988=0.12449
Agridforallseasons
Theaboveis,ofcourse,astartingpoint:therearemyriadotherchallengesthatfacetheliquidweb
Theaboveis,ofcourse,astartingpoint:therearemyriadotherchallengesthatfacetheliquidweb
designer,mostofwhicharisewhenyouintroducefixedcontent(suchasimages,Flash,andso
forth)intoafluidframework.Ivebeenexperimentingwithafewpossiblesolutionsonmyblog
(http://unstoppablerobotninja.com/),butother,betterworkaroundsarestilloutthere.
Andfinally,Idontpretendthatdesigniseasy,whetheritsfixedorfluid.Butgivenallthatweve
achievedoverthepastfewyearsmovingpasttables,evangelizingstandardsinourcompaniesand
inoursharedindustry,demandingbetterstandardsofourbrowsersandourpeersIdowishwed
bendsomeofthatingenuitytobreakoutofourrelianceonminimumscreenresolution.Afterall,
ourusersbrowsinghabitsarentasfixedasourcompswouldsuggest.Ihopethepromiseoffluid
gridshasfiredyourimagination,andImexcitedtoseehowyouimproveonthetechnique.Our
userswillbe,too.
Additionalreading
Asyoumayhavegatheredfrommyintroductorycrazedrantdigression,twopassionsofmineare
fluidwebdesignand,morerecently,theimportanceofawellconsideredgrid.Bothofthesehave
beenfueledbythefollowing,thoughthisisntanexhaustivelist:
JohnAllsopp,ADaoofWebDesign(http://www.alistapart.com/articles/dao/)
MarkBoulton,Feelingyourwayaroundgrids(http://www.markboulton.co.uk/)
DavidEmery,MoreWidth(http://deonline.co.uk/2006/11/27/morewidth)
MollyHolzschlag,ThinkingOutsidetheGrid
(http://www.alistapart.com/articles/outsidethegrid)
JeremyKeith,Theunpushedenvelope(http://adactio.com/journal/1149)
JeffreyZeldman,Rulesbaseddesign(http://www.zeldman.com/daily/0403b.shtml#ap3003)
Andfinally,attheendofatalkIgavelastAugustondesigningforfluidgrids,someonepointedout
theFluid960GridSystem(http://www.designinfluences.com/fluid960gs/).Ifyoureusinga
publicCSSframeworksuchas960GridSystem(http://960.gs/)already,thefluidportmightbe
ofinteresttoyou.
AbouttheAuthor
EthanMarcotte
EthanMarcotteisanindependentwebdesignerwhocaresdeeplyaboutbeautifuldesign,
elegantcode,andtheintersectionofthetwo.Overtheyears,hisclientelehasincluded
NewYorkMagazine,theSundanceFilmFestival,TheBostonGlobe,andPeople
Magazine.EthancanbefoundonTwitteroronhislongneglectedblog,andhismost
recentbookisResponsiveWebDesign.
MOREFROMTHISAUTHOR
WhereOurStandardsWentWrong
(/article/whereourstandardswentwrong),Frameworks
(/article/frameworks),FluidImages(/article/fluidimages),Responsive
WebDesign(/article/responsivewebdesign)
ISSN15340295Copyright19982016AListApart&OurAuthors