将图像添加到占位符输入类型

3

我想制作一个登录表单,但是我不知道如何在占位符中插入图片。我目前的代码如下:

            <span class="material-icons" style="font-size:20px; color: gray; float: left;">person
                <input placeholder="username" type="text">lock
            </span>

            <span class="material-icons" style="font-size:24px; color: gray; float: left;">lock
                <input placeholder="Password" type="text">
            </span>

但是这些方法都没有达到我需要的效果。

我希望图片位于输入框内部,而不是在其前面。


几个选项:使用伪元素material-icons::after或添加img标签并将其绝对定位。 - Varinder
2个回答

11

尝试使用以下代码 它会在文本字段中显示图像占位符,并在您单击文本字段时隐藏。

input#search {
    background-image: url('https://cdn0.iconfinder.com/data/icons/very-basic-2-android-l-lollipop-icon-pack/24/search-512.png');
    background-size:contain;
    background-repeat: no-repeat;
    text-indent: 20px;
    /* Extra Styling */
    padding: 5px 3px;
    transition:0.3s;
}
input#search:focus {
    background-image:none;
    text-indent:0px
}
<input type="text" id="search" name="search" Placeholder="Search" />


1
只需在CSS中使用带类的background属性即可。
       <html>
            <head>
            <title></title>
        <style type="text/css" media="screen">
        input.test{
           padding: .5em; 
        }
        input.icon[value="SEARCH WORDS"]{
            padding-left:48px; 
            background: 
url(https://material.io/icons/static/images/icons-180x180.png) no-repeat 8px center;
        }
    </style>
</head>
<body>
    <input class="icon" value="NOT SEARCH WORDS">
    <input class="icon" value="SEARCH WORDS">
</body>

希望有所帮助。

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