为什么输入字段的宽度大于其父div?

时间:2019-01-23 22:48:20

标签: css width form-fields

为什么表单输入字段的宽度大于其父div?宽度应用于文本div,但不应用于具有表单字段的div。为什么会这样呢?

See the livecode here.

.parent {
  width: 400px;
  background-color: yellow;
}

.left {
  display: inline-block;
  width: 50%;
  background-color: red
}

.right {
  display: inline-block;
  width: 30%;
  background-color: blue
}
<div class="parent">
  <div class="left">This is text</div>
  <div class="right"><input type="text"></div>
  <div class="left">This is text</div>
  <div class="right">text</div>
</div>

1 个答案:

答案 0 :(得分:1)

请确保将输入字段的最大宽度设置为100%,并将框大小设置为border-box,以确保填充和边框位于该100%范围内:

input {
    max-width: 100%;
    box-sizing: border-box;
}

.parent {
  width: 400px;
  background-color: yellow;
}

.left {
  display: inline-block;
  width: 50%;
  background-color: red
}

.right {
  display: inline-block;
  width: 30%;
  background-color: blue
}
<div class="parent">
  <div class="left">This is text</div>
  <div class="right"><input type="text"></div>
  <div class="left">This is text</div>
  <div class="right">text</div>
</div>