Here is a cross-browser solution that does not use Javascript:
Live demo
Inline elements such input
do not support :before
and :after
. To make things even harder the placeholder selector and their pseudo-classes are not fully supported by all browsers, as you found out.
So, the workaround is to add a label
placed relatively on top of the input box with a for
attribute pointing to the input text box. This way, when user clicks the label (fake placeholder) the focus goes into the input box underneath.
Replace your class="required"
by the attribute required="required"
. This gives you an opportunity to use the :invalid and :valid selectors, and also lets the browser display a validation error, when the form is submitted with empty required fields.
input {
width: 160px;
}
input[type=submit] {
width: auto;
}
input[required]+label {
color: #999;
font-family: Arial;
font-size: .8em;
position: relative;
left: -166px;
/* the negative of the input width */
}
input[required]+label:after {
content: '*';
color: red;
}
/* show the placeholder when input has no content (no content = invalid) */
input[required]:invalid+label {
display: inline-block;
}
/* hide the placeholder when input has some text typed in */
input[required]:valid+label {
display: none;
}
<form>
<input type="text" id="name" name="name" required="required" />
<label for="name">Name</label>
<br/>
<input type="email" id="email" name="email" placeholder="Email" />
<br/>
<input type="submit" />
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…