首页 > 解决方案 > 无法使图标留在输入内

问题描述

我正在学习 React,但我有一个简单的 html/css 问题。我以前有过这种事情,但由于某种原因我被卡住了。

我正在尝试制作一个简单的登录表单,但图标位于输入下方而不是内部。如果我尝试移动带有边距的图标,则图标会隐藏在输入后面。

我有一个 React 组件,它呈现:

<Input icon="register-user" onChange={this.handleChange} type='text' placeholder='Username'   />

输入如下所示:

<div className="control has-icon input-text">
  <input {...this.props} ref='input' className={inputClassNames}/>
  <i className={icon}/>
</div>

我的CSS看起来像:

.register {
  background-size: cover;
  .container {
    width: 736px;
    height: 370px;
    clear: both;
    display: block;
    .form {
      background-color: white;
      padding: 48px 48px 20px 48px;
      height: 400px;
      width: 392px;
      border-radius: 8px;
      box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.2);

      .control {
        margin-bottom: 16px;
      }

      .control:last-child {
        margin-top: 21px;
      }

      .has-icon {
        background-color: pink;
      }
    } //end .form

    input {
      outline: none;
      box-shadow: none;
      text-align: left;
      height: 32px;
      width: 280px;
      border: 1px solid #006bac;
      border-radius: 4px;
      background-color: #f2f7fa;
    }
  } // end .container

  input {
    outline: none;
    box-shadow: none;
    border-radius: 0px;
    height: 40px;
    color: $admin-register-input-text;
    font-size: 16px;
    background: #2c3c44;
    border: none;
  }

  .form,
  .image {
    float: right;
    width: 50%;
    height: 100%;
  }
  .title {
    color: blue;
  }
} //end .register

.register-user {
  background: url($login_user_icon) no-repeat 50%;
  height: 16px;
  width: 13px;
  color: #006bac;
  font-size: 14px;
  line-height: 14px;
  text-align: center;
  float: right;
}

标签: htmlcss

解决方案


这更像是 CSS 而不是 React 相关的问题,当涉及到重叠元素时,请考虑使用位置而不是边距。

演示

.container {
  position: relative;
  /* let the input assign the width of the parent */
  display: inline-block;
}

.icon {
  position: absolute;
  top: 0;
  right: 0;
}
<div class="container">
  <input type="text" class="input" />
  <i class="icon">☺&lt;/i>
</div>


推荐阅读