【问题标题】:CSS input element width going outside containerCSS输入元素宽度超出容器
【发布时间】:2016-07-08 08:26:12
【问题描述】:

为什么电子邮件和密码宽度超出input-container 宽度?

  form {
    background: #ccc;
  }
  .input-container {
    background: red;
    width: 469px;
    margin: 0 auto;
  }
  .usermail,
  .userpword {
    margin-top: 10px;
  }
  input,
  button {
    width: 100%;
    border-radius: 6px;
    border: 1px solid #cacece;
    padding: 10px 12px;
    font-size: 1em;
  }
  .username input {
    width: 206px;
  }
<form action='' method='post' id='signupform'>
  <div class='input-container'>
    <div class='username'>
      <input type='text' name='fname' id='fname' placeholder='First Name'>
      <input type='text' name='lname' id='lname' placeholder='Last Name'>
    </div>
    <div class='usermail'>
      <input type='email' name='email' id='email' placeholder='Email'>
    </div>
    <div class='userpword'>
      <input type='password' name='pword' id='pword' placeholder='Password'>
    </div>
    <button>Sign Up</button>
  </div>
</form>

【问题讨论】:

  • 因为您的填充不计入宽度,所以您的输入是100% + padding 宽。使用box-sizing: border-box 来解决这个问题。此外,这同样适用于您的边框。
  • ^ 谷歌“CSS 盒子模型”
  • 记住,一个简单的规则。 total width = width + padding + border
  • 忘记了填充效果。谢谢。

标签: html css


【解决方案1】:

那是因为您设置了填充。它将元素宽度的值与填充集相加。

为避免此行为,建议添加属性box-sizing: border-box

例子:

#element{
    box-sizing: border-box;}

甚至更好:

*{
    box-sizing: border-box;}

【讨论】:

  • 具体添加到input, button CSS规则中
  • 尽管“更好”是一个非常宽松的定义,因为许多人会认为使用* 通配符对于整体性能不好。就我个人而言,我不会使用 *,因为它会将整个盒子模型颠倒过来,并且您认为您现在知道的所有东西的工作方式都不同,但这是个人喜好。
猜你喜欢
  • 2021-01-22
  • 2021-11-02
  • 2013-05-30
  • 2021-11-08
  • 2021-11-02
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多