CSS将图标移动到输入字段的右侧

时间:2015-02-08 11:00:33

标签: html css

如何在我的输入栏中将放大镜移到右侧?

这是我的Fiddle

HTML:

<div class="search">
  <span class="fa fa-search"></span>
  <input placeholder="Search term">
</div>

CSS:

@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;
}

4 个答案:

答案 0 :(得分:2)

您也将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/

答案 1 :(得分:1)

您也可以在 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;

}

答案 2 :(得分:0)

<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 y字体真棒 https://jsfiddle.net/jlujan/kgxo81fm/15/

答案 3 :(得分:0)

在图标和输入周围创建一个相对容器跨度,以便图标始终相对于输入定位,而不是相对于 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>