css layout with flexbox
TRANSCRIPT
-
7/26/2019 Css Layout With Flexbox
1/13
1
CSSLAYOUTWITHFLEXBOX
LayingoutadesignwithCSSisfraughtwithperilofcrossbrowserbugsandmysteriouslycollapsingmargins.But
newtoolslikeflexboxhavetransformedthisonceodioustaskintosomethingyoushouldn'tdread.Bytheendof
thischapteryou'llbecodingupnewlayoutsforyourdesignfasterthanyoucanthinkofthem.
Rememberthoseoldcartoonswiththeroadrunnerandthecoyote?Rocketpropelledrollerskates,bottled
lightning,bundlesofdynamite,magneticbirdseed,razorboomerangs,"super"bombsandgianttrampolines no
technologycouldcatchthebird.EverytoolbackfiredandsentWileE.Coyoteplummetingtohillariousdeath.
UsingCSStolayoutyourdesignisliketryingtocatchtheroadrunnerwithajetpoweredpogostick.Itwon'tend
well.
Nothingismorefrustratingthanwritingapileofcode,refreshingyourbrowserandseeingajumbledmessof
overlappingtextandimages.Youcan'tusetablesbecausetheyaren'tsemantic.Floatsandclearsneverdowhat
youexpect.Justtocentersomethingonthepagerequiresstrangeincantationsofautomarginsortextalign the
centertagisrightout.
Butyouknowwhat?ThisisoldnewsbecauseCSSdoesn'tsuckatlayoutanymore.
Onceyouspendsometimewithflexboxyou'llfeellikeanunstoppablesuperheroofCSS.Yourfooterwillstayat
thebottomofthepagewhereitbelongs.YourLIswillfloweffortlesslyintoneatlittlecolumns.Divswillshrinkand
growandflyindelicateformationsliketheBlueAngels.Imagetagswilldanceandjumpandsingsongsofyour
designprowess.
"Wait,let's
not
get
carried
away"
you
say,
"Flexbox
is
too
new.
You
can't
even
use
it
in
IE9."
Itdoesn'tmatter.Thinkaboutit:howmanybrowsersdoesaPSDworkin?None?Exactly.Asadesigneryou'renot
buildingthefinalversionofthedesign.Youdon'tcareifflexboxdoesn'tworkinOperaMinibecausethecompyou
arecreatingforyourclientonlyneedstoruninChrome.WorryaboutSeaMonkeylater.
DIVINGINTOFLEXBOX
YouonlyneedtoknowahandfulofCSSpropertiestouseflexbox.We'llstartwithanoverviewandgetsome
terminologyoutoftheway.
-
7/26/2019 Css Layout With Flexbox
2/13
2
Everythingstartswiththeflexcontainer.Onceanelementissetasaflexcontaineritschildrenfollowtheflexbox
rulesforlayoutinsteadofthestandardblock,inlineandinlineblockrules.Withinaflexcontaineritemslineupon
the"mainaxis"andthemainaxiscaneitherbehorizontalorverticalsoyoucanarrangeitemsintocolumnsor
rows.
Thereisanotheraxisperpendiculartothemainaxiscalledthecrossaxis.Youcanshiftitemsalongbothaxes.In
theexamples
you've
seen
so
far
they
have
been
centered
but
you
can
also
move
them
to
the
beginning
or
end
of
eitheraxis.
-
7/26/2019 Css Layout With Flexbox
3/13
3
SPACINGAROUNDFLEXITEMS
SHRINKINGAND
GROWING
Youcandefinethesizeofflexitems.Thisletsyoucreatelayoutswith,forexample,acolumnwithafixedwidth
andacolumnthatgrowsorshrinkswiththespaceavailable.
-
7/26/2019 Css Layout With Flexbox
4/13
4
TIMETOLOOKATSOMECODE
I'veavoided
showing
you
code
up
to
this
point
because
the
CSS
property
names
don't
map
well
to
the
very
simple
conceptsbehindflexbox.TohelpyououtI'mintroducingthecodeinascreencastsoyoucanwatchwhathappens
tothelayoutliveasItype.I'vealsocreatedacheatsheetyoucanusewhileyougetusedtotheterminology.
EXAMPLESFROMREALWEBSITES
Flexboxdoesn'tsolveeverylayoutproblembutitcertainlyfixestheworstofthem.Aswelookatafewrealworld
examplesyouwilllearnafewothertechniquesforarrangingelementsonthepagebutflexboxalonewillgetyou
90%ofthewaymostofthetime.
-
7/26/2019 Css Layout With Flexbox
5/13
5
37SIGNALS
You'relookingatthreedivscenteredhorizontallycertainlynotthemostcomplicatedlayoutofalltime.Evenso,
beforeflexbox
creating
this
kind
of
layout
required
some
thought;
centering
elements
on
the
page
was
not
intuitive.
Basecamp
ManageProjects
Usedbymillionsforproductmanagement.
Highrise
ManageContacts
Knowthepeopleyoudobusinesswith.
Campfire
WorkinRealTime
Groupchatroomsforyourbusiness.
-
7/26/2019 Css Layout With Flexbox
6/13
6
THEHTML
NOLAYOUT
YET
ThisishowthemarkuprenderswithjustenoughCSStomakethestylinglookaboutthesame.Youarelookingat
thedefaultbrowserlayoutbeforewe'veappliedanyflexboxrules.Thethreeboxesaredivelements.Divelements
areblockelementsandblockelementsstack,theydon'tflownexttoeachother.
Firstlet'scenteritonthepageandgeteverythingflowingintoarow.
THECSS
.products{
display:flex;
flexflow:row;
justifycontent:center;
}
-
7/26/2019 Css Layout With Flexbox
7/13
7
FIVELINESOFCSSLATER...
Thediv
wrapping
the
product
divs
was
set
to
"display:
flex"
to
make
it
aflex
container.
Then
to
get
its
items
into
a
rowIsettheflexflowpropertyto"row".
Gettingeverythingcenteredwaseasy.Justifycontentlet'syoumoveflexitemsonthemainaxis.Inthiscasethe
mainaxisishorizontalbecausetheflexflowpropertyissetto"row".Whenthemainaxisishorizontal,justify
contentwillmovetheitemstotheleftandright.Ifthemainaxisisvertical,(setflexflowtocolumn),justify
contentmovestheitemsupanddowninsteadofleftandright.Tocentertheproductdivsintheexample
horizontallyIsetjustifycontentto"center".
Thefirstrealworldexampleisalmostdone.Themiddlecontainerneedssomespacearounditandalloftheitems
ineachcontainershouldbecenteredhorizontally.
Tocentertheitemsinthedivit'seasiesttothinkaboutthemasflowinginacolumnandthencenteringthemon
thecrossaxis.Sointhiscasethemainaxisisverticalandthecrossaxisishorizontal.Here'sthecode:
/*
1.Makealloftheproductdivsflexcontainers.
2.Settheiritemstoflowintoacolumn.
3.Centerthemlefttorightbycenteringthem
onthecrossaxisusingalignitems.
*/
.products>div{
display:flex;
flexflow:column;
alignitems:center;
}
/*Usingselectorslikethis
iscoveredinanotherchapter.*/
.products>div:nthchild(2){
margin:02em;
}
-
7/26/2019 Css Layout With Flexbox
8/13
8
ANATOMYOFATWEET
THEHTM
AaronGustafson@AaronGustafson
12h
SmartphoneBrowserlocalStorageisupto5xFasterthanNativeCachemobify.com/blog/smartphon
...
Collapse
Reply
Retweet
Favorite
-
7/26/2019 Css Layout With Flexbox
9/13
9
More
7
RETWEETS
5
FAVORITES
4:35AM 24May13
Replyto@AaronGustafson
-
7/26/2019 Css Layout With Flexbox
10/13
10
NOLAYOUT
PERFECTIS
THE
ENEMY
OF
DONE
Whenconfrontedwithaconfoundinglayoutproblemacommonpitfallistowastetimefindingthe"best"solution.
Assoonasyoufindyourselfponderingthemeritsofchangingthemarkupandworryingaboutmessingupthe
semantics,stopwhatyou'redoingandseeifabsolutepositioningwouldwork.
Wheneveryou'rethinkingabouttechnicaldecisionsyou'renotthinkingaboutdesign.Remember,yourjobisto
createacomp,notthefinalsite.Thecodeyouarewritingwillbereworkedandrewrittensodon'tspendanytime
makingitperfect perfectistheenemyofdone.
Thefirstchallengewiththetweetistheuserprofileimageandthedatetag.Althoughnotobviousinthisexample
thetweet
text
flows
under
the
date
and
the
profile
image
seems
to
have
its
own
column.
The
way
the
markup
was
writtendoesnotmakeaflexboxlayoutimmediatelyobvious.WhenIputthisexampletogetherIwastedafew
minutesthinkingaboutwaysIcouldchangethemarkupandgetthelayoutIwanted,butthenIcaughtmyselfand
justabsolutelypositionedbothelementswhereIwantedthem.
THECSS
/*createthespaceontheleftfortheprofileimage*/
.tweet.content,
-
7/26/2019 Css Layout With Flexbox
11/13
11
.tweet.reply{
paddingleft:70px;
}
/*movetheimagetotheleftintothecolumn*/
.content>img{
position:absolute;
marginleft:60px;
}
/*
Movethetimestampupandtotheright
Iuse"em"insteadofpixelshere,butpixels
arejustfine.
*/
.content>time:first
of
type{
position:absolute;
margintop:1.5em;
marginleft:30em;
}
/*Iaddedsomeverticalpaddingtoall
oftheelementsinthecontentdiv.
*/
.content>*{
padding:.25em0;
}
ABSOLUTELYPOSITIONEDTWOELEMENTS
-
7/26/2019 Css Layout With Flexbox
12/13
12
Thenextstepistotaketheactions,(e.g.collapse,reply,retweet,etc.),theretweetsandfavoritesandthelistof
smallprofilepicturesandputthemintorowsinsteadofcolumns.
ADASHOFFLEXBOX
.actions,li.people,.meta,.people>ul{
display:flex;
}
ALMOSTDONE
Elementsincontainersarearrangedintorowsbydefaultsoyoujustneedtosetthecontainertodisplay:flex.
You'llnoticeintherealtweetthenumbersareontopof"favorites"and"retweets".Therearetwowaystodothis.
Thefirstistotreatthemlikeflexcontainersandputthemintoacolumn.Thesecondwayistomakeeachofthe
spanswrappingthenumbersintoablockelementinsteadofinline.
Thesecondwayisonlyobviousifyouknowthatblockelementsstack.Thebeautyofflexboxisyoudon'tneedto
knowtheinsandoutsofblock,inlineorinlineblockelements.Learnthebasicsbutdon'twastetimeuseflexbox
whenit'snotobvious.
STACKTHEELEMENTS
.meta.retweets,
.meta.favorites{
display:flex;
flexflow:column;
}
-
7/26/2019 Css Layout With Flexbox
13/13
13
FINISHED
TIPSANDTRICKS
o Whenabsolutelypositioninganelementusemarginsinsteadoftop,left,right,bottom.Elementsabsolutelypositionedwith
marginsaremoreconsistentacrossdifferentscreenresolutions.
o Useemsinsteadofpixels.Emsadjustwhenyouchangefontsize.Ifyouincreasedthebasefontsizeinthisexamplethedate
wouldmaintainitsposition.
o Usepaddinginsteadofmarginforspacing.Spacescreatedwithmarginsometimescollapseintoeachotherinsteadofstacking.
Sometimesyouwantthisbutmostofthetimeit'snothelpful.Paddingdoesn'tcollapsesoit'smorepredictablethanusing
margins.
o Usetheuniversalselector,*,withoutfear.Experiencedwebdevelopersavoidtheuniversalselectorforperformancereasons.
Youshouldn'tspendanytimethinkingaboutthis.Thereareperformanceissuesbutnothingtoworryaboutwhencreatingthe
initialdesign.
o Thekeytocreatingmorecomplicatedlayoutswithflexboxistobreakitintopieces.Don'tbeafraidtomakeeverythingaflex
containerifthat'swhatworksforyou.