How to Match an Empty Input Box with CSS
The HTML <input> tag is used to define fields for user input.
It is possible to match an empty input box only if the input field is required. In this case, you can use the :valid pseudo-class.
In our tutorial, you can see how to match an empty input box step by step. Let’s start with creating HTML.
Create HTML
- Use a <form> element.
- Add an <input> element with the type, placeholder, id, and required attributes.
- Add a <span> element with the class attribute.
<form>
<input type="text" placeholder="Type something..." id="test" required="required">
<span class="message">Some text</span>
</form>
Now, we can add the CSS part.
Add CSS
- Set the visibility to "hidden" for the "message" class.
- Add a :valid pseudo-class to the "test" and also add the "message" class. Then, set the visibility to "visible".
.message {
visibility: hidden;
}
#test:valid+.message {
visibility: visible;
}
The result of our code looks like the following.
Example of matching an empty input type:
<!DOCTYPE html>
<html>
<head>
<title>The title of the document</title>
<style>
.message {
visibility: hidden;
}
#test:valid+.message {
visibility: visible;
}
</style>
</head>
<body>
<form>
<input type="text" placeholder="Type something..." id="test" required="required">
<span class="message">Some text</span>
</form>
</body>
</html>
Result of matching an empty input box
Below, type something to see how the placeholder text is hidden.