MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

CSS彈性盒子用法

翻譯不完整。請協助 翻譯此英文文件

CSS3 彈性盒子(Flexible Box 或 Flexbox),是一種用於在頁面上佈置元素的佈局模式,使得當頁面佈局必須適應不同的屏幕尺寸和不同的顯示設備時,元素可預測地運行。對於許多應用程序,彈性盒子模型提供了對塊模型的改進,因為它不使用浮動,柔性容器的邊緣也不會與其內容的邊緣折疊。

許多設計師會發現彈性盒子模型更易於使用。彈性盒子中的子元素可以在各個方向上進行佈局,並且能以彈性尺寸來適應顯示空間。由於元素的顯示順序可以與它們在源代碼中的順序無關,定位子元素將變得更容易,並且能夠用更簡單清晰的代碼來完成複雜的佈局。這種無關性是僅限制於視覺呈現上的,語言順序以及基於源代碼順序的導航均不受影響。

注意:儘管CSS 彈性盒子佈局規範 CSS 還處於最終徵求意見稿(Last Call Working Draft)階段(參見最新編輯草案),並非所有瀏覽器都實現了彈性盒子的所有功能。但是,這麼說吧,現在全線產品對彈性盒子都有良好支持。最新的兼容性狀態可以查看每個具體屬性的兼容性表格獲取。

彈性盒佈局概念

在定義方面來說,彈性佈局是指通過調整其內元素的寬高,從而在任何顯示設備上實現對可用顯示空間最佳填充的能力。彈性容器擴展其內元素來填充可用空間,或將其收縮來避免溢出。

塊級佈局更側重於垂直方向,行內佈局更側重於水平方向,與此相對的,彈性盒子佈局算法是方向無關的。雖然塊級佈局對於單獨一個頁面來說是行之有效的,但其仍然缺乏足夠的定義來支持那些必須隨用戶代理(用戶代理)不同或設備方向從水平轉為垂直等各種變化而變換方向,調整大小,拉伸,收縮的應用程序組件彈性盒子佈局主要適用於應用程序的組件及小規模的佈局,而(新興的)柵格佈局則針對大規模的佈局。這二者都是CSS工作組為在不同用戶代理,不同書寫模式和其他靈活性要求下的網頁應用程序有更好的互操作性而做出的更廣泛的努力的一部分。

彈性盒佈局相關詞彙

關於彈性盒子的討論已經從諸如水平/行內軸和垂直/塊級軸這些術語中解放出來,與此同時,需要有一套新的術語來正確描述此模型。在學習下面的詞彙項目時請對照下圖。圖中是一個 flex-direction 屬性為 row 的彈性容器,意味著其內的彈性項目將根據既定書寫模式沿主軸水平排列,其方向為元素的文本流方向,在這個例子裡,為從左到右。

flex_terms.png

Flex container
The parent element in which flex items are contained. A flex container is defined using the flex or inline-flex values of the display property.
Flex item

Each child of a flex container becomes a flex item. Text directly contained in a flex container is wrapped in an anonymous flex item.

Axes

Every flexible box layout follows two axes. The main axis is the axis along which the flex items follow each other. The cross axis is the axis perpendicular to the main axis.

  • The flex-direction property establishes the main axis.
  • The justify-content property defines how flex items are laid out along the main axis on the current line.
  • The align-items property defines the default for how flex items are laid out along the cross axis on the current line.
  • The align-self property defines how a single flex item is aligned on the cross axis, and overrides the default established by align-items.
Directions

The main start/main end and cross start/cross end sides of the flex container describe the origin and terminus of the flow of flex items. They follow the main axis and cross axis of the flex container in the vector established by the writing-mode (left-to-right, right-to-left, etc.).

  • The order property assigns elements to ordinal groups and determines which elements appear first.
  • The flex-flow property shorthands the flex-direction and flex-wrap properties to lay out the flex items.
Lines

Flex items can be laid out on either a single line or on several lines according to the flex-wrap property, which controls the direction of the cross axis and the direction in which new lines are stacked.

Dimensions

The flex items' agnostic equivalents of height and width are main size and cross size, which respectively follow the main axis and cross axis of the flex container.

定義一個彈性盒子

為要使用此樣式的元素指派CSS,需按以下方式設置顯示屬性:

display: flex

或者

display: inline-flex

這樣做將元素定義為彈性容器,其子元素則成為彈性項目。flex 值使彈性容器成為塊級元素。inline-flex 使彈性容器成為單個不可分的行內級元素。

注意: When using the vendor prefix tag for old browsers, add the prefix to the display property, not the display attribute itself. For example, display: -webkit-flex.

Flex Item Considerations

Text that is directly contained inside a flex container is automatically wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space is not rendered, as if it were designated display: none.

Absolutely positioned children of a flex container are positioned so that their static position is determined in reference to the main start content-box corner of their flex container.

The margins of adjacent flex items do not collapse. Using auto margins absorbs extra space in the vertical or horizontal direction and can be used for alignment or to separate adjacent flex items. See Aligning with 'auto' margins in the W3C Flexible Box Layout Model specification for more details.

Flexbox's alignment properties do "true" centering, unlike other centering methods in CSS. This means that the flex items will stay centered, even if they overflow the flex container. This can sometimes be problematic, however, if they overflow past the top edge of the page, or the left edge (in LTR languages like English; the problem occurs on the right edge in RTL languages like Arabic), as you can't scroll to that area, even if there is content there! In a future release, the alignment properties will be extended to have a "safe" option as well. For now, if this is a concern, you can instead use margins to achieve centering, as they'll respond in a "safe" way and stop centering if they overflow. Instead of using the align- properties, just put auto margins on the flex items you wish to center. Instead of the justify- properties, put auto margins on the outside edges of the first and last flex items in the flex container. The auto margins will "flex" and assume the leftover space, centering the flex items when there is leftover space, and switching to normal alignment when not. However, if you're trying to replace justify-content with margin-based centering in a multi-line flexbox, you're probably out of luck, as you need to put the margins on the first and last flex item on each line. Unless you can predict ahead of time which items will end up on which line, you can't reliably use margin-based centering in the main axis to replace the justify-content property.

Recall that while the display order of the elements is independent of their order in the source code, this independence affects only the visual rendering, leaving speech order and navigation based on the source order. Even the order property does not affect speech or navigation sequence. Thus developers must take care to order elements properly in the source so as not to damage the document's accessibility.

Flexible Box Properties

Properties not affecting flexible boxes

Because flexible boxes use a different layout algorithm, some properties do not make sense on a flex container:

  • column-* properties of the multiple column module have no effect on a flex item.
  • clear has no effect on a flex item.
  • float causes the display property of the element to compute to block.
  • vertical-align has no effect on the alignment of flex items.

Examples

Basic flex example

This basic example shows how to apply "flexibility" to an element and how sibling elements behave in a flexible state.

​<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
    .flex {
        /* basic styling */
        width: 350px;
        height: 200px;
        border: 1px solid #555;
        font: 14px Arial;

        /* flexbox setup */
        display: flex;
        flex-direction: row;
    }

    .flex > div {
        flex: 1 1 auto;
        width: 30px; /* To make the transition work nicely. (Transitions to/from
                        "width:auto" are buggy in Gecko and Webkit, at least.
                        See http://bugzil.la/731886 for more info.) */
        transition: width 0.7s ease-out;
    }

    /* colors */
    .flex > div:nth-child(1){ background: #009246; }
    .flex > div:nth-child(2){ background: #F1F2F1; }
    .flex > div:nth-child(3){ background: #CE2B37; }

    .flex > div:hover {
        width: 200px;
    }
   
    </style> 
  </head>
  <body>
    <p>Flexbox nuovo</p>
    <div class="flex">
      <div>uno</div>
      <div>due</div>
      <div>tre</div>
    </div>
  </body>
</html>

Holy Grail Layout example

This example demonstrates how flexbox provides the ability to dynamically change the layout for different screen resolutions. The following diagram illustrates the transformation.

HolyGrailLayout.png

Illustrated here is the case where the page layout suited to a browser window must be optimized for a smart phone window. Not only must the elements reduce in size, but the order in which they are presented must change. Flexbox makes this very simple.

​<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
    body {
        font: 24px Helvetica;
        background: #999999;
    }

    #main {
        min-height: 800px;
        margin: 0;
        padding: 0;
        display: flex;
        flex-flow: row;
    }
 
    #main > article {
        margin: 4px;
        padding: 5px;
        border: 1px solid #cccc33;
        border-radius: 7pt;
        background: #dddd88;
        flex: 3 1 60%;
        order: 2;
    }

    #main > nav {
        margin: 4px;
        padding: 5px;
        border: 1px solid #8888bb;
        border-radius: 7pt;
        background: #ccccff;
        flex: 1 6 20%;
        order: 1;
    }
  
    #main > aside {
        margin: 4px;
        padding: 5px;
        border: 1px solid #8888bb;
        border-radius: 7pt;
        background: #ccccff;
        flex: 1 6 20%;
        order: 3;
    }
 
    header, footer {
        display: block;
        margin: 4px;
        padding: 5px;
        min-height: 100px;
        border: 1px solid #eebb55;
        border-radius: 7pt;
        background: #ffeebb;
    }
 
    /* Too narrow to support three columns */
    @media all and (max-width: 640px) {
        #main, #page {
            flex-direction: column;
        }

        #main > article, #main > nav, #main > aside {
        /* Return them to document order */
            order: 0;
        }
  
        #main > nav, #main > aside, header, footer {
            min-height: 50px;
            max-height: 50px;
        }
    }
    </style>
  </head>
  <body>
    <header>header</header>
    <div id='main'>
      <article>article</article>
      <nav>nav</nav>
      <aside>aside</aside>
    </div>
    <footer>footer</footer>
  </body>
</html>

Playground

There are a few flexbox playgrounds available online for experimenting:

Things to keep in mind

The algorithm describing how flex items are laid out can be pretty tricky at times. Here are a few things to consider to avoid bad surprises when designing using flexible boxes.

Flexible boxes are laid out in conformance of the writing mode, which means that main start and main end are laid out according to the position of start and end.

cross start and cross end rely on the definition of the start or before position that depends on the value of direction.

Page breaks are possible in flexible boxes layout as long as break- property allows it. CSS3 break-after, break-before, and break-inside as well as CSS 2.1 page-break-before, page-break-after, and page-break-inside properties are accepted on a flex container, flex items, and inside flex items.

Browser compatibility

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support (single-line flexbox) 18.0 (18.0)[6]-moz[2]
22.0 (22.0)
21.0-webkit
29.0
11[3] 12.10-webkit[5] 6.1-webkit[1]
Multi-line flexbox 28.0 (28.0) 21.0-webkit
29.0
11[3] 12.10[5]
15 -webkit
6.1-webkit[1]
Feature Firefox Mobile (Gecko) Firefox OS Android IE Phone Opera Mobile Safari Mobile
Basic support (single-line flexbox) 18.0 (18.0)-moz[2]
22.0 (22.0)

1.0-moz[2]
1.1

2.1-webkit[4]
4.4
11 12.10[5]
15-webkit
7-webkit[1]
Multi-line flexbox 28.0 (28.0) 1.3 2.1-webkit[4]
4.4
11 12.10[5]
15-webkit
7-webkit[1]

[1] Safari up to version 6.0 (iOS.1) supported an old incompatible draft version of the specification. Safari 6.1 (and Safari on iOS 7) has been updated to support the final version.

[2] Up to Firefox 22, to activate flexbox support, the user has to change the about:config preference layout.css.flexbox.enabled to true. From Firefox 22 to Firefox 27, the preference is true by default, but the preference has been removed in Firefox 28.

[3] Internet Explorer 10 supports an old incompatible draft version of the specification; Internet Explorer 11 has been updated to support the final version.

[4] Android browser up to 4.3 supported an old incompatible draft version of the specification. Android 4.4 has been updated to support the final version.

[5] While in the initial implementation in Opera 12.10 flexbox was not prefixed, it got prefixed in versions 15 to 16 of Opera and 15 to 19 of Opera Mobile with -webkit. The prefix was removed again in Opera 17 and Opera Mobile 24.

[6] Up to Firefox 29, specifying visibility: collapse on a flex item causes it to be treated as if it were display: none instead of the intended behavior, treating it as if it were visibility: hidden. The suggested workaround is to use visibility:hidden for flex items that should behave as if they were designated visibility:collapse. For more information, see bug 783470.

See also

文件標籤與貢獻者

 此頁面的貢獻者: iigmir, 1986slayer
 最近更新: iigmir,