html - float 元素中的相对填充 : why does it work this way?

标签 html css

所以我了解如何处理以下问题,但我真的很想了解为什么会发生这种情况的背后的基本逻辑。

此场景假设您有 2 个 float div(一个在左侧,一个在右侧),每个占据页面的 50%。如果您这样设置它们:

.left {
    background-color: #CCFFCC;
    width: 50%;
    float: left;
}

.right {
    background-color: #FFFFCC;
    width: 50%;
    float: right;
}

div 彼此相邻,占页面总数的 100%。

但是如果你这样设置它们:

.left {
    background-color: #CCFFCC;
    width: 50%;
    float: left;
    padding: 10%;
}

.right {
    background-color: #FFFFCC;
    width: 50%;
    float: right;
    padding: 10%;
}

右边的元素滑到左边的下面。

我知道有几种方法可以解决这个问题,包括 box-sizing 属性,但我真正想知道的是为什么会发生这种情况。

根据盒子模型,padding 被添加到 div 的内部(我认为这会使 div 的整体大小与以前相同),但添加 padding 实际上是增加了div 的总体大小。

非常感谢任何帮助!

编辑: 我现在看到实际宽度 =

width + padding + border = actual width of an element

(感谢 NewsletterPoll!)

我想我只是对如何应用填充有一个根本性的误解。我的直觉 react 是假设填充基本上会从内容区域中减去,但事实并非如此,我现在明白了。

这可能是没人能回答的问题,但为什么它会如此不直观地构建成这样呢?基本上 width =/= 实际宽度,这看起来很困惑。我想知道在过去是否添加了填充作为事后的想法,或者他们是否可能只是以这种方式开始创建它?

这可能更像是对整个 CSS 及其开发方式的批评,背后可能没有任何实际原因。但是,如果它没有减去内容区域的原因,那可能会很有趣或有助于了解。

最佳答案

发生这种情况是因为 box-sizing 的默认值是 content-box。 在此框大小调整模式下,宽度计算如下:

actual width = width + padding + border

因此您的元素具有 CSS 属性

width: 50%;
padding: 10%;

最终宽度为 70% (10 + 50 + 10)。

| 10% |    50%    | 10% |

并且 2 个 70% 宽的元素不能彼此相邻。


来自 MDN : box-sizing :

content-box

This is the default style as specified by the CSS standard. The width and height properties are measured including only the content, but not the padding, border or margin. Note: Padding, border & margin will be outside of the box e.g. IF .box {width: 350px}; THEN you apply {border: 10px solid black;} RESULT {rendered in the browser} .box {width: 370px;}


你原来的说法其实是正确的:

"According to the box model, the padding gets added to the inside of a div"

div 中的填充 ,但是 box-sizing:content-box 中的 width CSS 属性告诉浏览器什么div 内“内容区域”的宽度应该是。那么实际的 div 就是 padding、border 和 content area 的组合。 (换句话说,你是说内容区域是 50% 宽,而不是 div 是 50% 宽)

关于html - float 元素中的相对填充 : why does it work this way?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33045741/

相关文章:

html - 如何设置仅覆盖其 50% 的 div 框的背景图像?

javascript - Youtube 有趣的页面加载方法

css - 视频应触及框的顶部和底部

html - 如何将此图像定位在页面的底部中心?

html - 如何制作 HTML/CSS/JS 变色背景(就像 Kahoot.it 有的那样)

html - 将 li 放在特定高度后的下一列

javascript - 移动棋子的位置

Java - 让java程序在网页上运行

html - IMAGE 未显示,但路径正确等

css - Meteor.js 上的 Stylus 库