盒子(或者元素)所占页面空间是否将margin计算在内?
笔者认为盒子(或者)元素所占页面空间的计算应该如下:
宽度:content`s width + 2 * padding + 2 * border。
高度:content`s height + 2 * padding + 2 * border。
margin 应该为盒子之间的空间。
还是拿熟悉的集装箱举例(标准盒子模型):
一个盒子就是一个集装箱,页面就是一个货船的横切面。
集装箱内货物所占空间横切卖弄即:content。
货物与集装箱内壁的水平距离即:padding。
集装箱四侧壁的厚度即:border。
集装箱与集装箱之间的距离即:margin。
依据如下(部分文字和图片直接取自MDN):
- 标准盒子模型(The standard CSS box model):In the standard box model, if you give a box a width and a height attribute, this defines the width and height of the content box. Any padding and border is then added to that width and height to get the total size taken up by the box.
图例:
- 替代(IE)盒子模型:Using this model, any width is the width of the visible box on the page, therefore the content area width is that width minus the width for the padding and border.
图例:
- The margin is an invisible space around your box. It pushes other elements away from the box. Margins can have positive or negative values. Setting a negative margin on one side of your box can cause it to overlap other things on the page. Whether you are using the standard or alternative box model, the margin is always added after the size of the visible box has been calculated.
- 代码实践中两盒子的 margin 值为两盒子中较大的 margin值,当然 margin 相同值时取同值。
代码示例:
<!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>
div {
width: 200px;
height: 200px;
padding: 30px;
border: 5px solid blue;
background-color: brown;
margin: 50px;
}
p {
width: 200px;
height: 200px;
padding: 30px;
border: 5px solid blue;
background-color: brown;
margin: 40px;
}
</style>
</head>
<body>
<div></div>
<p></p>
</body>
</html>
结果示例(chrome):
以上为笔者个人拙见,还请指正。