天天看點

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 edge, padding edge, border edge, and margin edge.

CSS盒模型有四條邊:外邊距邊、邊框邊、内填充邊、内容邊(Content edge、Padding edge、Border edge和Margin edge),四條邊由内到外把它劃分為四個區域:内容區域、内邊距區域、邊框區域、外邊距區域(Content area、Padding area、Border area和Margin area)。

CSS 盒模型與box-sizing
  • 内容區域(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的計算方式)。

CSS 盒模型與box-sizing

補充: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 也是可以的。

轉載于:https://www.cnblogs.com/guolao/p/9088465.html