Using :optional pseudo-class CSS in Forms
I would probably say forms if they asked me what is common to most websites. We could multiply these examples in many ways such as contact forms, and feedback forms. Some of the most important elements that make up this form are input, select, and textarea.
These elements that we use to get information from users on our websites are sometimes required. At this point, the CSS pseudo-class comes into play and we can change the style of the required fields.
input:required, select:required, textarea:required {
border: 1px solid #F00;
}
input:required, select:required, textarea:required {
border: 1px solid #F00;
}
Now if I ask you a question like this, how could we style the non-required fields? Actually, when we design forms and inputs with CSS, most of us write styles by default. But today I discovered that there is an extra method to do this:
:optional pseudo-class
It becomes possible to style the three form input types I mentioned above by using an optional pseudo-class.
<form>
<div class="fields">
<label for="fullname">Full Name:</label>
<input type="text" id="fullname" />
</div>
<div class="fields">
<label for="email">Email Address:</label>
<input type="email" id="email" required />
</div>
</form>
label {
display: block;
margin: 1px;
padding: 1px;
}
.fields {
margin: 1px;
padding: 1px;
}
input:optional {
border-color: red;
border-width: 3px;
}