CSS Master

(Primo) #1

Creating Flexible Components with flex


Anotherusecaseforflexboxiscreatingflexible,verticallyalignedformcomponents.
ConsidertheinterfacepatternshowninFigure4.41.


Figure 4.41. A form field with an adjacent button

Herewehaveaforminputcontrolandanadjacentbutton.Botharevertically
aligned,andourbuttonis 110 pixelswide.


Whatifwewantourinputelementtoexpandtofilltheavailablespaceinitscon-
tainer?Withoutflexbox,we’drequiresomeJavaScriptandhand-wavingtoupdate
thewidthofinputinresponsetochangesinthewidthofitsparent.Withflexbox,
however,wecanjustuseflex.


Theflexpropertyisactuallyshorthandforthreeotherproperties:


flex-grow: indicatesthatanelementshouldgrowifnecessaryandmustbe
apositiveinteger;initialvalueis 0


flex-shrink: indicatesthatanelementshouldshrinkifnecessaryandmustbe
apositiveinteger;initialvalueis 1


flex-basis: indicatestheinitialorminimumwidth(whentheflexaxisis
horizontal)orheightofanelement(whenit’svertical);maybea
lengthorpercentage,orauto,anditsinitialvalueisauto


Thoughit’spossibletoseteachoftheseindividually,thespecificationstronglyre-
commendsusingtheflexshorthand.Here’sanexample:


div {
display: flex;
justify-content: center;
}

input[type="text"],

Complex Layouts 177

Free download pdf