1. 程式人生 > 實用技巧 >justify-content屬性詳解

justify-content屬性詳解

justify-content

定義了flexboxflexbox內的元素在主軸的方向上的對齊方式

它可以設定以下幾種對齊方式:

靠近一方

justify-content:center;  /*flex元素都居中排列,沒有間距*/
justify-content:start;   /*flex元素從行/列首開始排列,沒有間距*/
justify-content:end;    /*flex元素從行/列尾開始排列,沒有間距*/
justify-content:flex-start;  /*從行首起始位置開始排列*/
justify-content:flex-end;   /*從行尾位置開始排列*/
justify-content:left;   /*pack items from the left*/
justify-content:right;  /*Pack items from the right*/

均勻分佈

以上的首尾元素指的是 每一行/列 的第一個和最後一個元素。

justify-content: space-between;  /* 均勻排列每個元素
                                   首個元素放置於起點,末尾元素放置於終點 */
justify-content: space-around;  /* 均勻排列每個元素
                                   每個元素周圍分配相同的間距,
                    首尾元素與父容器邊界的距離是另一邊間距的一半 */ justify-content: space-evenly; /* 均勻排列每個元素 每個元素之間的間距相等,包括首尾元素與邊框的間距 */ justify-content: stretch; /* 均勻排列每個元素 'auto'-sized 的元素會被拉伸以適應容器的大小 */

溢位控制

justify-content: safe center;     /* 如果元素排列後溢位,safe屬性將用start作為預設排列方式 */
justify-content: unsafe center;   /* 元素溢位後沒有調整 */

全域性屬性

justify-content: inherit;
justify-content: initial;
justify-content: unset;

注意

當同時給flex元素設定了以下兩個屬性時,

  • 主軸方向上的長度 width / height
  • margin : 0 auto

justify-content屬性設定的對齊方式不起作用。

推薦一個有趣的 flex練習小遊戲Flexbox Froggy - A game for learning CSS flexbox