在文本框内重叠使用Font Awesome图标

7
在下面这种重叠的情况下,如何避免标题和文本字段之间出现大的空白间隔?

.icon-link-mail {
  position: relative;
  left: 485px;
  top: 29px;
  padding: 8px 8px 7px 8px;
  z-index: 2
}
<h3>Title</h3>
<form name="mail_form" id="mail_form" method="POST" action="">
  <label for="sendto">
              <a href="#"><i class="icon-envelope icon-2x icon-link-mail" style="color:#E4E4E4; text-decoration:none"></i></a>
              <input name="sendto" class="sendto" type="text" style="width: 98%; margin-bottom:10px" placeholder="Send to.." />
              </label>
</form>

可以在这个fiddle中看到结果。


你的问题标题与解释不符。问题出在标题和文本字段之间的差距吗? - daveyfaherty
3个回答

10

个人建议使用伪元素,但如果您希望使用<i>图标,那么我们可以通过使用position:absolute而不是position:relative来更好地实现。添加position:relative只会移动图标,但会保留它本应占据的空间。position:absolute不会留下该空间。

但需要确保将父容器(label)设置为position:relative,这样图标将相对于父级而不是整个页面进行绝对定位。

#mail_form label {
  position: relative;
}

.icon-link-mail {
  position: absolute;
  z-index: 2;
  right: 0;
}
<h3>Title</h3>
<form name="mail_form" id="mail_form" method="POST" action="">
  <label for="sendto">
        <a href="#"><i class="icon-envelope icon-2x icon-link-mail" style="color:#E4E4E4; text-decoration:none"></i></a>
        <input name="sendto" class="sendto" type="text" style="width: 98%; margin-bottom:10px" placeholder="Send to.." />
     </label>
</form>

Result

enter image description here

Fiddle

http://jsfiddle.net/Ay6Hw/4/


当您的定位元素与其他相对或绝对定位的元素重叠时,将其z-index设置为-1以解决问题。 - Protector one

0

我发现最好的方法是使用图片。以下是代码:

.search input {
padding-left: 17px;
background: #FFF url("../images/icon_search.png") left no-repeat;
}
.search input:focus {
background:#fff;
}

这也将在焦点上移除背景图像,从而为用户提供更好的整体体验。


谢谢您的回复,但我必须先考虑使用字体awesome图标的另一种选择! - afazolo
好的,您可以始终使用:before或:after伪元素仅使用CSS使其正常工作。 - Soltechy

0

这里有一个解决方案,它使用简单的CSS和标准的font awesome语法,无需Unicode值等。

  1. 创建一个<input>标签,然后是一个带有所需图标的标准<i>标签。

  2. 使用相对定位以及更高的层次顺序(z-index),将图标移动到输入字段上方。

  3. (可选) 您可以通过标准JS使图标活动,以便提交数据。

请参见下面的三个代码片段,了解HTML / CSS / JS。

或者在JSFiddle中查看相同的内容: 示例:http://jsfiddle.net/ethanpil/ws1g27y3/

$('#filtersubmit').click(function() {
  alert('Searching for ' + $('#filter').val());
});
#filtersubmit {
  position: relative;
  z-index: 1;
  left: -25px;
  top: 1px;
  color: #7B7B7B;
  cursor: pointer;
  width: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="filter" type="text" placeholder="Search" />
<i id="filtersubmit" class="fa fa-search"></i>


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