【问题标题】:How can I center the placeholder and text box cursor after shrinking the placeholder text?缩小占位符文本后如何使占位符和文本框光标居中?
【发布时间】:2020-06-12 03:41:05
【问题描述】:

我有一个输入文本框,里面有占位符文本;现在,我正在缩小占位符文本,以便在文本框获得焦点时它仍然可见,但是当我缩小它时,尽管垂直平移,占位符文本太靠近输入框的顶部。

我知道文本框中的光标仍然居中,但我希望 占位符文本和光标在文本框中居中。有没有办法只用 CSS 来做到这一点?

//我的输入文本框:

<input
  type="text"
  className={errors.email && errors.email.length !== 0 ? 'bad-input' : ''}
  value={this.state.email}
  onChange={this.update('email')}
  placeholder="Email"
/>

// 缩小占位符文本的样式:

.login-modal-wrapper form .main-content-wrapper input[type="text"]:focus::placeholder,
.login-modal-wrapper form .main-content-wrapper input[type="password"]:focus::placeholder {
  font-size: 12px;
  transform: translateY(-20px);
  transition: all 0.5s;
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    对于水平居中,您应该使用text-align:center

    垂直调整需要手动设置,但有2个选项;

    1. 您可以调整文本框的填充; padding-top:10px;padding-top:40%;

    2. 调整文本框内文本的行高; line-height:20px;.

    【讨论】:

    • 澄清一下,您的意思是将padding-top 添加到input[type="text"] 选择器中吗?
    • @Karen 抱歉,无法完全理解。我添加了另一个答案。
    【解决方案2】:

    我又看了你的问题,这次我明白了,通过调整占位符的字体大小,会影响其相对于输入字段内文本的垂直对齐方式。

    您可以通过使用position:relative 并更改top 属性来调整占位符伪类;

    参见下面的示例;

    input::placeholder {
      position: relative;
      top: 30px;
      font-size: 100px;
    }
    <!DOCTYPE html>
    <html>
    
    <body>
      <form action="/action_page.php">
        <label for="fname">First name:</label>
        <input style="height:100px; width:200px;" type="text" id="fname" placeholder="test" name="fname"><br><br>
        <label for="lname">Last name:</label>
        <input type="text" id="lname" name="lname"><br><br>
        <input type="submit" value="Submit">
      </form>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 2014-10-29
      • 2020-05-27
      • 2016-02-02
      • 2015-12-15
      • 1970-01-01
      • 2019-10-02
      • 2018-06-07
      • 2020-03-27
      • 2012-07-12
      相关资源
      最近更新 更多