CSS 盒模型、解決方案

W3C 標準盒模型 & IE 怪異盒模型

頁面上顯示的每個元素(包括內聯元素)都可以看作一個盒子,即盒模型( box model )

盒模型由 4 部分組成,從內到外分別是:content padding border margin

W3C 標準盒模型一個元素的寬度(高度以此類推)應該這樣計算:
一個元素的寬度 = content
盒子總寬度 = margin-left + border-left + padding-left + width + padding-right + border-right + margin-right

IE 怪異盒模型一個元素的寬度(高度以此類推)卻是這樣計算的:

一個元素的寬度 =  content + padding + border
盒子總寬度 = margin-left + width + margin-right

// W3C 標準盒模型(瀏覽器默認)

box-sizing: content-box;

// IE 怪異盒模型

box-sizing: border-box;

當我們設置 box-sizing: border-box; 時,borderpadding 就被包含在了寬高之內,和 IE 盒模型是一樣的。

所以,為了避免你同一份 css 在不同瀏覽器下表現不同,最好加上:

\*, *:before, *:after {

-moz-box-sizing: border-box;

-webkit-box-sizing: border-box;

box-sizing: border-box;

}

JS 如何獲取盒模型對應的寬和高
let box = document.getElementById('box')

// 只能取到內聯樣式的寬高
console.log('style:' + box.style.width) // 100px

// 內聯樣式和外聯樣式的寬高都能取到,但只有 IE 支持
console.log('currentStyle:' + box.currentStyle.width) // 100px

// 內聯樣式和外聯樣式的寬高都能取到,幾乎所有主流瀏覽器都支持
console.log('getComputedStyle:' + getComputedStyle(box).width) // 100px

// 內聯樣式和外聯樣式的寬高都能取到,幾乎所有主流瀏覽器都支持,取到的是盒子總寬度
console.log('getBoundingClientRect:' + box.getBoundingClientRect().width) // 210

轉自:http://www.lovebxm.com/2017/08/27/css-box/

Every current browser supports box-sizing: border-box; unprefixed, so the need for vendor prefixes is fading. But, if you need to support older versions of Safari (< 5.1), Chrome (< 10), and Firefox (< 29), you should include the prefixes -webkit and -moz, like this:

html {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
*, *:before, *:after {
  -webkit-box-sizing: inherit;
  -moz-box-sizing: inherit;
  box-sizing: inherit;
  }

box-sizing: border-box; is supported in the current versions of all major browsers. The less-commonly used padding-box is only supported in Firefox at the moment. There's more comprehensive information about browser support in our [box-sizing](https://css-tricks.com/almanac/properties/b/box-sizing/) almanac entry.

There are a few issues with older versions of Internet Explorer (8 and older). IE 8 doesn't recognize border-box on elements with min/max-width or min/max-height (this used to affect Firefox too, but it was fixed in 2012). IE 7 and below do not recognize box-sizing at all, but there's a polyfill that can help.

參考:https://css-tricks.com/box-sizing/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容