盒模型

188 阅读1分钟

盒模型计算

box-sizing属性

将盒子添加了box-sizing:border-box;之后,盒子的width 和 height 数字就表示盒子实际占有的宽高(不含margin)了,即padding、border 变为“内缩 ”的,不再“外扩”。

box-sizing属性大量应用于移动网页制作中,因为它结合百分比布局、弹性布局等非常好用,在PC页面开发中使用较少。兼容到IE9

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin:0;
            padding:0;
        }
        .box {
            box-sizing:border-box;
            width:200px;
            height:200px;
            border: 10px solid #000;
            padding:10px;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

display属性

主要研究块级元素和行内元素

行内元素不能设置宽高,块级元素可以设置宽高,

特殊的行内块元素即能够并排显示也可以设置宽高(例如img标签,input输入框)

块级元素和行内元素的相互转换

使用display:block;即可将元素转为块级元素

使用display:inline;即可将元素转为行内元素,将元素转为行内元素的应用很少见

使用display:inline-block;即可将元素转为行内块元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        a {
            /* 转为块级元素 */
            display:block;
            height:60px;
            width:200px;
            background-color:red;
            text-align:center;
            line-height:60px;
            text-decoration:none;
            margin:20px 0;

        }
        a:hover {
            background-color:blue;
        }
        span {  
            /* 转为行内块元素 */
            display:inline-block;
            width:100px;
            height:25px;
            margin:10px;
       
            padding:10px;
            
            background-color:slateblue;
        }
    </style>
</head>
<body>
    <a href="">我是按钮</a>

    <span>1111111</span>
    <span>222222</span>
    <span>33333333</span>
</body>
</html>

元素的隐藏

使用display:none;可以将元素隐藏,元素将彻底放弃位置,如同没有书写它的标签一样

使用visibility:hidden;也可以将元素隐藏,但使元素不会放弃自己的位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width:200px;
            height:200px;
            background-color:red;
        }
        .box2 {
            width:200px;
            height:200px;
            background-color:rgb(4, 0, 255);
            /* display将盒子二隐藏 直接放弃自己位置*/
            /* display:none; */
            /* 使用visibility:hidden将盒子二隐藏,不放弃自己位置 */
            visibility:hidden;
        }
        .box3 {
            width:200px;
            height:200px;
            background-color:rgb(21, 255, 0);
        }
    </style>
</head>
<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <div class="box3"></div>
</body>
</html>