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?