html - 为什么这个 div 的背景应该完全由其内容填充时却显示在顶部?

标签 html css

我有一个 div 包含另一个包含 inputdiv。外部 div 从内部 div 获取高度,内部 divinput 获取高度。 div 上没有填充或边距。我已经从输入中删除了边框。为什么外部 div 的红色背景在顶部显示了一个像素?当 input 具有 padding: 0 时,为什么它会变得更糟? (使用复选框进行尝试。)

我已经将它与 inputborder: none 风格隔离开来(删除红色条),但我想了解 < em>为什么它有这种效果(在 Chrome 和 Firefox 上)。

document.querySelector("input[type=checkbox]").addEventListener("click", function() {
  document.querySelector("input[type=text]").classList.toggle("zero-padding", this.checked);
});
body {
    box-sizing: border-box;
}
.outer {
    display: inline-block;
    width: 5em;
    border: 1px solid black;
    background: red;
    /* divs don't have padding or margin by default, but I did try this just in case
    padding: 0;
    margin: 0;
    */
}
.inner {
    /* divs don't have padding or margin by default, but I did try this just in case
    padding: 0;
    margin: 0;
    */
}
.inner input {
    border: none;
    border-radius: 0;
    width: 100%;
    margin: 0;
    background: white;
}
.zero-padding {
  padding: 0;
}
<div class="outer"><div class="inner"><input type="text"></div></div>
<div>
  <label>
    <input type="checkbox"> Add <code>padding: 0</code> to the <code>input</code>
  </label>
</div>

我在 Linux 上的 Chrome v58 上的结果:

Result on Chrome

我在 Linux 上的 Firefox v53 上的结果:

Result on Firefox

最佳答案

那些 div 默认属性,例如字体大小、行高。我通过将“外部”div 的行高设置为 0 解决了这个问题;

document.querySelector("input[type=checkbox]").addEventListener("click", function() {
  document.querySelector("input[type=text]").classList.toggle("zero-padding", this.checked);
});
body {
    box-sizing: border-box;
}
.outer {
    display: inline-block;
    width: 5em;
    border: 1px solid black;
    background: red;
    line-height: 0;
    /* divs don't have padding or margin by default, but I did try this just in case
    padding: 0;
    margin: 0;
    */
    
}
.inner {
    /* divs don't have padding or margin by default, but I did try this just in case
    padding: 0;
    margin: 0;
    */
}
.inner input {
    border: none;
    border-radius: 0;
    width: 100%;
    margin: 0;
    background: white;
}
.zero-padding {
  padding: 0;
}
<div class="outer"><div class="inner"><input type="text"></div></div>
<div>
  <label>
    <input type="checkbox"> Add <code>padding: 0</code> to the <code>input</code>
  </label>
</div>

关于html - 为什么这个 div 的背景应该完全由其内容填充时却显示在顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789790/

相关文章:

html - 具有固定标题的表 - tbody 在我的表中溢出了 thead

html - 纯 CSS 下拉问题

HTML/CSS 内容最大高度

css - Chrome 对 margin-top 的解释与 Firefox 不同

jquery - 谷歌地图在 Bootstrap 3.0 模式中未完成加载

html - 从右中间开始带图标的数字

javascript - HTML5 Canvas 全尺寸

html - 页脚向上推以调整内容 div 中的图像大小

html - 防止控制继续使用表单内联

javascript - 如何使用 JQuery 检测 • 符号并将它们转换为 HTML ul