在搜索栏HTML中显示图像

时间:2020-07-30 19:17:02

标签: html css

我正在整理这张桌子,并向其中添加了搜索功能。但是,在搜索栏中,我想为背景图片放置一个搜索图标png文件,就像W3Schools上的示例一样。我将其放在myInput字段中,但是搜索栏中没有任何内容,或者它太大了,您可以在搜索图标的顶部看到一个很小的角,而我不知道该如何解决。

Post Background Size edit

Search box input element

#myInput {
  background-image: url('https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-512.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
<input type="text" id="myInput">

2 个答案:

答案 0 :(得分:2)

您需要使用background-size属性。因为图像大于输入,所以您看到的是白色部分。通过将该属性设置为contain,图像将缩小为input的大小。

#myInput {
  background-image: url('https://cdn1.iconfinder.com/data/icons/hawcons/32/698627-icon-111-search-512.png');
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 30px;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
<input placeholder="Search..." type="text" id="myInput">

注意:您还应该将background-position属性设置为0或一起删除所有属性;否则,搜索图标将向右和向下倾斜。 相反,如果要缩小图标,请将background-position更改为left center,然后将background-size设置为您选择的px值。

答案 1 :(得分:0)

HTML

<div class="fake-input">
    <input type="text" />
    <img src="http://www.zermatt-fun.ch/images/mastercard.jpg" width=25 />
</div>

CSS

.fake-input { position: relative; width:240px; }
.fake-input input { border:none; background-color:#fff; display:block; width: 100%; box-sizing: border-box }
.fake-input img { position: absolute; top: 2px; right: 5px }

Source is here

相关问题