CSS Attribute Selectors
Target elements based on their attributes with modern CSS
๐ฏ What are Attribute Selectors?
CSS attribute selectors allow you to select elements based on their attributes and attribute values. They provide powerful targeting capabilities for modern web development.
/* Select elements with a specific attribute */
[data-theme] {
transition: all 0.3s ease;
}
/* Select elements with specific attribute value */
[type="email"] {
border-left: 4px solid #3b82f6;
}
Output:
Types of Attribute Selectors
[attribute]
Selects elements with the attribute
[required] {
border: 2px solid #ef4444;
}
[attribute="value"]
Exact attribute value match
[type="password"] {
background: #fef3c7;
}
[attribute^="value"]
Starts with value
[class^="btn"] {
padding: 12px 24px;
border-radius: 6px;
}
[attribute$="value"]
Ends with value
[src$=".svg"] {
filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}
๐น Modern Form Styling with Attribute Selectors
Use CSS attribute selectors like input[type="text"] to style forms without extra classes. This creates cleaner HTML and more maintainable CSS, allowing for precise targeting of form elements based on their attributes. Enhance accessibility and visual consistency across input types, improving usability and form completion ratesโkey factors in conversion optimization and on-page SEO performance.
/* Modern form styling */
:root {
--primary-color: #3b82f6;
--success-color: #10b981;
--error-color: #ef4444;
--border-radius: 8px;
}
/* Base input styling */
[type="text"], [type="email"], [type="password"] {
width: 100%;
padding: 12px 16px;
border: 2px solid #e5e7eb;
border-radius: var(--border-radius);
font-size: 16px;
transition: all 0.3s ease;
background: white;
}
/* Focus states */
[type="text"]:focus, [type="email"]:focus, [type="password"]:focus {
outline: none;
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
/* Required field indicator */
[required] {
border-left: 4px solid var(--primary-color);
}
/* Valid state */
[type="email"]:valid {
border-color: var(--success-color);
}
/* Invalid state */
[type="email"]:invalid:not(:placeholder-shown) {
border-color: var(--error-color);
}
Output:
๐น Advanced Attribute Selectors
Use modern CSS with data attributes and complex selectors:
/* Data attribute selectors */
[data-status="active"] {
background: linear-gradient(135deg, #10b981, #059669);
color: white;
position: relative;
}
[data-status="active"]::before {
content: "โ";
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
}
/* Multiple attribute selectors */
[data-theme="dark"][data-size="large"] {
background: #1f2937;
color: #f9fafb;
padding: 20px 32px;
font-size: 18px;
}
/* Contains selector */
[class*="icon"] {
display: inline-flex;
align-items: center;
gap: 8px;
}
/* Language attribute */
[lang="en"] {
font-family: 'Inter', sans-serif;
}
[lang="ar"] {
direction: rtl;
font-family: 'Noto Sans Arabic', sans-serif;
}