If you only want to style a specific input type, you can use attribute selectors: input[type=text] - will only select text fields. input[type=password] - will only select password fields. input[type=number] - will only select number fields.
In modern browsers you can use :placeholder-shown
to target the empty input (not to be confused with ::placeholder
).
input:placeholder-shown {
border: 1px solid red; /* Red border only if the input is empty */
}
More info and browser support: https://css-tricks.com/almanac/selectors/p/placeholder-shown/
If only the field is required
you could go with input:valid
#foo-thing:valid + .msg { visibility: visible!important; }
<input type="text" id="foo-thing" required="required">
<span class="msg" style="visibility: hidden;">Yay not empty</span>
See live on jsFiddle
OR negate using #foo-thing:invalid
(credit to @SamGoody)
There is no selector in CSS which does this. Attribute selectors match attribute values, not computed values.
You would have to use JavaScript.
Updating the value of a field does not update its value attribute in the DOM so that's why your selector is always matching a field, even when it's not actually empty.
Instead use the invalid
pseudo-class to achieve what you want, like so:
input:required {
border: 1px solid green;
}
input:required:invalid {
border: 1px solid red;
}
<input required type="text" value="">
<input required type="text" value="Value">
input[value=""], input:not([value])
works with:
<input type="text" />
<input type="text" value="" />
But the style will not change as soon as someone will start typing (you need JS for that).
If supporting legacy browsers is not needed, you could use a combination of required
, valid
, and invalid
.
The good thing about using this is the valid
and invalid
pseudo-elements work well with the type attributes of input fields. For example:
input:invalid, textarea:invalid {
box-shadow: 0 0 5px #d45252;
border-color: #b03535
}
input:valid, textarea:valid {
box-shadow: 0 0 5px #5cd053;
border-color: #28921f;
}
<input type="email" name="email" placeholder="[email protected]" required />
<input type="url" name="website" placeholder="http://johndoe.com"/>
<input type="text" name="name" placeholder="John Doe" required/>
For reference, JSFiddle here: http://jsfiddle.net/0sf6m46j/
This worked for me:
For the HTML, add the required
attribute to the input element
<input class="my-input-element" type="text" placeholder="" required />
For the CSS, use the :invalid
selector to target the empty input
input.my-input-element:invalid {
}
Notes:
required
from w3Schools.com:
"When present, it specifies that an input field must be filled out before submitting the form."If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With