第一章:介紹flexbox

若是你想構建一個響應式網站,你真的須要瞭解flexbox。javascript

什麼是Flexbox?css

Flexbox是CSS3彈性盒佈局模型( CSS3 flexible box layout module )的通稱。這個模型定義了一種新的佈局模式( layout mode )。你可能會問,什麼是佈局模式?java

佈局模式是一套規則,這套規則決定了網頁元素( web elements )的大小( size )和位置( position ),這套規則也基於它們和兄弟、祖先元素的關係。git

【  A layout mode is a set of rules that determine the size and position of web elements, based on their relationships with siblings and ancestors. github

佈局模式有以下幾種類型:web

  • block :爲放置文檔( documents )而設計
  • inline :爲放置文本( text )而設計
  • table :爲放置表格( tables )而設計
  • positioned :Designed for positioning elements independent of other elements
  • flex ;Designed for laying out web components that can be resized smoothly

 下圖顯示了一個網頁( web page )動態改變佈局以適應不一樣屏幕的分辨率瀏覽器

  

當是小屏幕時,一行只能顯示一列,當是大屏幕時,一行能顯示三列的內容。一個網頁設計師能夠合理地使用任何佈局模式來達到上圖的變化——小屏幕一列大屏幕三列,但機智的設計師會使用flexbox。框架

 

爲何要使用flexbox?工具

使用flexbox最主要的緣由是:使用flexbox可讓複雜的佈局變得簡單。舉例來講,使用 flexbox 能夠很容易:佈局

  ① 垂直對齊父元素裏面的內容

    【 Align content vertically within a parent element 

  ② 基於網格佈局建立等高的列

    【 Create equal-height columns for grid-based layouts 】

  ③ 在不一樣的設備和屏幕分辨率下對內容進行從新排序

    【 Reorder content for different screen resolutions and different devices 】

上面這幾件事情經過其餘的佈局模式再加上傳統的css也能作到,可是它們須要float,好的JavaScript功底( fancy javascript ),或者 clever hacks。

相比之下,flexbox纔是真的頁面( page )佈局工具。設計師只需幾行代碼就能不費力的構建複雜的佈局,no floats, no workarounds, and no hacks 。

NOTE
For a good description of common design problems that were once hard or impossible to solve with CSS alone, visit https://philipwalton.github.io/solved-by-flexbox/.
Philip Walton shows (with code) how each problem is now 「trivially easy」 to solve with flexbox 

 flexbox和響應式web設計

flexbox對響應式web設計來講特別有用。當你在構建一個響應式網站時,你實際上是創建了這樣一個站點,這個站點能自動適應當前的設備。當在手機上時它會收縮以適應小屏幕,當在桌面等設備上上它會擴展以適應大屏幕。

When you build a responsive website, you build a site that adapts itself to the device on which it is displayed. It shrinks to fit the small screen of a smart phone and expands to fill the large screen of a desktop monitor. 】

使用 flexbox,網頁上的零件能夠被:

With flexbox, components on a web page can be made to: 】

  ① 隨着瀏覽器的viewport變大而擴展開來

  ② 隨着viewport的變小而收縮

  ③ 無視viewport的行爲( behavior ),保持相同的大小。

這種佈局控制( layout control )的程度( degree )對錶現( performance )沒有損耗。這兒沒有附加的框架去爭奪珍貴的資源下降性能。一切都是靠簡單的css完成,經過flexbox 佈局模式。並且響應快如閃電。
There are no add-on frameworks to compete for precious resources and slow things down. 】

 

flexbox 的挑戰

http://caniuse.com/#search=flex

flexbox面臨的主要挑戰來源於外部——當前瀏覽器的支持程度而不是內部——flexbox自己很是容易學習。一方面咱們想發揮 flexbox 炫酷的佈局能力,另外一方面,咱們但願網站在全部的瀏覽器上功能完整。

On the other hand, we want websites to be fully functional on all browsers 】

這裏有個底線:若是你只支持現代瀏覽器你能夠毫無顧忌的如今就使用flexbox,若是你還須要支持老的瀏覽器,你須要採用下面一個或所有的策略:

  ① 在樣式表內添加瀏覽器前綴( vendor prefixes )

  ② 漸進加強的設計方案( Design with progressive enhancement )

 

接下來的步驟

在接下來的章節裏,咱們將會學習 flexbox 的術語和語法。你將會看到,flexbox 是如何助於佈局控制( layout control ),你也會學到怎樣和那些不支持flexbox的老瀏覽器打交道。

到本書結束,你將會知道如何用flexbox構建一個響應式網頁能夠在全部的瀏覽器全部的設備上運行。

相關文章
相關標籤/搜索