W3docs

How to Match an Empty Input Box with CSS

It is possible to match an empty input box only if the input field is required. In this snippet, we’ll show how to do this using the CSS :valid pseudo-class.

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 <span class="attribute">type</span>, <span class="attribute">placeholder</span>, <span class="attribute">id</span>, and <span class="attribute">required</span> attributes.
  • Add a <span> element with the <span class="attribute">class</span> attribute.

How to Match an Empty Input Box with CSS

<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".

How to Match an Empty Input Box with CSS

.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

<div class="demo px-2.5 mt-1 mb-5 not-prose"> Below, type something to see how the placeholder text is hidden. <form action-xhr="/fom/submit" method="post"> <input id="test" placeholder="Type something..." required="required" type="text"> </input> <span class="message">Some text</span> </form> </div>