CSS 盒模型与box-sizing

一、盒模型

一个web页面由许多html元素组成,而每一个html元素都可以表示为一个矩形的盒子,CSS盒模型正是描述这些矩形盒子的存在。

MDN的描述:

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 edgepadding edgeborder edge, and margin edge.

CSS盒模型有四条边:外边距边、边框边、内填充边、内容边(Content edge、Padding edge、Border edge和Margin edge),四条边由内到外把它划分为四个区域:内容区域、内边距区域、边框区域、外边距区域(Content area、Padding area、Border area和Margin area)。

box_model

  • 内容区域(content area )是包含元素真实内容的区域。
  • 内边距区域(padding area) 延伸到包围padding的边框。如果content area设置了背景、颜色或者图片,这些样式将会延伸到padding上。
  • 边框区域(border area )是包含边框的区域,扩展了内边距区域。
  • 外边距区域(margin area)用空白区域扩展边框区域,以分开相邻的元素。

通过CSS属性(width、height、padding、border和margin)来控制它们的尺寸。

二、box-sizing(css3属性)

1.box-sizing的值

1 /* 关键字 值 */
2 box-sizing: content-box;/*默认值*/
3 box-sizing: border-box;
4 
5 /* 全局 值 */
6 box-sizing: inherit;
7 box-sizing: initial;
8 box-sizing: unset;

2.box-sizing的作用

box-sizing的作用就是告诉浏览器,使用的盒模型是W3C盒模型,还是IE盒模型。

a.当 box-sizing 的值为 content-box(默认值) 时,其尺寸计算公式为:

width = content-width;
height = content-height;

b.当 box-sizing 的值为 border-box 时,其尺寸计算公式为:

width = content-width + padding-left + padding-right + border-left-width + border-right-width;
height = content-height + padding-top + padding-bottom + border-top-height + border-bottom-height;

无论取何值,盒子尺寸是一样的,改变的是盒子的容量(盒子内部的width和height的计算方式)。

w3c_and_ie_box_model

补充:IE6、7为W3C盒模型。

3.对于box-sizing属性值的选择

在项目里,究竟该使用哪种盒模型?我也不知道啊

在MDN上有这样一句话:

Some experts recommend that web developers should consider routinely applying box-sizing: border-box to all elements.

一些专家甚至建议所有的Web开发者们将所有的元素的 box-sizing 都设为 border-box。

Twitter的开源框架Bootstrap3就全局设置了box-sizing: border-box,由此可见IE盒模型的是比较受欢迎的。

补充:

W3C在CSS3中,加入了 calc() 函数。

CSS函数calc()可以用在任何一个需要<length><frequency><angle><time><number>、或<integer>的地方。有了calc(),你就可以通过计算来决定一个CSS属性的值了。

/* property: calc(expression) */
width: calc(100% - 80px);

使用 calc() 函数,我们可以在 content-box 里实现 border-box,相对的,在 border-box 里实现 content-box 也是可以的。

posted @ 2018-05-25 14:35  郭佬  阅读(3562)  评论(0编辑  收藏  举报
我终究成长为一个不特别的人