According to the standard, adding padding to a HTML element in CSS will grow the element by the amount defined. For example:
根据标准,将填充添加到CSS中的HTML元素将使元素按定义的量增长。例如:
.elem {
width: 100px;
height: 100px;
padding: 20px;
}
will add 20 pixels to the .elem's sides, causing the actual width and height to be 140px total.
将向.elem的两侧添加20个像素,使实际宽度和高度总计为140px。
Since this is actually pretty impractical in web design (having to calculate and keep track of the resulting sizes), I was wondering if it was somehow possible to do the reverse instead. I set a padding, and the inner text area shrinks instead. So the element stays at 100*100px, has the padding of 20px inside it, and I don't have to worry about messing up my design while experimenting with the padding.
由于这在网页设计中实际上是不切实际的(必须计算和跟踪结果大小),我想知道是否有可能以相反的方式进行反向操作。我设置了一个填充,内部文本区域缩小了。所以元素保持在100 * 100px,内部填充20px,我不必担心在试验填充时弄乱我的设计。
Is this possible? Perhaps through a language that compiles to CSS (haven't looked into that much)? And perhaps a more minor question: why does it work this way in the first place?
这可能吗?也许是通过一种编译成CSS的语言(没有考虑过那么多)?也许是一个更小的问题:为什么它首先以这种方式工作?
2 个解决方案
#1
3
Use box-sizing
:
elemSelector {
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
This value for the property declares that the declared size of the element will include the border
and the padding
.
该属性的值声明元素的声明大小将包括边框和填充。
References:
-
box-sizing
at: 'CSS Basic User Interface Module Level 3 (CSS UI)'. -
box-sizing
at MDN.
box-sizing at:'CSS基本用户界面模块3级(CSS UI)'。
MDN的盒子大小。
#2
0
It is currently impossible to perform what you are after. You'll have to account for padding in total width before you attempt to define what your css 'width' value will be. For more information on this, see the CSS Box Model. This is the only method to guarantee correct sizing in all web-capable devices, CSS3 compatible and not.
目前无法执行您所追求的目标。在尝试定义css的“宽度”值之前,您必须考虑总宽度的填充。有关此内容的更多信息,请参阅CSS Box模型。这是保证在所有支持Web的设备中正确调整大小的唯一方法,CSS3兼容与否。
#1
3
Use box-sizing
:
elemSelector {
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
This value for the property declares that the declared size of the element will include the border
and the padding
.
该属性的值声明元素的声明大小将包括边框和填充。
References:
-
box-sizing
at: 'CSS Basic User Interface Module Level 3 (CSS UI)'. -
box-sizing
at MDN.
box-sizing at:'CSS基本用户界面模块3级(CSS UI)'。
MDN的盒子大小。
#2
0
It is currently impossible to perform what you are after. You'll have to account for padding in total width before you attempt to define what your css 'width' value will be. For more information on this, see the CSS Box Model. This is the only method to guarantee correct sizing in all web-capable devices, CSS3 compatible and not.
目前无法执行您所追求的目标。在尝试定义css的“宽度”值之前,您必须考虑总宽度的填充。有关此内容的更多信息,请参阅CSS Box模型。这是保证在所有支持Web的设备中正确调整大小的唯一方法,CSS3兼容与否。