DIV CSS 佈局教程網

學 Bootstrap 前該先懂的事:box-sizing: border-box 到底是什麼
編輯:關於JavaScript     

學 Bootstrap 時常會遇到一些莫名其妙的坑,多半不是 Bootstrap 的問題,而是它預設了某個 CSS 行為,而你還不知道。最典型的就是 box-sizing: border-box。

Bootstrap 一開場就改寫了全域設定

打開 Bootstrap 的 CSS,最前面就有這一段:

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

它對所有元素生效,無所不在。所以你得先知道它改變了什麼。

對照實驗

先看不設 border-box 的一般情況:

<div class="outer" style="width:500px; height:500px; padding:100px;
                          border:1px solid #000; background-color: yellow;">
  <div class="inner" style="width:100%; height:100%; background-color: pink;"</div>
</div>

量出來的結果:outer 實際佔 702 × 702(500 + 100×2 + 1×2),inner 則是 500 × 500。這是 CSS 的預設行為,content-box:width 只管內容區,padding 和 border 另外加在外面。

接著加上 border-box:

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
<div class="outer" style="width:500px; height:500px; padding:100px;
                          border:1px solid #000; background-color: yellow;">
  <div class="inner" style="width:100%; height:100%; background-color: pink;"</div>
</div>

結果變成:outer 就是 500 × 500,而 inner 縮成 298 × 298。

padding 和 border 跑到哪去了?

答案是:跑到裡面去了。

border-box 的定義是:width 包含 content + padding + border。所以 outer 的 500px 要扣掉左右各 100px 的 padding(共 200)與左右各 1px 的 border(共 2),內容區只剩下 500 − 200 − 2 = 298px。inner 設 width: 100% 自然就是 298。

打開開發者工具的 Computed 面板會看得很清楚:padding 與 border 都確實存在、都生效了,只是它們佔走的是元素內部的空間,而不是向外撐大。

為什麼這個設計其實更好用

傳統的 content-box 有個很惱人的特性:寬度不可預測。你寫 width: 33.33% 想做三欄,一旦加上 padding,每欄就會變寬,三欄加起来超過 100% 而換行。border-box 讓「你寫的寬度就是最終佔的寬度」,排版計算直觀得多——這也是它和柵格系統是天生一對的原因。

一個具體的對照

<!DOCTYPE html>
<html>
<head>
<title>box-sizing</title>
<style type="text/css">
.testdiv {
    padding: 10px;
    width: 100px;
    border: 10px solid;
}
</style>
</head>
<body>
<div class="testdiv">普通</div>
<div class="testdiv" style="-webkit-box-sizing: border-box;">特殊</div>
</body>
</html>

上面那個 div 實際佔 140px 寬(100 + 10×2 + 10×2),下面那個就是 100px——padding 與 border 都收在 100px 以內。

順帶一提

如果你有舊版 IE 的開發經驗,會發現 border-box 就是當年 IE 的「怪異模式」(quirks mode)行為。當年我們花很多力氣用 hack 去對抗它,現在它反倒成了我們主動開啟的預設值,也算有趣的一段歷史。

今天不需要再寫 -webkit- 與 -moz- 前綴了,box-sizing 已經是全面支援的標準屬性。Bootstrap 4/5 也同樣保留了這段全域設定,所以理解它,等於理解了 Bootstrap 排版背後最重要的一條規則。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved