Attribute Selectors cho phép chọn element dựa trên attribute và giá trị của nó. Rất hữu ích cho form styling không cần thêm class.
Các loại Attribute Selectors
| Selector | Mô tả | Ví dụ |
|---|---|---|
| [attr] | Có attribute | input[required] |
| [attr=value] | Attribute = giá trị chính xác | input[type="text"] |
| [attr~=value] | Attribute chứa từ (space-separated) | input[class~="large"] |
| [attr|=value] | Attribute bắt đầu bằng value + "-" | html[lang|="en"] (en, en-US, en-GB) |
| [attr^=value] | Attribute bắt đầu bằng value | a[href^="https://"] |
| [attr$=value] | Attribute kết thúc bằng value | a[href$=".pdf"] |
| [attr*=value] | Attribute chứa value ở bất kỳ đâu | a[href*="google"] |
| [attr operator value i] | Case-insensitive (thêm i) | input[type="TEXT" i] |
| [attr operator value s] | Case-sensitive (thêm s) | input[type="text" s] |
Ví dụ mã nguồn: Style Form theo type
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; max-width: 500px; }
form { display: flex; flex-direction: column; gap: 15px; }
/* Text inputs */
input[type="text"],
input[type="email"],
input[type="url"],
input[type="tel"],
input[type="number"],
input[type="password"] {
width: 100%;
padding: 12px 16px;
font-size: 16px;
border: 2px solid #ddd;
border-radius: 8px;
transition: border-color 0.2s, box-shadow 0.2s;
box-sizing: border-box;
}
input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus {
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0,123,255,0.2);
outline: none;
}
/* Placeholder styling */
input::placeholder { color: #999; }
/* Submit button */
input[type="submit"],
button[type="submit"] {
background: #007bff;
color: white;
border: none;
padding: 14px 24px;
font-size: 16px;
font-weight: 600;
border-radius: 8px;
cursor: pointer;
transition: background 0.2s, transform 0.1s;
}
input[type="submit"]:hover { background: #0056b3; }
input[type="submit"]:active { transform: scale(0.98); }
/* Required indicator */
input[required]::after { content: " *"; color: #dc3545; }
/* Disabled state */
input:disabled { background: #f5f5f5; color: #999; cursor: not-allowed; }
/* Readonly */
input[readonly] { background: #f8f9fa; }
/* File input custom */
input[type="file"] { padding: 8px; }
/* Checkbox/Radio custom (cần thêm markup) */
.checkbox-group { display: flex; flex-direction: column; gap: 8px; }
.checkbox-group label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
Form Styling with Attribute Selectors