我记得我之前在网上有查到,如果在CSS属性里面声明一个值可以使得外边距,内边距和框的数值是计算在盒的高度和宽度里面的,但我忘记这个属性和这个值是什么了?求高手告知。

还有我想问为什么CSS默认外边距,内边距和框的值要独立出来,不算在盒的高度和宽度里面?这样有什么好处吗?


回复讨论(解决方案)

box-sizing 设为 content-box 时, height 和 width 只包含内容, 不含 padding 和 border
设为 border-box 时, height 和 width 包含 padding 和 border

你看看 W3C 官方的文档:

http://www.w3.org/TR/css3-ui/#box-sizing

content-box
This is the behavior of width and height as specified by CSS2.1. The specified width and height (and respective min/max properties) apply to the width and height respectively of the content box of the element. The padding and border of the element are laid out and drawn outside the specified width and height.
border-box
Length and percentages values for width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified width and height properties. As the content width and height cannot be negative ([CSS21], section 10.2), this computation is floored at 0. Used values, as exposed for instance through getComputedStyle(), also refer to the border box.

还有我想问为什么CSS默认外边距,内边距和框的值要独立出来,不算在盒的高度和宽度里面?这样有什么好处吗?



如果我想要明确的设置内容的 height 和 width, 但 css 的 height 和 width 这两个属性却始终把 padding 和 border 的尺寸都包含在其中, 那我设置时不就是得先计算才能设置好吗
比如

$(element).css('width', 内容期望的宽度 + padding-left + padding-right + border-left + border-right);

这样岂不是相当麻烦吗, 而且如果 padding-left , padding-right , border-left, border-right 之中的任意一个发生改变时, 都将影响到 内容的宽度

还有我想问为什么CSS默认外边距,内边距和框的值要独立出来,不算在盒的高度和宽度里面?这样有什么好处吗?



如果我想要明确的设置内容的 height 和 width, 但 css 的 height 和 width 这两个属性却始终把 padding 和 border 的尺寸都包含在其中, 那我设置时不就是得先计算才能设置好吗
比如

$(element).css('width', 内容期望的宽度 + padding-left + padding-right + border-left + border-right);

这样岂不是相当麻烦吗, 而且如果 padding-left , padding-right , border-left, border-right 之中的任意一个发生改变时, 都将影响到 内容的宽度



非常感谢。

09-15 19:54