CSS-Flex 佈局教程:實例篇

參考文章:Flex 佈局教程:實例篇css

1、骰子的佈局

  • 骰子的一面,最多能夠放置9個點。

下面,就來看看Flex如何實現,從1個點到9個點的佈局。html

若是不加說明,本節的HTML模板一概以下:佈局

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 頁面自動刷新 -->
    <meta http-equiv="refresh" content="1">
    <title>Document</title>
    <style> * { box-sizing: border-box; } html, body { height: 100%; } .box { margin: 16px; padding: 4px; background-color: #e7e7e7; width: 104px; height: 104px; object-fit: contain; box-shadow: inset 0 5px white, inset 0 -5px #bbb, inset 5px 0 #d7d7d7, inset -5px 0 #d7d7d7; border-radius: 10%; /* flex容器屬性 */ display: flex; } .item { display: block; width: 24px; height: 24px; border-radius: 50%; margin: 4px; background-color: #333; box-shadow: inset 0 3px #111, inset 0 -3px #555; } </style>
</head>

<body>
    <div class="box">
        <span class="item"></span>
        <!-- <span class="item"></span> -->
    </div>
</body>
複製代碼

上面代碼中,div元素(表明骰子的一個面)是Flex容器,span元素(表明一個點)是Flex項目。若是有多個項目,就要添加多個span元素,以此類推。flex

1.1 單項目

  • 首先,只有左上角1個點的狀況。Flex佈局默認就是首行左對齊,因此一行代碼就夠了。

.box {
  display: flex;
}
複製代碼
  • 設置項目的對齊方式,就能實現居中對齊和右對齊。

.box {
  display: flex;
  justify-content: center;
}
複製代碼

.box {
  display: flex;
  justify-content: flex-end;
}
複製代碼
  • 設置交叉軸對齊方式,能夠垂直移動主軸。

.box {
  display: flex;
  align-items: center;
}
複製代碼

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}
複製代碼

.box {
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
複製代碼

.box {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}
複製代碼

1.2 雙項目(先看容器佈局,在此基礎上移動項目佈局)

  • justify-content

.box {
  display: flex;
  justify-content: space-between;
}
複製代碼
  • flex-direction

.box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
複製代碼
  • align-items

.box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
複製代碼

.box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
}
複製代碼
  • align-self

.box {
  display: flex;
}

.item:nth-child(2) {
  align-self: center;
}
複製代碼

.box {
  display: flex;
  justify-content: space-between;
}

.item:nth-child(2) {
  align-self: flex-end;
}
複製代碼

1.3 三項目

.box {
  display: flex;
}

.item:nth-child(2) {
  align-self: center;
}

.item:nth-child(3) {
  align-self: flex-end;
}
複製代碼

2、項目flex屬性

  • 兩個快捷值:auto (1 1 auto)none (0 0 auto)

(1)ui

.box {
  display: flex;
}
.item {
    flex: auto;
}
複製代碼

(2)spa

.box {
  display: flex;
}
.item {
    flex: none;
}
複製代碼

(3)3d

.box {
  display: flex;
}
.item {
    flex: 1; // 1 1 0%
}
複製代碼

(4)code

.box {
  display: flex;
}
.item {
    flex: 1;
}
.item:nth-child(1){
    flex: 0 0 100%;
}

.item:nth-child(2){
    flex: 0 0 50%;
}
複製代碼
相關文章
相關標籤/搜索