盒子模型
盒子模型表示一個元素佔據範圍
觀察方式:
Chrome Developer Tool > Elements > Computed
組成:
content > padding > border > margin
內容 content
除了內容文字本身外,寬度(
width
)與高度(height
)兩個屬性也會影響
寬度 width
.w-100 {
width: 100px;
}
數值由一個數字與一個單位組成,像素(px
)表示固定單位
高度 height
.h-100 {
height: 100px;
}
數值由一個數字與一個單位組成,像素(px
)表示固定單位
建立一個正方形
.cube {
width: 100px;
height: 100px;
background: #000;
color: #fff;
}
行高 line-height
.nh-100 {
line-height: 100px;
}
當行高與高度數值一樣時,會產生垂直置中的效果
換行觸發條件:
- 多個區塊元素
<br/>
換行元素- 內容超過元素本身寬度
使用行高要注意破版問題
文字顏色 color
.color-red {
color: red;
}
.color-custom {
color: #dedede;
}
使用個別顏色的英文名稱,或使用十六進制的色碼皆可 (#dedede
)
文字大小 font-size
.fs-18 {
font-size: 18px;
}
數值由一個數字與一個單位組成,像素(px
)表示固定單位
文字線條 font-weight
.fw-100 {
font-weight: 100;
}
.fw-900 {
font-weight: 900;
}
100 線條最細,900 線條最粗
不可以帶單位,例如
100px
這樣是錯誤的
水平對齊
.text-left {
text-align: left;
}
.text-center {
text-align: center;
}
.text-right {
text-align: right;
}
預設是 left
背景顏色 background-color
.bg-red {
background-color: red;
}
背景圖片 background-image
.bg-image {
background-image: url(images/some.png);
}
使用 url
抓取目標圖片
當圖片小於元素寬高時,會自動重複顯示
使用 background-repeat: no-repeat;
來取消重複
.bg-image {
background-image: url(images/some.png);
background-repeat: no-repeat;
}
內距 padding
content 與 border 之間的距離
.pt-20 {
padding-top: 20px;
}
.pe-20 {
padding-right: 20px;
}
.pb-20 {
padding-bottom: 20px;
}
.ps-20 {
padding-left: 20px;
}
.p-20 {
padding: 20px;
}
.p-20-40 {
padding: 20px 40px;
}
.p-custom {
padding: 10px 20px 30px 40px;
}
padding: 20px
表示『上下左右』都是 20px
padding: 20px 40px
表示『上下』是 20px
,『左右』是 40px
padding: 10px 20px 30px 40px
表示『上』『右』『下』『左』分別為 10px
20px
30px
40px
邊匡 border
.border {
border-width: 3px;
border-color: #000000;
border-style: solid;
/* border: 3px solid #000000; */
}
.border-radius {
border-top-right-radius: 10px;
border-top-left-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
/* border-radius: 10px; */
}
border: 3px solid #000000;
等同三個屬性合併宣告
border-radius: 10px;
倒圓角
畫圓圈
.circle {
width: 100px;
height: 100px;
border-radius: 100px;
}
條件:
- 正方型
- 倒圓角數據大於等於寬高
外距 margin
border 與其他區塊之間的距離
.mt-20 {
margin-top: 20px;
}
.me-20 {
margin-right: 20px;
}
.mb-20 {
margin-bottom: 20px;
}
.ms-20 {
margin-left: 20px;
}
.m-20 {
margin: 20px;
}
.m-20-40 {
margin: 20px 40px;
}
.m-custom {
margin: 10px 20px 30px 40px;
}
margin: 20px
表示『上下左右』都是 20px
margin: 20px 40px
表示『上下』是 20px
,『左右』是 40px
margin: 10px 20px 30px 40px
表示『上』『右』『下』『左』分別為 10px
20px
30px
40px
將左右外距設為
auto
,區塊會水平置中
計算模式 box-sizing
.block {
width: 200px;
height: 100px;
padding: 20px;
border: 2px solid #000;
}
明明設定了寬 200 高 100,但是卻沒有如預期的寬高顯示?
content-box
預設計算模式為 content-box
,此模式下內容寬高計算公式為
content + padding + border
帶入上面的範例得出寬高
寬 = 200 + (20 * 2) + (2 * 2) = 244
高 = 100 + (20 * 2) + (2 * 2) = 144
如此計算方式,在排版上造成很大的困擾(每次異動都要計算)
border-box
計算模式改為 border-box
,此模式下寬高計算公式為
content = width - padding - border
表示設定寬高後,content
可用範圍為扣除 padding
與 border
如此,寬高就不會異動
.border-box {
box-sizing: border-box;
}