【问题标题】:Why are two inputs within an inline-block element twice as long as one input?为什么内联块元素中的两个输入是一个输入的两倍?
【发布时间】:2021-12-27 15:58:57
【问题描述】:

假设我有这个代码:

div {
  display: inline-block;
}

input {
  width: 100%;
}

section {
  margin-block: 20px;
}
<section>
  <div>
    <input/>
    <input/>
  </div>
</section>

<section>
  <div>
    <input/>
  </div>
</section>

第一部分的长度大约是第一部分的两倍,但为什么呢?我试图理解为什么会这样。如果我放置 inline-block div 而不是输入,也会发生同样的事情。

【问题讨论】:

  • 第一次输入后添加
  • @DCR 有效,但为什么呢?
  • 你应该将显示内联块添加到你的输入而不是 div
  • 我将 inline-block 放入 div 以模拟我拥有的实际代码(一个没有设置宽度的固定模态窗口,因此它的宽度就是其中的内容)。

标签: html css


【解决方案1】:

NB - 我认为这是一个骗局......如果我找到一个我会删除这个答案并关闭这个问题,但现在,我正在为你提供一个答案。

通常,div 是 block 元素,输入是 inline 元素,因此根据浏览器的大小,它们占据大约 140 像素的长度。因此,两个内联元素通常会并排放置在一个 div 中,并且该 div 将跨越其容器的整个长度。请参阅边框以了解我的意思:

section {
    margin-block: 20px;
}

div {
    border: 1px solid red; /* for illustration purposes */
}
<section>
    <div>
        <input>
        <input>
    </div>
</section>
<section>
    <div>
        <input>
   </div>
</section>

但是,您将 div 设置为 inline-block,这自然会改变事物的显示方式:

section {
    margin-block: 20px;
}

div {
    display: inline-block;
    border: 1px solid red; /* for illustration purposes */
}
<section>
    <div>
        <input>
        <input>
    </div>
</section>
<section>
    <div>
        <input>
   </div>
</section>

现在,完成图片的第二件事是将输入元素设置为占容器宽度的 100%。只是它没有做你期望它做的事情......因为输入是inline元素并且包含div是inline-block,包含div将保持两个输入的大小并排 -一边。

您可以在此处看到它保持其大小的插图,即使输入设置为 width: 25% 每个也是如此(删除了一些 HTML 空格以使输入更清楚地占用水平空间的 50%) :

section {
    margin-block: 20px;
}

div {
    display: inline-block;
    border: 1px solid red; /* for illustration purposes */
}

input {
    width: 25%;
}
<section>
    <div>
        <input><!-- this comment is just here to remove the inherent whitespace between the two inputs
     --><input>
    </div>
</section>
<section>
    <div>
        <input>
   </div>
</section>

当您的内联内容超出宽度时会发生什么?它换行到下一行,并且元素的高度增加以适应新行:

section {
    margin-block: 20px;
}

div {
    display: inline-block;
    border: 1px solid red; /* for illustration purposes */
}

input {
    width: 100%;
}
<section>
    <div>
        <input>
        <input>
    </div>
</section>
<section>
    <div>
        <input>
   </div>
</section>

【讨论】:

猜你喜欢
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多