zoukankan      html  css  js  c++  java
  • css3使用box-sizing布局

    css3增添了盒模型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;
            }

    效果图    

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

    如果直接加上padding、border什么的,马上就破坏了布局:

     

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

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

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

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

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

    效果图:

     兼容性:IE8+及其他主流浏览器均支持box-sizing。其中IE6及以下默认是以类似border-box盒模型来计算尺寸。

     (ps:Firefox浏览器,box-sizing还可以设置一个padding-box,指定元素的宽度/高度等于内容的宽度/高度和內距,

       即:Element Width/Height = content width/height+padding

  • 相关阅读:
    我的vimrc设置
    nginx
    选中
    vscode垂直选中列选中
    lsof
    bashrc和bash_profile
    centos安装tree命令
    linux查看磁盘大小df命令
    linux查看文件夹大小du命令
    git本地推送远程
  • 原文地址:https://www.cnblogs.com/ooooevan/p/5470982.html
Copyright © 2011-2022 走看看