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



如何将放大镜移动到输入字段的右手边?

这是我的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>

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

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

<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/

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

最新更新