CSS :optional

The CSS :optional pseudo-class targets form elements that are not required, meaning elements without the required attribute. It can be used to apply specific styles to optional input fields, textareas, or other form elements.

The syntax for the :optional pseudo-class is:

</>
Copy
selector:optional {
    property: value;
}

Where:

ParameterDescription
selectorThe form element (e.g., <input>, <textarea>) to which the :optional pseudo-class will apply.
propertyThe CSS property to style the element.
valueThe value assigned to the CSS property.

Examples

1. Styling Optional Input Fields

In this example, optional <input> fields are styled with a blue border.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        input:optional {
            border: 2px solid blue;
        }
    </style>
</head>
<body>
    <form>
        <label>Optional Field:</label>
        <input type="text" placeholder="Optional field"><br><br>
        <label>Required Field:</label>
        <input type="text" placeholder="Required field" required>
    </form>
</body>
</html>

2. Styling Optional Textareas

Here, optional <textarea> elements are styled with a lightblue background.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        textarea:optional {
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <textarea placeholder="Optional field" rows="4" cols="30"></textarea><br><br>
    <textarea placeholder="Required field" rows="4" cols="30" required></textarea>
</body>
</html>

3. Styling Optional Select Dropdowns

In this example, optional <select> elements are styled with a green border and italic text.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        select:optional {
            border: 2px solid green;
            font-style: italic;
        }
    </style>
</head>
<body>
    <form>
        <label>Optional Dropdown:</label>
        <select>
            <option value="">Select an option</option>
            <option>Option 1</option>
            <option>Option 2</option>
        </select><br><br>
        <label>Required Dropdown:</label>
        <select required>
            <option value="">Select an option</option>
            <option>Option 1</option>
        </select>
    </form>
</body>
</html>

4. Styling Placeholder Text in Optional Fields

In this example, placeholder text in optional input fields is styled with italic text and a light gray color.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        input:optional::placeholder {
            font-style: italic;
            color: lightgray;
        }
    </style>
</head>
<body>
    <input type="text" placeholder="Optional field"><br><br>
    <input type="text" placeholder="Required field" required>
</body>
</html>