元素(任何元素,浮动或不浮动)占用的总空间如下:
totalWidth = contentWidth + margin + border + padding
width使用CSS 指定属性时,只需设置contentWidth上述等式.
例如,如果您尝试将元素放入给定的空间量,则需要考虑所有宽度因子,而不仅仅是一个.因此,如果您只有200px的空间,并且您希望内容周围有5px的边距,1px的边框和10px的填充,则必须按如下方式工作:
contentWidth = availableWidth - margin - border - padding
contentWidth = 200px - (2x5px) - (2x1px) - (2x10px)
contentWidth = 200px - 10px - 2px - 20px
contentWidth = 168px
**note that the (2xNN) refers to the fact that you have to
consider both the impact to both the left and right side
of the element in the total.
Run Code Online (Sandbox Code Playgroud)
因此,在CSS中,您可以将元素设置为:
width: 168px;
border: 1px <color> <type>;
padding: 10px;
margin: 5px;
Run Code Online (Sandbox Code Playgroud)
这就是W3C(即标准)盒子模型的工作原理.您可以强制使用其他框模型,使用box-sizingCSS属性定义框模型的工作方式,但应尽可能使用标准框模型.