美文网首页
CSS 盒模型、解决方案

CSS 盒模型、解决方案

作者: 滚石_c2a6 | 来源:发表于2018-05-04 20:29 被阅读5次

    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/

    相关文章

      网友评论

          本文标题:CSS 盒模型、解决方案

          本文链接:https://www.haomeiwen.com/subject/brjjrftx.html