CSS盒子模型

2018-12-20  本文已影响0人  住在醉翁亭边

1. 什么是CSS盒子模型

When laying out a document, the browser's rendering engine represents each element as a rectangular box according to the standard CSS basic box model. CSS determines the size, position, and properties (color, background, border size, etc.) of these boxes.Every box is composed of four parts (or areas), defined by their respective edges: the content edge, padding edge, border edge, and margin edge.

这个是MDN 上的解释。我的理解是浏览器渲染引擎会将元素描述成一个由margin,border,padding,content组成的矩形盒子,css决定了这个盒子的尺寸,位置和属性(color,background...)。

2. 盒子的组成

在chrome调试面板中,选择元素后可以很清楚的看到该元素的盒子。图中的右下角和左边选中的高亮都可以看到。


20181220101118.jpg

3. 用css的width和height设置宽度

这里的width和height设置的就是content。
标准模式下设置了width和height之后,盒子的尺寸是border+padding+content+margin。这里的content的宽高就是css的width和height。


20181220103052.jpg

IE<6的浏览器的怪异模式下,盒子的尺寸是width和height+margin,此时content=width - border- padding,也就是设置的width和height会将border和padding也包含在内。

2018122010305.jpg

3. css3的box-sizing属性

box-sizing主要有两个属性content-box和border-box。
而这两个属性分别对应了上面的标准模式和非标准模式。
当我们想给一个元素加padding和border但又想让元素的宽度不被撑开,设置box-sizing:border-box;就可以了,这样width的宽度就会包含padding和border。元素的尺寸还会保持为width。

上一篇下一篇

猜你喜欢

热点阅读