W3C 標(biāo)準(zhǔn)盒模型 & IE 怪異盒模型
頁面上顯示的每個(gè)元素(包括內(nèi)聯(lián)元素)都可以看作一個(gè)盒子,即盒模型( box model )
盒模型由 4 部分組成堡距,從內(nèi)到外分別是:content padding border margin
W3C 標(biāo)準(zhǔn)盒模型一個(gè)元素的寬度(高度以此類推)應(yīng)該這樣計(jì)算:
一個(gè)元素的寬度 = content
盒子總寬度 = margin-left + border-left + padding-left + width + padding-right + border-right + margin-right
而IE 怪異盒模型一個(gè)元素的寬度(高度以此類推)卻是這樣計(jì)算的:
一個(gè)元素的寬度 = content + padding + border
盒子總寬度 = margin-left + width + margin-right
// W3C 標(biāo)準(zhǔn)盒模型(瀏覽器默認(rèn))
box-sizing: content-box;
// IE 怪異盒模型
box-sizing: border-box;
當(dāng)我們?cè)O(shè)置 box-sizing: border-box;
時(shí)甲锡,border
和 padding
就被包含在了寬高之內(nèi),和 IE 盒模型是一樣的羽戒。
所以缤沦,為了避免你同一份 css 在不同瀏覽器下表現(xiàn)不同,最好加上:
\*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
JS 如何獲取盒模型對(duì)應(yīng)的寬和高
let box = document.getElementById('box')
// 只能取到內(nèi)聯(lián)樣式的寬高
console.log('style:' + box.style.width) // 100px
// 內(nèi)聯(lián)樣式和外聯(lián)樣式的寬高都能取到易稠,但只有 IE 支持
console.log('currentStyle:' + box.currentStyle.width) // 100px
// 內(nèi)聯(lián)樣式和外聯(lián)樣式的寬高都能取到缸废,幾乎所有主流瀏覽器都支持
console.log('getComputedStyle:' + getComputedStyle(box).width) // 100px
// 內(nèi)聯(lián)樣式和外聯(lián)樣式的寬高都能取到,幾乎所有主流瀏覽器都支持缩多,取到的是盒子總寬度
console.log('getBoundingClientRect:' + box.getBoundingClientRect().width) // 210
轉(zhuǎn)自: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.