gpt4 book ai didi

css - 填充会增加元素的大小是否有原因?

转载 作者:数据小太阳 更新时间:2023-10-29 09:15:49 32 4
gpt4 key购买 nike

当我发现 <div>如果你给它 10px 的填充,大小为 - 比如说 - 200px 变成 220px 宽。这对我来说毫无意义,当内部设置改变时外部尺寸不应该改变。每次调整填充时,它都会强制您调整大小。

我是不是做错了什么,或者这种行为有什么原因吗?

编辑:我知道这是它应该如何工作的,我的问题是为什么?我不明白这是合乎逻辑的吗?与保持大小和填充分开的相反方法相比,这是否有任何优势?

最佳答案

有两种不同的所谓“框模型”,一种将填充(和边框)添加到指定的 width,而另一种则不添加。随着 CSS3 的出现,您可以幸运地在两种模型之间切换。更准确地说,您正在寻找的行为可以通过指定来实现

box-sizing: border-box;
ms-box-sizing: border-box;
webkit-box-sizing: border-box;
moz-box-sizing: border-box;
width: 200px;

在您的 div 的 CSS 中。然后,在现代浏览器中,无论如何,div 将始终保持 200 像素宽。有关更多详细信息和支持的浏览器列表,请参阅 this guide .

编辑:WRT 关于为什么传统盒子模型是原样的编辑,维基百科实际上 offers some insight :

Before HTML 4 and CSS, very few HTML elements supported both border and padding, so the definition of the width and height of an element was not very contentious. However, it varied depending on the element. The HTML width attribute of a table defined the width of the table including its border. On the other hand, the HTML width attribute of an image defined the width of the image itself (inside any border). The only element to support padding in those early days was the table cell. Width for the cell was defined as "the suggested width for a cell content in pixels excluding the cell padding."

CSS introduced margin, border and padding for many more elements. It adopted a definition width in relation to content, border, margin and padding similar to that for a table cell. This has since become known as the W3C box model.

关于css - 填充会增加元素的大小是否有原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2196614/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com