使用position:absolute来设置输入宽度

Ad *_*lor 13 css

一个简单而烦人的 - 我尝试通过使用绝对定位设置输入[type = text]宽度(即右:10px;左:10px)但我不能让它玩球.

有没有人有解决方案将它变成形状?

pei*_*rix 24

实际上,你正在做的事情很好.您只需要记住设置父元素的位置.

<div>
   <input type="text">
</div>
Run Code Online (Sandbox Code Playgroud)

然后CSS它:

div {
    width: 400px;
    position: relative;
}
input {
    position: absolute;
    left: 5px;
    right: 5px;
}
Run Code Online (Sandbox Code Playgroud)

这将导致输入框为390px.

如果将div设置为灵活,则输入框也是如此.

编辑:似乎只能在Chrome中使用,因此您需要将输入放在另一个元素中.这也适用于FF和IE:

<div id="parent">
    <div><input type="text"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

用这个CSS:

#parent {
    position: relative;
    width: 400px;
}
  #parent div {
      position: absolute;
      left: 5px;
      right: 5px;
  }
    #parent div input {
        width: 100%;
    }
Run Code Online (Sandbox Code Playgroud)

这具有预期的效果.有点黑客,也许......

  • 将<input>包装到另一个<div>中做了诀窍 - 巧妙! (3认同)