技術筆記

flexbox

覺得排版很累人又麻煩嗎?
以前想排下列幾種排法 都非常的困難
應該會用盡postion, table, display跟float吧(苦笑…)

order

justify-content

flex-grow

align-self

 

第一次看到flexbox 就覺得也太神奇了吧
根本解決我苦惱多年的排版
先來看看瀏覽器支援程度

 

Browser Support

browser

這邊看到IE要10以上才可以用,
所以其實桌上版網站 我還是會避免用flexbox
(千萬不要看到不能用這個就把視窗關掉了)
因為他真的很適合做手機版網站的排版

 

首先 我把flexbox功能分兩塊

flex-function

 

container

(之後範例都以底色黃色區別)
可以控制item們的大方向,例如他們是要靠左對齊、分散對齊、垂直置中等等

 

item

(之後範例都以底色深灰區別)
則是可以各別控制,例如我想item1是其他item兩倍寬、item4順序要從最後一個變第一個

 

那我們就開始囉

我們的html結構非常簡單

<ul class="container">
  <li class="item"><a href="#">1</a></li>
  <li class="item"><a href="#">2</a></li>
  <li class="item"><a href="#">3</a></li>
  <li class="item"><a href="#">4</a></li>
</ul>

css //當然一定要加上display: flex; 才能開始做所以有事情

.container{
  display: flex;
}

 

flex-direction

row(default) | row-reverse | column | column-reverse
控制list水平還是垂直
[codepen_embed height=”442″ theme_id=”8415″ slug_hash=”VYvjeY” default_tab=”result” user=”hannahpun”]See the Pen flex-direction by hannahpun (@hannahpun) on CodePen.[/codepen_embed]

 

justify-content

flex-start(default) | flex-end | center | space-between | space-around
控制list的對齊方向
[codepen_embed height=”385″ theme_id=”8415″ slug_hash=”xbwORo” default_tab=”result” user=”hannahpun”]See the Pen justify-content by hannahpun (@hannahpun) on CodePen.[/codepen_embed]

 

align-items

flex-start | flex-end | center | baseline | stretch(default)
控制list的垂直對齊位置
[codepen_embed height=”493″ theme_id=”8415″ slug_hash=”EaVyZJ” default_tab=”result” user=”hannahpun”]See the Pen align-items by hannahpun (@hannahpun) on CodePen.[/codepen_embed]

 

align-self

auto | flex-start | flex-end | center | baseline | stretch
上圖的最後深灰色底就看的租來是各別控制item部分

 

flex-grow

<number>

控制每個item比例,可以拿來做三欄、兩欄的應用

See the Pen flex-grow by hannahpun (@hannahpun) on CodePen.

 

order

<integer>
[codepen_embed height=”161″ theme_id=”8415″ slug_hash=”QwjEKa” default_tab=”result” user=”hannahpun”]See the Pen flex-order by hannahpun (@hannahpun) on CodePen.[/codepen_embed]

 

應用-水平垂直置中

你會發現平常超擾人的水平垂直置中用flexbox變得超 級 簡 單
[codepen_embed height=”272″ theme_id=”8415″ slug_hash=”wBKWLX” default_tab=”result” user=”hannahpun”]See the Pen 水平垂直置中 by hannahpun (@hannahpun) on CodePen.[/codepen_embed]

 

應用-三欄式設計

通通用flexbox就解決所有對齊問題

See the Pen flexbox-use by hannahpun (@hannahpun) on CodePen.


寫完發現有人把它變成圖解釋
也蠻清楚的 可以點下面圖片
flexbox

易歐思創意 的個人頭像

易歐思創意

易歐思創意 數位轉單顧問

看 易歐思創意 的所有文章 →
回文章列表