Search code examples
csspseudo-elementpseudo-class

CSS pseudo-class :required does not work together with pseudo-element ::before


My intent is to put a * on labels of required fields.

I am testing with Chrome 47, Firefox 43 and Opera 34. None of these can understand the CSS selector

span:required::before

According to http://caniuse.com/#feat=form-validation they all should be able to understand it, and if you use

span:hover::before

instead, it actually works. What do I do wrong? Here is my Code:

<!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      span::before {
        content: "\00A0";
      }
      span:required::before { /* This does NOT work! */
        content: "*";
      }
      span:hover::before { /* But this DOES work! */
        content: "_";
      }
    </style>
  </head>
  
  <body>
    <form>
      <p>
        <span required>Name</span>
        <input id="name" type="text" />
      </p>
      
      <p>
        <span>Date of Birth</span>
        <input id="birth" type="text" />
      </p>
    </form>
    
  </body>
</html>


Solution

  • Two problems:

    • Form labels have a dedicated element, label. You should be using that, not span.

    • The required attribute only applies to the controls themselves, that is, input, select, textarea, etc. A span is just plain text (and a label is basically that on its own) and the required attribute makes no sense on such an element.1

    If you're trying to style a label of a required input, you will need to give it a class name instead.

    This has nothing to do with :required::before, though, given that most form elements are replaced elements, it's unlikely you'll find that pseudo-class and that pseudo-element together.


    1 contenteditable notwithstanding.