Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Role of CSS :optional Selector
The CSS :optional pseudo-class selector is used to target form elements that do not have the required attribute. This selector is particularly useful for styling optional form fields differently from required ones.
Syntax
:optional {
/* CSS properties */
}
/* Target specific optional elements */
input:optional {
/* CSS properties */
}
Example: Styling Optional Form Fields
The following example demonstrates how to style optional input fields with a light blue background while required fields remain with default styling −
<!DOCTYPE html>
<html>
<head>
<style>
form {
padding: 20px;
font-family: Arial, sans-serif;
}
input {
padding: 8px;
margin: 5px 0;
border: 2px solid #ddd;
border-radius: 4px;
}
input:optional {
background-color: #e6f3ff;
border-color: #b3d9ff;
}
input:required {
background-color: #fff0e6;
border-color: #ffb366;
}
label {
display: block;
margin-top: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<form>
<label>Name (Required):</label>
<input type="text" name="name" required>
<label>Email (Required):</label>
<input type="email" name="email" required>
<label>Phone (Optional):</label>
<input type="tel" name="phone">
<label>Comments (Optional):</label>
<input type="text" name="comments">
</form>
</body>
</html>
A form appears with four input fields. The required fields (Name and Email) have an orange background with orange borders, while the optional fields (Phone and Comments) have a light blue background with blue borders.
Browser Support
The :optional selector is widely supported across modern browsers including Chrome, Firefox, Safari, and Edge. It works with form elements like <input>, <select>, and <textarea>.
Conclusion
The :optional selector provides an effective way to visually distinguish optional form fields from required ones. This improves user experience by clearly indicating which fields are mandatory for form submission.
