0

I attempted to do this with a CSS selector like label::after + input:required but the asterisk doesn't show up. Here's a full example:

div {
  margin: 10px;
}

label,
input {
  display: inline-block;
  width: 100px;
}

label::after+input:required {
  content: "*";
}
<form>
  <div>
    <label for="name">First name</label>
    <input id="name" name="name" type="text" required>
  </div>
  <div>
    <label for="email">Email</label>
    <input id="email" name="email" type="email">
  </div>
  <button>Submit</button>
</form>

Also, I did some research and all the reasonable solutions I found involve adding a "required" class to the label. This works but it violates DRY and adds additional potential for error since I could forget to add the class to a required field's label.

Is there a way to do this without any changes to the HTML?

Chad
  • 1
  • 1
  • 1
    The adjacent sibling selector `+` targets what comes after the `+` sign. That is, in your CSS, it's attempting to find the `input` element, rather than `label`. I'm afraid you'd need to address the HTML markup a little bit. – Bumhan Yu Feb 27 '22 at 04:15

0 Answers0