浅谈CSS3中的box-sizing(content-box与border-box)


CSS3中的box-sizing 属性允许以特定的方式来指定盒模型,有两种方式:

  • content-box:标准盒模型,又叫做 W3C盒模型,一般在现代浏览器中使用的都是这个盒模型
  • border-box:怪异盒模型,低版本IE浏览器中的盒模型

现代浏览器和IE9+默认值是content-box。
语法格式:

box-sizing:content-box | border-box

 

这里写图片描述
区别:

  • content-box:padding和border不被包含在定义的width和height之内。
    盒子的实际宽度=设置的width+padding+border
  • border-box:padding和border被包含在定义的width和height之内。
    盒子的实际宽度=设置的width(padding和border不会影响实际宽度)

我们新建一个HTML页面来详细解释

div{ height:200px; width:200px; background:green; margin:50px; border:20px solid black; padding:20px; } .div1{ box-sizing:content-box; } .div2{ box-sizing:border-box; }

 

javascript代码:

<script> var div =document.getElementsByTagName("div"); console.log("content-box宽度="+div[0].offsetWidth); console.log("border-box宽度="+div[1].offsetWidth); </script>

 

运行结果:
这里写图片描述

—————————————————————————————
分析:

这里写图片描述


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM