【问题标题】:Input type to have width of 100% and be inside parent div输入类型具有 100% 的宽度并在父 div 内
【发布时间】:2016-08-25 09:09:36
【问题描述】:

我有一个输入电子邮件和密码以及其他一些按钮的表单。

html:

<div  id="login-form">
<form>
    <input type="email" placeholder="Email" id="email" name="email_phone">
    <br>
    <input type="password" placeholder="Password" id="password" name="password">
    <br>
    <button id="login-submit">Submit</button>
    <br>
    <button id="login-forgot">Forgot Password</button>
</form>
<br>
<br>
<center>
    <p>Don't have an account?</p>
</center>
<button id="create-new-account">Create Account Now</button>
</div>

我需要输入和按钮的宽度为父级的 100%。 并且有 10px 的内边距。

#login-form input[type=email], #login-form input[type=password] {
    width: 100%;
    font-size: 14pt;
    border: none;
    outline: none;
    padding: 10px;
}

#login-form button {
    width: 100%;
    border: none;
    color: white;
    font-size: 14pt;
    padding: 10px;
    margin-top: 10px;
    border-radius: 4px;
    cursor: pointer;
}

那么问题就从输入宽度开始。所有按钮都在父元素内,但输入框跨父 div。像这样:

demo at Codepen.

如何将输入框保持在父 div 内且宽度为 100% 且仍有填充

【问题讨论】:

  • 父 div 有填充吗?或者只是尝试 box-sizing: border-box 看看是否有效,因为您添加了填充,如果 box-size 不是边框框,那么它将被添加到元素中
  • 不,它没有填充。

标签: html css


【解决方案1】:

将此代码添加到您的样式文件中

*,
 ::before {
    box-sizing: border-box;
}

【讨论】:

    【解决方案2】:

    问题在于输入填充。要修复它,请将 box-sizing 属性添加到您的输入字段:

    box-sizing: border-box;
    

    我刚刚在你的 codepen 中测试过,看起来是你想要的结果。

    【讨论】:

    • 是的。这就是解决方案。谢谢。
    【解决方案3】:

    将 div 宽度设为 100%,然后更改输入字段宽度

    【讨论】:

      【解决方案4】:

      这是因为输入元素中的填充。它设置为 10,导致它必须扩展超过父元素的边缘。可能的解决方案包括仅移除填充或减小宽度以使其很好地适合内部。

      【讨论】:

      • 但是删除填充看起来很难看,因为文本从边框开始。是否可以有填充并将输入保留在父 div 中?
      猜你喜欢
      • 2012-03-24
      • 2011-01-21
      • 2020-08-02
      • 1970-01-01
      • 2013-01-02
      • 2011-12-24
      • 2013-08-04
      • 2012-11-10
      • 1970-01-01
      相关资源
      最近更新 更多