CSS :required
The CSS :required pseudo-class targets form elements that are marked as required using the required
attribute. It is commonly used to style elements such as <input>
, <textarea>
, and <select>
that must be filled out before a form can be submitted.
The syntax for the :required
pseudo-class is:
</>
Copy
selector:required {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The form element (e.g., <input> , <textarea> ) to which the :required pseudo-class will apply. |
property | The CSS property to style the element. |
value | The value assigned to the CSS property. |
Examples
1. Styling Required Input Fields
In this example, required <input>
fields are styled with a red border.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:required {
border: 2px solid red;
}
</style>
</head>
<body>
<form>
<label>Name (required):</label>
<input type="text" required><br><br>
<label>Optional Field:</label>
<input type="text">
</form>
</body>
</html>
2. Styling Required Textareas
Here, required <textarea>
elements are styled with a lightyellow background.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
textarea:required {
background-color: lightyellow;
}
</style>
</head>
<body>
<textarea placeholder="Required field" rows="4" cols="30" required></textarea><br><br>
<textarea placeholder="Optional field" rows="4" cols="30"></textarea>
</body>
</html>
3. Styling Required Select Dropdowns
In this example, required <select>
elements are styled with a blue border and bold text.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
select:required {
border: 2px solid blue;
font-weight: bold;
}
</style>
</head>
<body>
<form>
<label>Choose an option (required):</label>
<select required>
<option value="">Select an option</option>
<option>Option 1</option>
<option>Option 2</option>
</select><br><br>
<label>Optional Dropdown:</label>
<select>
<option value="">Select an option</option>
<option>Option 1</option>
</select>
</form>
</body>
</html>
4. Styling Required Fields with Placeholder Text
In this example, required input fields are styled with italic text for their placeholder text.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:required::placeholder {
font-style: italic;
color: gray;
}
</style>
</head>
<body>
<input type="text" placeholder="Required field" required><br><br>
<input type="text" placeholder="Optional field">
</body>
</html>