盒模型 box-sizing 属性

css3增添了盒模型box-sizing属性box-sizing属性值可以有下面三个

content-box默认值,让元素维持W3C的标准盒模型。元素的宽度/高度(width/height)(所占空间)等于元素边框宽度(border)加上元素内边距(padding)加上元素内容宽度 /高度content width/height)即:Element Width/Height = border+padding+content width/height

border-box:让元素维持IE6及以下版本盒模型元素的宽度/高度(所占空间)等于元素内容的宽度/高度

这里的content width/height包含了元素的border,padding,内容的width/height。即:Element Width/Height =width /height-border-padding

inherit继承父元素的盒模型模式。

 具体适用场景:

<div class="wrapper">
    <div id="header">页眉</div>
    <div class="sidebar">侧边栏</div>
    <div class="content">内容内容内容内容内容内容内容内容内容内容内容</div>
    <div id="footer">页脚</div></div>
 
 

        *{margin: 0;padding: 0;}
        .wrapper{
            width: 500px;
            margin: 0 auto;
            color:#fff;
            text-align: center;
        }
        #header{
            height: 50px;
            background-color: red;
        }
        .sidebar{
            float: left;
            width: 150px;
            height: 100px;
            background-color: #0099cc;
        }
        .content{
            float: left;
            width: 350px;
            height: 100px;
            background-color: #999999;
        }
        #footer{
            background-color: #ff6600;
            height: 50px;
            clear: both;
        }

但如果又被要求改好看点,比如内容区加内边距边框什么的修饰一下。

如果直接加上paddingborder什么的,马上就破坏了布局

 

因为box-sizing默认是content-box,内容区大小不会变,加上paddingmarginborder的话,就会往外撑开,从而破坏布局结构

这时,使用border-box就可以完美解决了

 .content{
            box-sizing: border-box;
            padding: 22px;
            border: 12px solid blue;
            float: left;
            width: 350px;
            height: 100px;
            background-color: #999999;
        } 

这样,元素所占空间不会变,加了paddingborder的话,会往内挤,保持外面容器不被破坏

(注意,margin不包含在元素空间,加了margin会向外撑开

 

猜你喜欢

转载自www.cnblogs.com/expedition/p/11296281.html