unraveling flexbox - amazon s3 · chapter 11: ordering the order of the elements on your screen...

52
The ultimate guide to building modern CSS layouts with exbox UNRAVELING FLEXBOX Landon Schropp

Upload: others

Post on 19-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

The ultimate guide to building modern CSS layouts with flexbox

UNRAVELING

FLEXBOX

Landon Schropp

Page 2: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

SampleVersion1.3

Copyright©2016LandonSchroppLLC

AllRightsReserved

ThisisasampleofUnravelingFlexbox.Thefullversionis

availableforpurchaseatunravelingflexbox.com.

Page 3: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

INTRODUCTION

Page 4: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

HaveyoueverspenthoursagonizingoveraCSSlayoutthat

justwouldn'twork?Haveyoustruggledwithcolumns,

verticalcentering,floatsorinlinedisplays?Haveyoueven,

gasp,givenupandusedtablesforyourlayouts?

It’stimetosaygoodbyetoallthatpain.FlexboxisaCSS

layoutspecificationthatmakesiteasytoconstructdynamic

layouts.It'sasetoftoolsthatgivesyoumoreflexibilityand

powerwithCSSthanyou'veeverhadbefore.Withflexbox,

verticalcentering,same-heightcolumns,reordering,and

directionagnosticismareapieceofcake.

There'sapopularmythfloatingaroundthatflexboxisn't

readyforprimetimeyet.Wrong!93%ofpeoplearenow

runningabrowserthatsupportsflexbox,andthat

numberisgrowingeveryday.That'sbetterthanthe

supportfortheHTML5<video>element!Youcanuse

flexboxtodayanditwillworkalmosteverywhere!

Thisbookisyourguidetomasteringflexbox.Itwillteach

youtheinsandoutsofallthepropertiesandhowthey

interacttogether.Moreimportantly,itwillshowyouhowto

applythemtoreallayouts.

Page 5: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

What'sintheBook?

Thisbookisaboutteachingyoutouseflexboxinthereal

world.TheexamplesineachchapterareastruetolifeasI

couldmakethem.ManyofthemarelayoutsI'vepreviously

builtforpayingclients.Youcanusewhatyoulearnhere

directlyinyourprojects.

Here'sthebreakdown:

Chapter1:GettingDicey

Inthischapter,you'llbuildyourveryfirstlayout,thefacesof

dice!

Chapter2:CraftingTwelve-ColumnLayouts

Learnhowyoucanuseflexboxtobuildtwelve-column

layoutsyou'vealwaysneededagridsystemforinthepast.

Chapter3:BuildingaVideoPlayer

Buildavideoplayerwithflexboxthat'llmakeYouTube's

developersjealous.

Chapter4:SayGoodbyetoVendorPrefixes

I’llshowyouhowtosetupyourenvironmentsoyoucan

ignoreallvendorprefixes.You’llwriteyourcodeonce,andit

willworkeverywhere!

Page 6: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Chapter5:BreakingFreeFromTwelve-Column

Layouts

You'llgobeyondtwelve-columnsandbuildacoolcalendar

layoutintheprocess.

Chapter6:PerfectPricing

Createapricinglayoutthatwillfeelrightathomeonany

marketingsite.

Chapter7:FlexboxForms

Flexboxisn'tjustforfull-pagelayouts!Inthischapter,you'll

learnhowtouseflexboxtobuildsmall,reusableform

controls.

Chapter8:ResponsiveDesign

Learnhowtoharnessflexboxforresponsivelayoutsthat

workgreatonbothdesktopandmobile.

Chapter9:WrappingLikeaBoss

Saygoodbyetofloatsandclearfixes.You'llbeusingflexbox's

fantasticwrappingcontrolsfromnowon.

Chapter10:ProgressiveEnhancement

You'lllearnhowtotakeadvantageoftheflexboxgoodness

andstillsupportInternetExplorer9andbelow!

Page 7: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Chapter11:Ordering

Theorderoftheelementsonyourscreendoesn'thaveto

matchtheorderintheHTML.Thischapterwillshowyou

howtoreordertheseelementswithflexbox.

Chapter12:Cross-BrowserTesting

You'lllearnhowtotestyourcodeacrosseverymajorbrowser

anddevice.

Chapter13:HowtoWriteaGridSystem

Haveyoueverwonderedhowgridsystemslike960gswork?

Inthischapteryou'llcreateyourveryownflexboxgrid

system.

Chapter14:Minesweeper

You'lluseeverythingyou'velearnedinthisbooktobuildan

awesomeMinesweeperlayout!

Whenabookcontainstoomanydetails,it'sdifficulttocatch

theimportantpoints.InthisbookI'veomittedstylesthat

don'tapplytoflexbox,suchastypography,colorsand

borders.Ifyou'dliketoseeallofthestylesforachapter,

takealookatthecodeexamples.

Page 8: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

CodeExamples

TheexamplesforthisbookarepoweredbyMiddleman,a

staticsitegeneratorthatmakesiteasytobuildHTMLand

CSSwebsites.Thereareseveralwaysforyoutoaccessthe

examplecode:

Thelastoptionistrickierthanthefirstthree,soI'donly

recommenditifyou'refeelingambitious.Ifyou'reaMac

user,I'verecordedavideotomaketheinstallationprocess

easierforyou.Ifyou'reaWindowsuser,there'scurrentlya

buginMiddlemanpreventingyoufromrunningthe

examples.

Thefirststepistoinstalltheproject'sdependencies:

ViewthesourceonGitHub.•

Downloadthecompiledbuild.•

Browsethehostedexamples.•

Runtheexampleserveryourself.•

Ruby•

Git•

NodeJS•

Bundler•

Page 9: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Next,clonetheproject'sGitrepositoryandswitchintothat

directory.

gitclone"https://github.com/"\

"LandonSchropp/unraveling_flexbox"

cdunraveling_flexbox

UseBundlertoinstalltheproject'sgemdependencies.

bundleinstall

Finally,startuptheMiddlemanserver.

bundleexecmiddleman

Ifeverything'ssetupcorrectly,youcannavigateto

http://localhost:4567toviewtheexamples.

Acknowledgements

I'dliketothankmywife,Danielle,forallhersupportin

writingthisbook.I'vespenttoomanyeveningshunched

overmycomputerinsteadofhangingoutwithher.Notonly

didshetoleratemyinsanity,butshegavealargeportionof

herowntimetoeditingthisbook.LoveyouDanielle!

Page 10: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

I'dalsoliketothankmybetareaders,especiallyJoshua,

Darrin,Andrew,DucandChristine.Youguysmadeahuge

differenceinthequalityofthisbook,andIreallyappreciate

it!

EnoughChitchat

Let'sdivein.WelcometoUnravelingFlexbox!

Page 11: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

CHAPTER 1

Getting Dicey

Page 12: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Thesixdicefaces

Thebestwaytolearnflexboxistorollupyoursleevesand

writesomecode.Inthischapter,I’llwalkyouthroughyour

veryfirstflexboxlayout:thefacesofdice!

TheFirstFace

Astandardplayingdieconsistsofsixfaces(sides).Eachface

hasanumberofpips(dots)whichdeterminethevalueofthe

side.Thefirstsideconsistsofasinglepipinthecenterofthe

face.

Let'sstartbywritingtheHTMLforthefirstface.

<divclass="first-face">

<spanclass="pip"></span>

</div>

Page 13: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Tomakelifealittleeasier,I’veaddedthebasicstylesforthe

facesandthepips.Here'swhatitlookslike:

Thefirststepistotellthebrowsertomakethefaceaflexbox

container.

.first-face{

display:flex;

}

Itdoesn'tlookanydifferent,butthere'salotgoingonunder

thehood.

Page 14: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Theflexboxcontainer'smainaxisandcrossaxis

Thefirst-facecontainernowhasahorizontalmainaxis.

Themainaxisofaflexcontainercanbehorizontalor

vertical.Thedefaultishorizontal.Ifweaddedanotherpipto

theface,itwouldshowuptotherightofthefirstone.The

containeralsohasaverticalcrossaxis.Thecrossaxisis

alwaysperpendiculartothemainaxis.

Thejustify-contentpropertydefinesthealignmentalong

themainaxis.Sincewewanttocenterthepipalongthe

mainaxis,we'llusethecentervalue.

.first-face{

display:flex;

justify-content:center;

}

Page 15: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Allright!Sincethemainaxisishorizontal,thepipisnow

centeredintheparentelement.

Thealign-itemspropertydictateshowtheitemsarelaid

outalongthecrossaxis.Becausewewantthepiptocenter

alongthisaxis,usethecentervalueheretoo.

.first-face{

display:flex;

justify-content:center;

align-items:center;

}

Page 16: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Andjustlikethat,thepipiscentered!Horizontallyand

Verticallycenteringanelementwasoneofthehardesttricks

toaccomplishinCSSbeforeflexbox,andyou'vedoneitina

fewlinesofcode!

GettingTrickier

Onthesecondfaceofadie,thefirstpipisinthetopleft

cornerandthesecondisinthebottomright.That'salso

prettyeasytodowithflexbox!

Again,startwiththemarkupandthebasicCSS.

<divclass="second-face">

<spanclass="pip"></span>

<spanclass="pip"></span>

</div>

.second-face{

display:flex;

}

Page 17: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Nowyouhavetwopipsrightnexttoeachother.Thistime

around,thepipsshouldbeonoppositesidesoftheface.

There'savalueforjustify-contentthatwillletusdojust

that:space-between.

Thespace-betweenvalueevenlyfillsthespacebetweenflex

items.Sincethereareonlytwopips,thispushesthemaway

fromeachother.

.second-face{

display:flex;

justify-content:space-between;

}

Page 18: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Here'swherewerunintoaproblem.Unlikebefore,youcan't

setalign-itemsbecauseitwillaffectbothpips.Luckily,

flexboxincludesalign-self.Thishandypropertyletsyou

alignindividualitemsinaflexcontaineralongthecross

axis!Thevalueyouwantforthispropertyisflex-end.

.second-face{

display:flex;

justify-content:space-between;

}

.second-face.pip:nth-of-type(2){

align-self:flex-end;

}

Page 19: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Looksgood!

HorizontalandVerticalNesting

Let'sskipthethirdfaceandtacklethefourth.Thisoneisa

littletrickierthantheothersbecauseweneedtosupporttwo

columns,eachwithtwopips.

Therearetwothingsaboutflexboxthatwillsaveyouhere:

flexcontainerscanhaveverticalorhorizontalcontent,and

flexcontainerscanbenested.

Unlikebefore,themarkupwillnowincludecolumns.

Page 20: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

<divclass="fourth-face">

<divclass="column">

<spanclass="pip"></span>

<spanclass="pip"></span>

</div>

<divclass="column">

<spanclass="pip"></span>

<spanclass="pip"></span>

</div>

</div>

Sinceyouwantthetwocolumnstobeonoppositesides,go

aheadandusejustify-content:space-betweenlikeyou

didbefore.

.fourth-face{

display:flex;

justify-content:space-between;

}

Page 21: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Next,youneedtomakethecolumnsflexcontainers.Itmight

seemliketheyalreadyare,butrememberthatyouhaven't

setdisplay:flexyet.Youcanusetheflex-direction

propertytotosetthedirectionofthemainaxistocolumn.

.fourth-face{

display:flex;

justify-content:space-between;

}

.fourth-face.column{

display:flex;

flex-direction:column;

}

Page 22: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Itdoesn'tlookanydifferent,butthecolumnsarenowflex

containers.Noticehowyoustuckaflexcontainerdirectly

insideanotherflexcontainer?That'sokay!Flexboxdoesn't

careifthecontainersarenested.

Thefinalstepistospacethepipsapartfromeachother.

Sincethemainaxisforthecolumnsisvertical,youcanuse

justify-contentagain.

.fourth-face{

display:flex;

justify-content:space-between;

}

.fourth-face.column{

display:flex;

flex-direction:column;

justify-content:space-between;

}

Page 23: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Note:Thisfacecouldhavebeenbuiltwithoutcolumnsbyusing

wrapping.I'llcoverwrappinginmoredetailinChapter9.

WrappingUp

Woohoo!Threefacesdownandthreetogo.Atthispoint,

youhaveeverythingyouneedtobuildtheotherthree.Give

itashot!Whenyou'redone,takealookatthecodeexamples

fortheanswers.

Page 24: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

CHAPTER 2

Crafting Twelve-Column Layouts

Page 25: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Inatwelve-columnlayout,thepageisbrokenapartinto

twelveinvisiblecolumns.Thesecolumnshavesmall

amountsofspacebetweenthem,calledgutters.Thepageis

dividedintorows,andthecontainersintherowstakeupa

certainnumberofcolumns.

Atwelve-columngridwithcolumnsandgutters

Ifyoulookforthem,you'llstarttoseetwelve-column

layoutseverywhere.Takealookattheselandingpagesfrom

Heroku,ChowNowandSquare.Noticehowthesectionsare

brokenupintohalves,thirdsandfourths?

Inthischapter,I'llshowyouhowtousetheflex-grow,

flex-shrinkandflex-basispropertiestobuildtwelve-

columnlayouts,withouttheneedforalibrary!

Page 26: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Examplesoftwelve-columnlayoutsfromHeroku,ChowNowandSquare

SettingUptheContainer

Let'ssayyouwanteachofthe<div>elementsinthe

followingHTMLtotakeupathirdofthe<section>.

<section>

<divclass="column">First</div>

<divclass="column">Second</div>

<divclass="column">Third</div>

</section>

Page 27: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Bydefault,the<section>elementtakesup100%ofthe

widthofthescreen.Startbylimitingitswidthto740pixels.

Whileyou'reatit,alsoaddguttersaroundthecolumns.

section{

max-width:740px;

margin:0auto;

}

.column{

margin:10px;

}

Popopenthecodeexamplesandtrydraggingyourbrowser

windowuntilit'ssmallerthan740pixels.Noticehowthe

<section>getssmallerasthescreenshrinks,butstaysfixed

whenthescreenislargerthan740pixels?

Page 28: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Flexin'ItUp

Makethe<section>aflexcontainerlikeyoudidin

Chapter1.

section{

max-width:740px;

margin:0auto;

display:flex;

}

Bydefault,flexboxsetsthewidthsofthecolumnstothesize

oftheircontent.Youcanchangethisbehaviorbyusingthe

flex-growandflex-shrinkproperties.

Theflex-growpropertytellsflexboxhowtogrowtheitem

totakeupadditionalspace,ifnecessary.flex-shrinktells

flexboxhowtoshrinkwhennecessary.Sincewewantthe

columnstobehavethesamewhilegrowingandshrinking,

setbothofthesepropertiesto1.

Page 29: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

.column{

margin:10px;

flex-grow:1;

flex-shrink:1;

}

Woohoo!Theflexboxcontainernowfillsupthreecolumns.

Thevaluesforflex-growandflex-shrinkareproportional,

meaningtheychangerelativetootheritemsintheflex

container.Flexboxaddsthevaluesforthepropertiesand

thendivideseachcolumn'svaluebythatsum.Soeach

columntakesup1÷(1+1+1),or⅓ofthetotalspace.

Whathappensifoneofthecolumnshasadifferentvalue?

.column:first-of-type{

flex-grow:2;

flex-shrink:2;

}

Page 30: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Thefirstcolumntakesupthesameamountofspaceasthe

othertwo.That'sbecausethevaluesaddupto4,sothefirst

columnis:

2÷(2+1+1)=½

Theothertwoare:

1÷(2+1+1)=¼

AllAboutThatBasis

Ifyoulookcloselyatthelastexample,you'llnoticethatthe

firstcolumndoesn'tquitecoverhalfofthecontainer.Ifyou

addmorecontenttothethirdcolumn,youcanreallyseethe

problem.

<section>

<divclass="column">First</div>

<divclass="column">Second</div>

<divclass="column">

Thethirdcolumn,withmorecontentthan

before!

</div>

</section>

Page 31: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

What'sgoingon?Whyisflexboxnotflexingcorrectly?

Itturnsoutflexboxdoesn'tdistributespaceevenlytoeach

column.Itfiguresouthowmuchspaceeachcolumnstarts

with,specifiedbytheflex-basisproperty.Then,the

remainingspaceisdistributedusingtheflex-growand

flex-shrinkproperties.

Thismightseemconfusing,andthat'sbecauseitis.Theway

thisstuffaddsupisreallydamncomplicated,butdon't

worry,youdon'tneedtounderstandthenuancestouse

flexbox.

Sincewedon'tcareabouthowmuchspacethecontent

originallytakesup,setflex-basisto0.

Page 32: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

.column{

margin:10px;

flex-grow:1;

flex-shrink:1;

flex-basis:0;

}

.column:first-of-type{

flex-grow:2;

flex-shrink:2;

flex-basis:0;

}

Tah-dah!Itworks!Well,kindof—there'sonelastthingto

fix.

MoreFlexBasis

Ifyouaddanothersectionbelowthefirst,youcanseethe

problem.

Page 33: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

<section>

<divclass="column">First</div>

<divclass="column">Second</div>

<divclass="column">Third</div>

</section>

<section>

<divclass="column">First</div>

<divclass="column">Second</div>

<divclass="column">Third</div>

<divclass="column">Fourth</div>

</section>

.column{

margin:10px;

flex-grow:1;

flex-shrink:1;

flex-basis:0;

}

section:first-of-type.column:first-of-type{

flex-grow:2;

flex-shrink:2;

flex-basis:0;

}

Page 34: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Whydon'tthecolumnslineup?It'sbecauseflexboxincludes

thepadding,borderandmargininthebasiswhenit

calculateshowbigtheitemshouldbe.

Thefirstandsecondcolumnsinthesecondrowhave22

pixelsbetweenthem(20pixelsforthegutterand2pixelsfor

theborders).Wecanaddthismissingspacetothefirst

columninthefirstrowbysettingflex-basisto22px.

section:first-of-type.column:first-of-type{

flex-grow:2;

flex-shrink:2;

flex-basis:22px;

}

Page 35: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Shorthand

Together,flex-grow,flex-shrinkandflex-basisformthe

cornerstoneofwhatmakesflexboxflexible.Sincethese

propertiesaresocloselytiedtogether,there'sahandy

shorthandproperty,flex,thatletsyousetallthree.Youcan

useitlikethis:

flex:<flex-grow><flex-shrink><flex-basis>;

WecanrewriteourCSStolooklikethis:

.column{

flex:110px;

}

section:first-of-type.column:first-of-type{

flex:2222px;

}

Ahh,that'sbetter.Whythe0pxinthefirstflexdeclaration?

There'sabuginInternetExplorer10and11thatignores

flexifthebasisdoesn'tincludeaunit.

Page 36: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

That'sIt!

You'vecoveredatonofgreatstuffinthischapter,including

flex-grow,flex-shrinkandflex-basis.You'vealsoseen

howthesepropertiescanbeusedtoimplementtwelve-

columnlayouts.

Ifyou'relookingforachallenge,tryfinishingofftheentire

grid.Here'swhatitlookslikecompleted.

Ifyou'restillconfusedabouthowflex-grow,flex-shrink

andflex-basiswork,don'tworry.Thesepropertiesarethe

hardestthingtounderstandaboutflexbox.You'llbe

reviewingthemagaininlaterchapters,includingthenext

chapter,whereyou'llbuildanawesomevideoplayerlayout!

Page 37: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

CHAPTER 3

Building a Video Player

Page 38: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

What'sthebestpartaboutwatchingamovie?Isitthesalty

popcornthatcoatsyourfingertipsinhot,meltedbutter?How

aboutthemountainsofcrunchycandyorthemonolithic

soda?Coulditbethespecialeffectsandexplosions,orthe

rawtalentoftheactorsandactresses?Maybeit'sthe

profoundcinematographyorthemovingmusicalscore?

Ofcoursenot!It'stheplaybackcontrolsforthevideoplayer,

andinthischapter,you'regoingtolearnhowtomakethem!

I'llshowyouhowtobuildthekillerlayoutyouseeabove

usingflexbox!

Lights,Camera,Action!

Ifyoulookatthevideoplayerscreenshotabout,you'llnotice

thatitcanbecleanlydividedintomultiplesections.

Page 39: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Let'sstartbycapturingthisstructureinHTML.

<divclass="video-player">

<imgsrc="hot_air_balloons.jpg"alt="Video"

width="960"height="540">

<divclass="controls-container">

<divclass="controls">

<divclass="top-controls">

<divclass="volume-controls"></div>

<divclass="playback-controls"></div>

<divclass="size-controls"></div>

</div>

<divclass="progress-controls"></div>

</div>

</div>

</div>

Hereyou'vecreatedacontainerforthevideoplayer.

Normally,insidethatcontaineryou'dusea<video>element,

buttomakelifeeasierwe'llusean<img>element.

Page 40: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Insidethevideoplayercontainerisa<div>withaclassof

controls-container,whichwillbeusedfor—youguessedit

—containingthecontrols.Thetoprowofthecontrolsissplit

intothevolumecontrols,theplaybackcontrolsandthesize

controls.Thebottomrowisdevotedtotheprogresscontrols.

TheContainer

Thefirstthingyouneedtodoiscenterthevideoplayer

controlsinthecontainer.Youcandothisbyabsolutely

positioningthecontrolscontaineroverthetopofthevideo

player.Thisallowsthevideoplayer<div>tobedetermined

bythesizeoftheimageinsideofit.Whileyou'reatit,add

someCSStosizethecontrolscontainersoyoucanseeit.

.video-player{

position:relative;

}

.controls-container{

position:absolute;

top:0;

bottom:0;

left:0;

right:0;

}

Page 41: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

.controls{

width:480px;

margin-bottom:32px;

padding:12px4px;

}

Whatwewantisforthecontrolstobepositionedinthe

bottomcenterofthecontrolscontainer.Youcanaccomplish

thatsettingthecontrolcontainer'sdisplaypropertytoflex

andusingalign-itemsandjustify-content.

Page 42: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

.controls-container{

...

display:flex;

justify-content:center;

align-items:flex-end;

}

Thereyougo!Nowyouhaveanicelypositioned<div>for

yourcontrols.

TheProgressControls

Thenextstepistobuildtheprogresscontrols.TheHTMLfor

theseisprettystraightforward.

Page 43: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

<divclass="progress-controls">

<spanclass="time-elapsed">00:00:00</span>

<inputtype="range">

<spanclass="time-remaining">01:14:26</span>

</div>

Theideahereistoplacethetimeelapsedandtimeremaining

<span>elementsontheleftandrightofthecontainer,

respectively.The<input>thenfillsuptheremainingspace.

.progress-controls{

display:flex;

}

.time-elapsed,.time-remaining{

flex:00auto;

}

.progress-controlsinput[type="range"]{

flex:110px;

}

Page 44: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

What'sthatautovalue?Settingtheflex-basistoautotells

flexboxtoresizethecontainerbaseduponthesizeofthe

content.Inthiscase,thetimeelapsedandtimeremaining

spanstakeupasmuchroomastheyneed.Then,theprogress

controlscontainerstretchestotakeuptherestofthespace.

TheTopControls

Thetopcontrolsarealittletrickierthanthebottomcontrols.

<divclass="top-controls">

<divclass="volume-controls">

<button>

<imgalt="LowVolume"

src="low_volume.svg">

</button>

<inputtype="range">

<button>

<imgalt="HighVolume"

src="high_volume.svg">

</button>

</div>

Page 45: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

<divclass="playback-controls">

<button>

<imgalt="Rewind"src="rewind.svg">

</button>

<button>

<imgalt="Play"src="play.svg">

</button>

<button>

<imgalt="FastForward"

src="fast_forward.svg">

</button>

</div>

<divclass="size-controls">

<button>

<imgalt="Fullscreen"

src="fullscreen.svg">

</button>

</div>

</div>

Page 46: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Themarkupdoesn'tlookverynice,butit'lldothejob.It

mainlyconsistsofbuttonscontainingimagesand<div>

containers.

Thefirststepinstylingthetopcontrolsistodisplaythem

sidebyside.Inordertodothat,youneedtosetthetop

container'sdisplaytoflex.Remember,thedefaultvaluefor

flex-directionisrow,sothecontainer'scontentswillbe

displayedhorizontally.Whileyou'reatit,addalittlemargin

tothebottomofthetopcontrols.

.top-controls{

display:flex;

margin-bottom:8px;

}

Tomakethevolumecontrols,playbackcontrolsandsize

controlshorizontal,you'llalsomakeeachaflexcontainer.

Youcanusealign-itemstoverticallycentertheircontent.

Page 47: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

.volume-controls,

.playback-controls,

.size-controls{

display:flex;

align-items:center;

}

Next,youneedtospacethemout.Youmaybethinkingyou

canmakethevolumecontrolsandsizecontrolscontainer

sizetotheircontent,andhavetheplaybackcontrolsstretch

tofitthecontainerusingflex-growandflex-shrink.

However,ifyoutrythat,you'llendupwithcontrolsthatlook

likethis:

Noticehowtheplaybackcontrolsaren'tcentered?Instead,

you'llmaketheplaybackcontrolscontainersizetoits

Page 48: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

contentandletthevolumeandsizecontrolsexpand.

.playback-controls{

flex:00auto;

}

.volume-controls,.size-controls{

flex:110px;

}

Thisworksbecausetheflex-basisoftheplaybackcontrols

isauto,soplaybackcontrolscontainerissizedtothebuttons

itcontains.Thevolumeandsizecontrolsthenevenlyfillthe

remainingspace.

Next,aligntheitemsinthesizecontrolscontainertothe

end.

.size-controls{

justify-content:flex-end;

}

Page 49: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Theverylaststepistoaddasmallmarginaroundthe

buttonsandtimeelements.

button,.time-elapsed,.time-remaining{

margin:08px;

}

That'sit!Twothumbsup!

Page 50: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

Fin

Thenexttimeyou'rereadytokickbackandwatchyour

favoriteactionflick,rememberyoucanrebuildtheplayback

controlsusingyourownflexboxkungfu.

Page 51: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

CONCLUSION

Page 52: UNRAVELING FLEXBOX - Amazon S3 · Chapter 11: Ordering The order of the elements on your screen doesn't have to match the order in the HTML. This chapter will show you how to reorder

ThanksforReading!

ThanksforreadingthissampleofUnravelingFlexbox.Ihope

you'veenjoyedit!You'velearnedquiteabitaboutflexboxso

far,butthere'ssomuchmoreintheelevenchaptersyou

haven'tseenyet.

Inthefullbook,you'lllearnhowto:

PurchaseUnravelingFlexbox

Gobeyondtwelve-columnstobuildlayoutsthat

werepreviouslyimpossible.

Buildresponsiveflexboxlayoutsthatworkgreat

inmobile,tabletanddesktopbrowsers.

Supportolderbrowserswhilestillusingflexbox.•

Implementkillerflexboxformcontrols.•

Createvideoplaybackcontrolswithflexbox.•

Buildlayoutsthatwrapacrossmultiplelines.•

Writeyourveryownflexboxgridsystem.•

Testandfixyourcodeacrossallmobileand

desktopbrowsers.

Styleaflexible,tieredpricinglayout.•

Useflexboxtoreorderelementsonapage.•

Useeverythingyou'velearnedtobuildan

insanelyawesomeMinesweeperlayout.