CSS之盒模型

127 阅读1分钟

CSS之盒模型

盒模型

盒子结构

在html中,每一个元素都是以盒子的形式存在。这样设计的好处在于,简单直观,dom树实现起来容易。

那么盒子到底是什么样的呢?下面有一段代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .box {
        display: inline-block;
        width: 200px;
        height: 200px;
        padding: 10px;
        border: 10px solid salmon;
    }
</style>
<body>
    <div class="box" ></div>
</body>
</html>

用浏览器打开这个html文件我们可以看到一个红格子

image.png

打开开发者工具:Elements

虽然我们表面上只能看到一层红格子,但是实际上这个盒子被分成了多层。

从外到内依次是margin(外间距)、border(边框)、padding(内间距)和content(内容)。

通过调整这四个部分的内容,我们可以很轻松的调整元素的大小以及相互之间的距离。

image.png

盒模型

解释完一般盒子的构成我们再来说一下盒模型,盒模型之间的不同之处在于width和height控制的部分不同。可以通过css中的box-sizing进行控制,默认情况下为content-box。

分类:

IE盒模型(border-box) : width和height包括border,padding,content

W3C标准模型(content-box) : width和height包括content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .box {
        display: inline-block;
        width: 200px;
        height: 200px;
        padding: 10px;
        border: 10px solid salmon;
    }
    .content {
        box-sizing: content-box;
    }
​
    .border {
        box-sizing: border-box;
    }
</style>
<body>
    <div class="box content" >content-box</div>
    <div class="box border" >border-box</div>
</body>
</html>

image.png

从图中可以很明显的发现同样设置为200px的盒子大小完全不一样。

content-box:

image.png

border-box:

image.png

观察两者的盒模型发现,content-box的content=width,border-box的content+padding+border=width

至此,两者的的区别介绍完毕。