0%

前端設計 — 置中方法整理

Display 屬性置中

📌 Display: block

1
2
3
4
<div class="outter outter1">
<div class="box box1">讓我置中</div>
<div class="box box1">讓我置中</div>
</div>
1
2
3
4
5
.outter.outter1 .box1{
display: block;
margin: 0 auto;
width: 100px;
}

📌 Display: inline-block

1
2
3
4
<div class="outter outter1">
<div class="box box1">讓我置中</div>
<div class="box box1">讓我置中</div>
</div>
1
2
3
4
5
6
7
8
9
.outter.outter1{
text-align: center;
}

.box1{
display: inline-block;
vertical-align: top;
text-align: right;
}

📌 Display: flex

搭配 justify-content,對子層做水平置中

1
2
3
<div class="outter outter1">
<div class="box box1">讓我置中</div>
</div>
1
2
3
4
5
.outter.outter1{
display: flex;
justify-content: center;
/* justify-content: center對子層做"水平"置中 */
}

搭配 margin

  1. margin: 0 auto;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    .outter.outter1{
    display: flex;
    /* 先使子層由左至右排列 */
    }

    .box1{
    margin:0 auto;
    /*再針對box本身做置中,此例為margin:0 auto*/
    }
  2. margin: auto auto;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    .outter.outter1{
    display: flex;
    /* 先使子層由左至右排列 */
    }

    .box1{
    margin: auto auto;
    /* 再針對box本身做置中,此例會在outter3-3"正中間"! */
    }

搭配 align-items

1
2
3
4
5
6
7
8
9
10
11
.outter.outter1{
display: flex;
align-items: center;
/* align-items針對子層做"垂直"置中 */
justify-content: center;
/* justify-content: center針對子層做"水平"置中 */
}

.box1{
text-align: center;
}

搭配 align-self

1
2
3
4
5
6
7
8
9
10
11
.outter.outter1{
display: flex;
/* 使子層由左向右排列 */
justify-content: center;
/* justify-content: center針對子層做"水平"置中 */
}

.box1{
align-self: center;
/* 針對自己做垂直置中 */
}

搭配 flex-direction

  1. 垂直置中

    1
    2
    3
    4
    5
    6
    7
    8
    .outter.outter1{
    display: flex;
    /* 使子層由左到右排列 */
    flex-direction: column;
    /* 使子層由上向下排列 */
    justify-content: center;
    /* 方向被flex-direction轉換為控制"垂直"方向 */
    }
  2. 水平置中

    1
    2
    3
    4
    5
    6
    7
    8
    .outter.outter1{
    display: flex;
    /* 使子層由左到右排列 */
    flex-direction: column;
    /* 使子層由上向下排列 */
    align-items: center;
    /* 方向被flex-direction轉換為控制"水平"方向 */
    }
  3. 正中間

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    .outter.outter1{
    display: flex;
    /* 使子層由左到右排列 */
    flex-direction: column;
    /* 使子層由上向下排列 */
    justify-content: center;
    /* 方向被flex-direction轉換為控制"垂直"方向 */
    align-items: center;
    /* 方向被flex-direction轉換為控制"水平"方向 */
    }

📌 Position 屬性置中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.outter.outter1{
position: relative;
/* 令此層可為position:absolute的參考點 */
}

.box1{
position: absolute;
/* 參考點為上一層 */
top:50%;
left:50%;
/* top,left的參考值為上一層 */
transform: translate(-50%,-50%);
/* transform參考值(X,Y)為自己的寬高 */
}

📌 文字的置中

1
2
3
4
5
6
/* 完全置中於box的正中間 */
.box{
text-align: center;
line-height: 100px;
/* 高度由line-height表示=>值為box5的高 */
}

前端設計 — 盒模型(Box Model)及Display屬性?

⭐ 盒模型(Box Model)

🔖 盒模型定義

瀏覽器將每一個標籤元素都視為一個矩形的「盒模型」,而每一個盒模型都由四個屬性組成,由內而外分別為內容(content)、內距(padding)、邊界(border)及外距(margin)

閱讀全文 »