I'd like to add an image icon to an input placeholder, like in this picture:
Please note that this is a placeholder, so when the user starts typing, the icon also disappears.
I came with the following solution for webkit (Safari+Chrome) using ::-webkit-input-placeholder
and ::before
. Unfortunately, the straightforward application to mozilla seems not to work.
So my question is: is there a cross-browser solution to add an image icon to an input placeholder?
Solution for webkit:
#myinput::-webkit-input-placeholder::before {
content: ' ';
position: absolute;
top: 2px; /* adjust icon position */
left: 0px;
width: 14px; /* size of a single icon */
height: 14px;
background-image: url("/path/to/icons.png"); /* all icons in a single file */
background-repeat: no-repeat;
background-position: -48px 0px; /* position of the right icon */
}
This question is related to
css
html
cross-browser
placeholder
`CSS:
input#search{
background-image: url(bg.jpg);
background-repeat: no-repeat;
text-indent: 20px;
}
input#search:focus{
background-image:none;
}
HTML:
<input type="text" id="search" name="search" value="search" />`
Adding to Tim's answer:
#search:placeholder-shown {
// show background image, I like svg
// when using svg, do not use HEX for colour; you can use rbg/a instead
// also notice the single quotes
background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
// other background props
}
#search:not(:placeholder-shown) { background-image: none;}
I don't know whether there's a better answer out there as time goes by but this is simple and it works;
input[type='email'] {
background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
background-image: none;
}
Style it up to suit.
<html>
<head>
<style>
input[type=text] {
width: 50%;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 16px;
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding: 12px 20px 12px 40px;
}
</style>
</head>
<body>
<p>Input with icon:</p>
<form>
<input type="text" name="search" placeholder="Search..">
</form>
</body>
</html>
Source: Stackoverflow.com