将图标移动到输入框右侧的CSS方法

5

如何将放大镜移动到输入框右侧?

这是我的Fiddle

@import url("//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css");
body {
  margin: 30px;
}

.search {
  position: relative;
  color: #aaa;
  font-size: 16px;
}

.search input {
  width: 250px;
  height: 32px;
  background: #fcfcfc;
  border: 1px solid #aaa;
  border-radius: 5px;
  box-shadow: 0 0 3px #ccc, 0 10px 15px #ebebeb inset;
}

.search input {
  text-indent: 32px;
}

.search .fa-search {
  position: absolute;
  top: 10px;
  left: 10px;
}
<div class="search">
  <span class="fa fa-search"></span>
  <input placeholder="Search term">
</div>

4个回答

6
你也将 left:10px 应用在图标上。可以将其设置为更多的像素距离左侧,或者直接从右侧以像素为单位进行设置。
.search .fa-search {left: 230px;}

http://jsfiddle.net/xhjLyf1k/1/

将位置设置为正确位置而非左边(以防止输入字段的调整大小):

.search {display: inline-block} /* prevent 100% width */
.search .fa-search {left: auto; right: 10px;}

http://jsfiddle.net/xhjLyf1k/2/


2
您还可以在CSS中使用 ::before 伪元素,在右侧添加一个图标。
.search::before {
  position: absolute;
  height: 3rem;
  width: 3rem;
  top: 50%;

  transform: translate(-50%, -50%);
  right: 0rem;
  content: "";
  background-image: url('../images/search.png');
  background-size: contain;

}

1

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" rel="stylesheet"/>
<div class='form-group'>
<label>Clave</label>
<div class="input-group input-group-sm" >
 <input class='form-control' type="password">
 <div class="input-group-btn">
 <button type="submit" id="togglePassword" class="btn btn-default fa fa-eye"></button>
</div>
</div>
</div> 

Bootstrap和Font Awesome https://jsfiddle.net/jlujan/kgxo81fm/15/


1
你需要编辑你的答案,解释为什么你认为它有效,并包括除你复制的代码之外的所有代码,因为链接会随着时间的推移而失效。 - Lajos Arpad

1
在图标和输入框周围创建一个相对容器 span,使图标始终相对于输入框定位,而不是100%宽度的 div。然后您可以将此组件移动到任何位置并使图标正常工作。

@import url("//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css");
body {
  margin: 30px;
}

.search {

  color: #aaa;
  font-size: 16px;
}

.form-element {
  position: relative;
}

.search input {
  width: 250px;
  height: 32px;
  background: #fcfcfc;
  border: 1px solid #aaa;
  border-radius: 5px;
  box-shadow: 0 0 3px #ccc, 0 10px 15px #ebebeb inset;
}

.search input {
  text-indent: 1em;
}

.search .fa-search {
  position: absolute;
  top: 0;
  right: 10px;
  bottom: 0;
}
<div class="search">
<span class="form-element">
  <span class="fa fa-search"></span>
  <input placeholder="Search term">
  </span>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接