CSS相关疑问-01

盒子(或者元素)所占页面空间是否将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.
    图例:
    标准盒子模型图例

标准盒子模型-margin

  • 替代(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.
    图例:
    IE盒子模型图例
  • 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):
在这里插入图片描述

以上为笔者个人拙见,还请指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值