Вы находитесь на странице: 1из 24

C SS

LA YOUT

WITH

FLE XBOX

Lay ing out a design with CSS is fraught with peril of cross-browser bugs and myster iously col -

lapsing mar gins. But new tools like flexbox have transformed this once odious task into some-

thing you shouldn't dread. By the end of this chap ter you'll be coding up new lay outs for your

design faster than you can think of them.

R Rocket

e mem ber those old car toons with the road run ner and the coy ote? pro pelled roller skates, bot tled light ning, bun dles of dy na -

mite, mag netic bird seed, razor boomerangs, "super" bombs and giant tram po lines -- no tech nol ogy could catch the bird. Every tool back fired and sent Wile E. Coy ote plum met ing to hillar i ous death. Using CSS to lay out your de sign is like try ing to catch the road run ner with a jet-pow ered pogo stick. It won't end well.

CSS sucks at layout

Noth ing is more frus trat ing than writ ing a pile of code, re fresh ing your browser and see ing a jum bled mess of overl ap ping text and im ages. You can't use ta bles be cause they aren't se m an tic. Floats and clears never do what you ex pect. Just to cen ter somet hing on the page re quires strange in can ta tions of auto mar gins or text-align -- the cen ter tag is right out. But you know what? This is old news be cause CSS doesn't suck at lay out any more.

Introducing Flexbox

Once you spend some time with flexbox you'll feel like an un stop pable super hero of CSS. Your footer will stay at the bot tom of the page where it be longs. Your list items will flow ef fort lessly into neat lit tle columns. Divs will shrink and grow and fly in del i cate for ma tions like the Blue An gels. Image tags will dance and jump and sing songs of your de sign prowess. "Wait, let's not get car ried away" you say, "Flexbox is too new. You can't even use it in IE9." It doesn't matt er. Think about it: how many browsers does a PSD work in? None? Ex actly. As a de s igner you're not build ing the final ver sion of the de sign. You don't care if flexbox doesn't work in Opera Mini be cause the comp you are cre a ti ng for your client only needs to run in Chrome. Worry about Sea Mon key later. The key is to keep your lay out code sep a rate from your style code. Cre ate an en tirely new stylesheet just for lay out. Du pli cate se lec tors if you have to. By keep ing it sep a rate, it's eas ier for a front-end de vel oper to cre ate the final, pro duc tion-ready layo ut code once the de sign has so lid i fied enough.
Diving into Flexbox

You only need to know a hand ful of CSS prop er ties and a lit tle ter mi nol ogy to use flexbox. Every thing starts with the flex con tainer. Once an el e ment is set as a flex con tainer it's chil dren fol low the flexbox rules for lay out in stead of the stan dard block, in line and inl ine-block rules. Within a flex con tainer items line up on the "main axis" and the main axis can ei ther be hor i zon tal or ver ti cal so you can arrange items into columns or rows. The

axes are in vis i ble, but in the ex am ples added, vis i ble lines will help you see how the main axis and cross axis are ori ented. Every ex am ple uses the same HTML.

< d i vc l a s s = " f l e x " > < h e a d e r > < / h e a d e r > < a r t i c l e > < / a r t i c l e > < a s i d e > < / a s i d e > < f o o t e r > < / f o o t e r > < / d i v >

There is a litt le CSS to style the boxes and give them some di men sion, plus the div is set as a flex con tainer.

. f l e x { d i s p l a y :f l e x ; } . f l e x>* { m i n w i d t h :1 0 0 p x ; m i n h e i g h t :1 0 0 p x ; } h e a d e r { b a c k g r o u n d :r g b a ( 2 0 0 ,2 0 0 ,2 0 0 ,1 ) ; } a r t i c l e { b a c k g r o u n d :r g b a ( 2 0 0 ,2 0 0 ,2 0 0 ,. 8 ) ; } a s i d e { b a c k g r o u n d :r g b a ( 2 0 0 ,2 0 0 ,2 0 0 ,. 6 ) ; } f o o t e r { b a c k g r o u n d :r g b a ( 2 0 0 ,2 0 0 ,2 0 0 ,. 4 ) ; }

A quick overview of flexbox terminology

The first ex amp le cen ters the flex con tainer chil dren, (the <header>, <ar ti cle>, <aside> and <footer>), ver ti cally and hor i zon tally. Ver ti cal cen ter ing with CSS used to be re a lly hard, with flexbox it's one line of CSS.

f l e x f l o w :r o w ; a l i g n i t e m s :c e n t e r ;/ *T h i sc e n t e r st h ei t e m sv e r t i c a l l y .* / j u s t i f y c o n t e n t :c e n t e r ;/ *T h i sc e n t e r se v e r y t h i n gh o r i z o n t a l l y .

The flex-flow prop erty de ter mines which way the main axis is ori ented, (the cross-axis is alw ays per pindic u lar to the main axis). When it's set to row, the main axis is hor i zon tal, and it's ver ti cal when set to col umn. You use jus tify-con tent to de ter mine where the items line up on the main axis and align-items to shift them around on the cross-axis.

The main axis is hor i zon tal, so the the flex items are lined up in a row.

What hap pens if the main axis is ver ti cal, (so flex-flow is set to col umn)?

The main axis is ver ti c al, so the the flex items are lined up in a col umn.

In the ex am ples you've seen so far, jus tify-con tent and align-items have been set to cen ter but you can also move them to the be gin ning or end of ei ther axis. To move the flex con tainer chil dren to the end of ei ther axis, set jus tify-con tent or align-items to flex-end. To move them to the be gin ning use flex-start.

The con tent is in the bot tom right cor ner be c ause it's aligned with the end of the main axis and the end of the cross axis.

Space around flex items

In stead of push ing items to the be gin ning, cent er or end of the main axis, you can dis trib ute space evenly around the items. Set jus tify-con tent to space-around or space-be tween.

The flex items are cen tered on the cross axis and have space evenly dis trib uted around them along the main axis.

Shrinking and grow ing

You can de fine the size of flex items. This lets you cre ate lay outs with, for ex am ple, a col u mn with a fixed width and a col u mn that grows or shrinks with the space avail able. You achieve this magic by set ting three sep a rate prop er ties on the chil dren of the flex con tainer: flex-grow, flex-shrink, and flex-ba sis. Or you can com bine all three val ues in one prop erty: flex.

The left flex item stretches to fill about a third of the screen and the oth ers shrink to fill the rest evenly. In this case I've also de c ided to have them grow and fill the ver ti c al space.

The skinny col umn is fixed at 50 pix els. The other columns grow and shrink to fill in the re m ain ing space evenly.

Beyond static images and text

You haven't seen much code up to this point bec ause the CSS prop erty names don't map well to the very sim ple con cepts be hind flexbox. Flexbox makes much more sense when you can watch and see what happ ens on the screen as the code is up dated. Here are three screen casts to help you add flexbox to your ar se nal. You can also lean on this cheat sheet while you get used to the ter mi nol ogy. The ba sics Grow ing and shrink ing flex items More ad vanced odds and ends

Examples from Real Websites

Flexbox doesn't solve every lay out prob lem but it cer tainly fixes the worst of them. As you look at a few real world ex am ples you will learn a few other tech niques for ar rang ing el e ments on the page but flexbox alone will get you 90% of the way most of the time.

37signals

The prod uct sec tion of the 37sig nals home p age.

You're look ing at three divs cen tered hor i zon tally cer tainly not the most com pli cated lay out of all time. Even so, be fore flexbox cre a t ing this kind of lay out re quired some thought; cen ter ing el e ments on the page was not in tu itive.

The HTML

< d i vc l a s s = " p r o d u c t s " > < d i v > < i m gs r c = " b a s e c a m p . p n g " > < / i m g > < h 2 > < ah r e f = " " > B a s e c a m p < / a > < / h 2 > < h 3 > M a n a g eP r o j e c t s < / h 3 > < p > U s e db ym i l l i o n sf o rp r o d u c tm a n a g e m e n t . < / p > < / d i v > < d i v > < i m gs r c = " h i g h r i s e . p n g " > < / i m g > < h 2 > < ah r e f = " " > H i g h r i s e < / a > < / h 2 > < h 3 > < ah r e f = " " > M a n a g eC o n t a c t s < / a > < / h 3 > < p > K n o wt h ep e o p l ey o ud ob u s i n e s sw i t h . < / p > < / d i v > < d i v > < i m gs r c = " c a m p f i r e . p n g " > < / i m g > < h 2 > < ah r e f = " " > C a m p f i r e < / a > < / h 2 > < h 3 > W o r ki nR e a l T i m e < / h 3 > < p > G r o u pc h a tr o o m sf o ry o u rb u s i n e s s . < / p > < / d i v > < / d i v >

No layout yet

Be fore any lay out logic it's all mushed to the left and in a col umn.

This is how the markup rend ers with just enough CSS to make the styling look about the same. You are look ing at the de fault browser lay out be fore we've ap plied any flexbox rules. The three boxes are div el e ments. Div el e ments are block el e ments and block el e ments stack, they don't flow next to each other. First let's cent er it on the page and get every thing flow ing into a row.

The CSS

. p r o d u c t s { d i s p l a y :f l e x ; f l e x f l o w :r o w ; j u s t i f y c o n t e n t :c e n t e r ; }

Five lines of CSS later...

Five lines of flexbox code set ting three prop er ties and our Base c amp ex am p le is start ing to look pretty good.

The div wrap ping the prod uct divs was set to "dis play: flex" to make it a flex con tainer. Then to get its items into a row, set the flex-flow prop erty to "row". Get ting every thing cen tered was easy. Jus tify-con tent let's you move flex items on the main axis. In this case the main axis is hor i zon tal be cause the flex-flow prop erty is set to "row". When the main axis is hor i zon tal, jus tify-con tent will move the items to the left and right. If the main axis is ver ti c al, (set flex-flow to col umn), jus tify-con tent moves the items up and down in stead of left and right. To cen ter the prod uct divs in the ex am ple hor i zon tally,set jus tify-con tent to "cen ter".

The first real world ex am ple is al most done. The mid dle con tainer needs some space around it and all of the items in each con tainer should be cen tered hor i zon tally. To cen ter the items in the div it's eas i est to think about them as flow ing in a col umn and then cen ter ing them on the cross axis. So in this case the main axis is ver ti cal and the cross axis is hor i zon tal. Here's the code:

/ * 1 .M a k ea l lo ft h ep r o d u c td i v sf l e xc o n t a i n e r s . 2 .S e tt h e i ri t e m st of l o wi n t oac o l u m n . 3 .C e n t e rt h e ml e f t t o r i g h tb yc e n t e r i n gt h e m o nt h ec r o s sa x i su s i n ga l i g n i t e m s . * / . p r o d u c t s>d i v { d i s p l a y :f l e x ; f l e x f l o w :c o l u m n ; a l i g n i t e m s :c e n t e r ; } / *U s i n gs e l e c t o r sl i k et h i s i sc o v e r e di na n o t h e rc h a p t e r . * / . p r o d u c t s>d i v : n t h c h i l d ( 2 ) { m a r g i n :02 e m ; }

The fin ished ex am p le with every thing lined up in side the prod uct divs and mar gin around the mid d le.

Anatomy of a Tweet

An ex am p le tweet.

The HTML

< d i vc l a s s = " t w e e t " > < d i vc l a s s = " c o n t e n t " > < i m gs r c = " a a r o n . p n g " > < / i m g > < h 2 > A a r o nG u s t a f s o n< s p a n > @ A a r o n G u s t a f s o n < / s p a n > < / h 2 > < t i m e > 1 2 h < / t i m e > < p > S m a r t p h o n eB r o w s e rl o c a l S t o r a g ei su pt o5 xF a s t e rt h a nN < ah r e f = " / " > m o b i f y . c o m / b l o g / s m a r t p h o n. . . < / a > < / p > < u lc l a s s = " a c t i o n s " > < l i > < ah r e f = " " > C o l l a p s e < / a > < / l i > < l i > < ah r e f = " " > R e p l y < / a > < / l i > < l i > < ah r e f = " " > R e t w e e t < / a > < / l i > < l i > < ah r e f = " " > F a v o r i t e < / a > < / l i > < l i > < ah r e f = " " > M o r e < / a > < / l i > < / u l > < u lc l a s s = " m e t a " > < l ic l a s s = " r e t w e e t s " > < s p a n > 7 < / s p a n > < s p a n > R E T W E E T S < / s p a n > < / l i > < l ic l a s s = " f a v o r i t e s " > < s p a n > 5 < / s p a n > < s p a n > F A V O R I T E S < / s p a n > < / l i > < l ic l a s s = " p e o p l e " > < u lc l a s s = " p e o p l e " > < l i > < i m gs r c = " p e o p l e 1 . j p g " / > < / l i > < l i > < i m gs r c = " p e o p l e 2 . j p g " / >

< / l i > < l i > < i m gs r c = " p e o p l e 3 . j p g " / > < / l i > < l i > < i m gs r c = " p e o p l e 4 . j p g " / > < / l i > < l i > < i m gs r c = " p e o p l e 5 . j p g " / > < / l i > < l i > < i m gs r c = " p e o p l e 6 . j p g " / > < / l i > < l i > < i m gs r c = " p e o p l e 7 . j p g " / > < / l i > < / u l > < / l i > < / u l > < t i m e > 4 : 3 5A M-2 4M a y1 3 < / t i m e > < / d i v > < d i vc l a s s = " r e p l y " > < d i vc o n t e n t e d i t a b l e = " t r u e " > R e p l yt o< s p a n > @ A a r o n G u s t a f s o n < / s p a n > < / d i v > < / d i v > < / d i v >

No layout

The de fault browser lay out: stacked in a col umn and pushed over to the left.

Perfect is the enemy of done

When conf ronted with a con found ing lay out prob lem a com mon pit fall is to waste time find ing the "best" so lut ion. As soon as you find your self pon der ing the mer its of chang ing the markup and wor ry ing about mess ing up the se man tics, stop what you're doing and see if ab solute po si tion ing would work. When ever you're think ing about tech ni cal de ci sions you're not think ing about de sign. Re mem ber, your job is to cre ate a comp, not the final

site. The code you are writ ing will be re worked and rewrit ten so don't spend any time mak ing it per fect -- per fect is the enemy of done. The first chal lenge with the tweet is the user pro file image and the date tag. Al though not ob vi ous in this ex am ple the tweet text flows under the date and the pro file image seems to have it's own col umn. The way the markup was writt en does not make a flexbox lay out im me di ately ob vi ous. You might be tempted to spend a few min utes to fig ure out a way you could change the markup and get the lay out you want with flexbox, but here is an ex amp le where you could eas ily get mired down in tech ni cal de tails. In stead, just ab solutely po si tion both el e ments where you want them. There is dan ger in ab solute po si tion ing for pro duc tion code, but it's fine in small doses for pro to typ ing.

The CSS

/ *c r e a t et h es p a c eo nt h el e f tf o rt h ep r o f i l ei m a g e * / . t w e e t. c o n t e n t , . t w e e t. r e p l y { p a d d i n g l e f t :7 0 p x ; } / * m o v et h ei m a g et ot h el e f ti n t ot h ec o l u m n * / . c o n t e n t>i m g { p o s i t i o n :a b s o l u t e ; m a r g i n l e f t :6 0 p x ; } / * M o v et h et i m e s t a m pu pa n dt ot h er i g h t U s e d" e m "i n s t e a do fp i x e l sh e r e ,b u tp i x e l s a r ej u s tf i n e . * / . c o n t e n t>t i m e : f i r s t o f t y p e { p o s i t i o n :a b s o l u t e ; m a r g i n t o p :1 . 5 e m ; m a r g i n l e f t :3 0 e m ; } / * A d d e ds o m ev e r t i c a lp a d d i n gt oa l l o ft h ee l e m e n t si nt h ec o n t e n td i v . * / . c o n t e n t>* { p a d d i n g :. 2 5 e m0 ; }

Ab solutely positioned two elements

What the tweet looks like after ab solutely po si tion ing two el e m ents and adding some spac ing.

The next step is to take the ac tions, (e.g. coll apse, reply, retweet, etc.), the retweets and fa vorites and the list of small pro file pic tures and put them into rows in stead of columns.

A dash of flexbox

. a c t i o n s ,l i . p e o p l e ,. m e t a ,. p e o p l e>u l{ d i s p l a y :f l e x ; }

Almost done

One line of CSS and it's al m ost done.

El e ments in con tain ers are arranged into rows by de fault so you just need to set the con tainer to dis play: flex. You'll not ice in the real tweet the num bers are on top of "fa vorites" and "retweets". There are two ways to do this. The first is to treat them like flex con taine rs and put them into a col umn. The sec ond way is to make each of the spans wrap ping the num bers into a block el e ment in stead of in line. The seco nd way is only ob vi ous if you know that block el e ments stack. The beauty of flexbox is you don't need to know the ins and outs of block, in line or in line-block el e ments. Learn the ba sics but don't waste time use flexbox when it's not ob vi ous.

Stack the elements

. m e t a. r e t w e e t s , . m e t a. f a v o r i t e s { d i s p l a y :f l e x ; f l e x f l o w :c o l u m n ; }

Finished

Two more lines of CSS for lay out plus some spac ing and bor d ers around key el e m ents. Yes, it's miss ing icons for the ac tion links. It's just an ex am p le.

CSS-Tricks

In cluded in the book ex am ple code is a third, much more com pli cated ex am ple for you to look at. Most of the CSS-Tricks forum has been recre ated using flexbox for lay out.

The CSS-Tricks forum re verse en gi neered using flexbox.

Load the ex am ple in Chrome and use the skills you learned in the chap ter on using Chrome's De vel oper tools to see how some of the el e ments in the ex am ple are laid out using flexbox.

Tips and tricks


When ab solutely po si tion ing an el e ment use mar gins in stead of top, left, right, bot tom. El e ments ab solutely po si tioned with mar gins are more con sis tent across dif fer ent screen res o lu tions. Use ems in stead of pix els. Ems adj ust when you change font-size. If you in creased the base font size in this ex am ple the date would main tain its po si tion. Use padding in stead of mar gin for spac ing. Spaces cre ated with mar gin some times coll apse into each other in stead of stack ing. Some times you want this but most of the time it's not help ful. Padding doesn't col lapse so it's more pre dictable than using mar gins. Use the uni ver sal se lec tor, *, with out fear. Ex pe ri enced web de vel op ers avoid the uni ver sal se lec tor for per for mance rea sons. You shouldn't spend any time think ing about this. There are per for mance is sues but noth ing to worry about when cre a t ing the ini tial de sign. The key to cre a t ing more com pli cated layo uts with flexbox is to break it into pieces. Don't be afraid to make every thing a flex con tainer if that's what works for you.

Summary
Mas ter ing the art of lay ing out el e ments on a page using CSS is the hard est part of de sign ing in the browser. Flexbox has made this task much eas ier. Here is your flexbox cheat sheet, use it wisely. Every ex am ple in this chap ter has code, in cluded with the book, you can look at and use in your pro jects. Open the ex am ples, (in cluded with this book), with Chrome and use the de vel oper tools to get a closer look. The real-world ex am ples are also in cluded with your copy of the book and hosted on the web. The 37sig nals ex am ple, the twit ter ex am ple and the CSS-Tricks forum.

Вам также может понравиться