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

UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

May 27, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

The ultimate guide to building modern CSS layouts with flexbox

UNRAVELING

FLEXBOX

Landon Schropp

Page 2: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

SampleVersion1.3

Copyright©2016LandonSchroppLLC

AllRightsReserved

ThisisasampleofUnravelingFlexbox.Thefullversionis

availableforpurchaseatunravelingflexbox.com.

Page 3: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

INTRODUCTION

Page 4: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

I'dalsoliketothankmybetareaders,especiallyJoshua,

Darrin,Andrew,DucandChristine.Youguysmadeahuge

differenceinthequalityofthisbook,andIreallyappreciate

it!

EnoughChitchat

Let'sdivein.WelcometoUnravelingFlexbox!

Page 11: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

CHAPTER 1

Getting Dicey

Page 12: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

Tomakelifealittleeasier,I’veaddedthebasicstylesforthe

facesandthepips.Here'swhatitlookslike:

Thefirststepistotellthebrowsertomakethefaceaflexbox

container.

.first-face{

display:flex;

}

Itdoesn'tlookanydifferent,butthere'salotgoingonunder

thehood.

Page 14: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

Allright!Sincethemainaxisishorizontal,thepipisnow

centeredintheparentelement.

Thealign-itemspropertydictateshowtheitemsarelaid

outalongthecrossaxis.Becausewewantthepiptocenter

alongthisaxis,usethecentervalueheretoo.

.first-face{

display:flex;

justify-content:center;

align-items:center;

}

Page 16: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

Looksgood!

HorizontalandVerticalNesting

Let'sskipthethirdfaceandtacklethefourth.Thisoneisa

littletrickierthantheothersbecauseweneedtosupporttwo

columns,eachwithtwopips.

Therearetwothingsaboutflexboxthatwillsaveyouhere:

flexcontainerscanhaveverticalorhorizontalcontent,and

flexcontainerscanbenested.

Unlikebefore,themarkupwillnowincludecolumns.

Page 20: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

<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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

Note:Thisfacecouldhavebeenbuiltwithoutcolumnsbyusing

wrapping.I'llcoverwrappinginmoredetailinChapter9.

WrappingUp

Woohoo!Threefacesdownandthreetogo.Atthispoint,

youhaveeverythingyouneedtobuildtheotherthree.Give

itashot!Whenyou'redone,takealookatthecodeexamples

fortheanswers.

Page 24: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

CHAPTER 2

Crafting Twelve-Column Layouts

Page 25: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

.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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

.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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

<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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

CHAPTER 3

Building a Video Player

Page 38: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

.controls{

width:480px;

margin-bottom:32px;

padding:12px4px;

}

Whatwewantisforthecontrolstobepositionedinthe

bottomcenterofthecontrolscontainer.Youcanaccomplish

thatsettingthecontrolcontainer'sdisplaypropertytoflex

andusingalign-itemsandjustify-content.

Page 42: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

.controls-container{

...

display:flex;

justify-content:center;

align-items:flex-end;

}

Thereyougo!Nowyouhaveanicelypositioned<div>for

yourcontrols.

TheProgressControls

Thenextstepistobuildtheprogresscontrols.TheHTMLfor

theseisprettystraightforward.

Page 43: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

<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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

<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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

.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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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 FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

Theverylaststepistoaddasmallmarginaroundthe

buttonsandtimeelements.

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

margin:08px;

}

That'sit!Twothumbsup!

Page 50: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

Fin

Thenexttimeyou'rereadytokickbackandwatchyour

favoriteactionflick,rememberyoucanrebuildtheplayback

controlsusingyourownflexboxkungfu.

Page 51: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

CONCLUSION

Page 52: UNRAVELING FLEXBOXmightydeals.s3.amazonaws.com/dealimages/unraveling-flexbox/Unra… · Flexbox isn't just for full-page layouts! In this chapter, you'll learn how to use flexbox

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.