🔍 CSS Attribute Selectors & Media Types

Select elements by attributes and create responsive designs with media queries

← Back to Content Next Topic: CSS Images →

🎯 What are Attribute Selectors?

Attribute selectors allow you to select elements based on their attributes and attribute values. They provide powerful targeting without needing classes or IDs.

Why Use Attribute Selectors?

  • ✅ Target elements by data attributes
  • ✅ Style forms based on input types
  • ✅ Select links by URL patterns
  • ✅ Target elements without adding classes
  • ✅ Create flexible, maintainable selectors

📝 Basic Attribute Selectors

1. [attribute] - Has Attribute

/* Select elements with specific attribute */
a[target] {
    background: yellow;
}

input[required] {
    border-left: 3px solid red;
}

img[alt] {
    border: 2px solid green;
}

2. [attribute="value"] - Exact Match

/* Exact value match */
input[type="text"] {
    border: 1px solid blue;
}

a[target="_blank"] {
    color: red;
}

button[type="submit"] {
    background: green;
    color: white;
}

Exact Match Example:

🔤 String Matching Attribute Selectors

3. [attribute^="value"] - Starts With

/* Starts with value */
a[href^="https"] {
    color: green;
    font-weight: bold;
}

a[href^="http://"] {
    color: blue;
}

a[href^="mailto:"] {
    color: orange;
}

/* Class names starting with btn- */
[class^="btn-"] {
    padding: 10px 20px;
    border-radius: 5px;
}

4. [attribute$="value"] - Ends With

/* Ends with value */
a[href$=".pdf"] {
    color: red;
    font-weight: bold;
}

a[href$=".pdf"]::after {
    content: " 📄";
}

a[href$=".zip"]::after {
    content: " 📦";
}

img[src$=".jpg"],
img[src$=".png"] {
    border: 2px solid gray;
}

5. [attribute*="value"] - Contains

/* Contains value anywhere */
a[href*="google"] {
    color: #4285f4;
}

a[href*="github"] {
    color: #333;
}

[class*="icon"] {
    display: inline-block;
    width: 20px;
    height: 20px;
}

input[name*="email"] {
    background: url('email-icon.png') no-repeat right;
}

🔧 Space and Hyphen Selectors

6. [attribute~="value"] - Space-Separated Word

/* Matches space-separated word */
[class~="button"] {
    padding: 10px 20px;
}

/* Works with multiple classes */
/* class="primary button large" */
[class~="button"] {
    /* Matches */
}

7. [attribute|="value"] - Hyphen-Separated Start

/* Matches exact value or value- */
[lang|="en"] {
    color: blue;
}

/* Matches: lang="en" or lang="en-US" or lang="en-GB" */

🔠 Case Sensitivity

Add i flag for case-insensitive matching.

/* Case-insensitive matching */
a[href$=".PDF" i] {
    color: red;
}

/* Matches: .pdf, .PDF, .Pdf, .pDF, etc. */

input[type="email" i] {
    border-color: blue;
}

📊 Data Attributes

Custom data attributes are perfect for JavaScript interaction and CSS styling.

/* Select by data attributes */
[data-status="active"] {
    background: green;
    color: white;
}

[data-status="pending"] {
    background: orange;
    color: white;
}

[data-status="inactive"] {
    background: gray;
    color: white;
}

/* Use in tooltips */
[data-tooltip] {
    position: relative;
    cursor: help;
}

[data-tooltip]::after {
    content: attr(data-tooltip);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    padding: 8px 12px;
    background: #333;
    color: white;
    border-radius: 4px;
    white-space: nowrap;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s;
}

[data-tooltip]:hover::after {
    opacity: 1;
}

Data Attribute Example:

Active Pending Inactive

💼 Practical Attribute Selector Examples

Example 1: Style External Links

/* Style external links differently */
a[href^="http"]::after {
    content: " ↗";
    font-size: 0.8em;
}

/* Internal links (no icon) */
a[href^="/"],
a[href^="#"] {
    /* No icon */
}

Example 2: File Type Icons

/* Add icons based on file type */
a[href$=".pdf"]::before {
    content: "📄 ";
}

a[href$=".doc"]::before,
a[href$=".docx"]::before {
    content: "📝 ";
}

a[href$=".zip"]::before {
    content: "📦 ";
}

a[href$=".mp3"]::before,
a[href$=".wav"]::before {
    content: "🎵 ";
}

Example 3: Required Form Fields

/* Style required inputs */
input[required] {
    border-left: 3px solid #e74c3c;
}

/* Add asterisk to required labels */
label[for] input[required] ~ label::after,
input[required] + label::after {
    content: " *";
    color: red;
    font-weight: bold;
}

Example 4: Button States

/* Different button types */
button[type="submit"] {
    background: #27ae60;
    color: white;
}

button[type="reset"] {
    background: #e74c3c;
    color: white;
}

button[disabled] {
    background: #95a5a6;
    cursor: not-allowed;
    opacity: 0.6;
}

📱 Media Queries

Media queries enable responsive design by applying styles based on device characteristics.

Basic Syntax:

/* Basic media query */
@media screen and (max-width: 768px) {
    /* Styles for screens 768px and smaller */
    .container {
        width: 100%;
        padding: 10px;
    }
}

Common Breakpoints:

/* Mobile First Approach */

/* Extra Small (phones, less than 576px) */
/* Default styles go here */

/* Small devices (landscape phones, 576px and up) */
@media (min-width: 576px) {
    .container { max-width: 540px; }
}

/* Medium devices (tablets, 768px and up) */
@media (min-width: 768px) {
    .container { max-width: 720px; }
}

/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
    .container { max-width: 960px; }
}

/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {
    .container { max-width: 1140px; }
}

Desktop First Approach:

/* Desktop styles by default */

/* Tablet (max 1024px) */
@media (max-width: 1024px) {
    .sidebar { width: 200px; }
}

/* Mobile (max 768px) */
@media (max-width: 768px) {
    .sidebar { 
        width: 100%;
        position: static;
    }
}

/* Small mobile (max 480px) */
@media (max-width: 480px) {
    .container { padding: 10px; }
}

🔧 Media Features

Width and Height:

/* Width queries */
@media (min-width: 600px) { }
@media (max-width: 1200px) { }
@media (width: 800px) { }

/* Height queries */
@media (min-height: 600px) { }
@media (max-height: 800px) { }

Orientation:

/* Portrait (height > width) */
@media (orientation: portrait) {
    .gallery {
        grid-template-columns: 1fr;
    }
}

/* Landscape (width > height) */
@media (orientation: landscape) {
    .gallery {
        grid-template-columns: repeat(3, 1fr);
    }
}

Aspect Ratio:

/* Specific aspect ratio */
@media (aspect-ratio: 16/9) {
    .video { width: 100%; }
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    /* Wide screens */
}

Resolution:

/* High-resolution displays (Retina) */
@media (min-resolution: 2dppx) {
    .logo {
        background-image: url('logo@2x.png');
        background-size: 100px 50px;
    }
}

Prefers Color Scheme:

/* Dark mode */
@media (prefers-color-scheme: dark) {
    body {
        background: #1a1a1a;
        color: #ffffff;
    }
}

/* Light mode */
@media (prefers-color-scheme: light) {
    body {
        background: #ffffff;
        color: #000000;
    }
}

Prefers Reduced Motion:

/* Respect user's motion preferences */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
}

🖥️ Media Types

/* Screen (default) */
@media screen {
    body { font-family: sans-serif; }
}

/* Print */
@media print {
    header, footer, nav {
        display: none;
    }
    
    body {
        font-size: 12pt;
        color: black;
    }
    
    a::after {
        content: " (" attr(href) ")";
    }
}

/* All media types */
@media all {
    /* Applies to everything */
}

🔗 Combining Media Queries

/* AND operator */
@media screen and (min-width: 768px) and (max-width: 1024px) {
    /* Tablets only */
}

/* OR operator (comma) */
@media (max-width: 768px), (orientation: portrait) {
    /* Mobile OR portrait */
}

/* NOT operator */
@media not print {
    /* Everything except print */
}

/* Complex combination */
@media screen and (min-width: 768px) and (orientation: landscape) {
    /* Landscape tablets and desktops */
}

💼 Practical Media Query Examples

Example 1: Responsive Navigation

/* Desktop navigation */
nav {
    display: flex;
    justify-content: space-between;
}

/* Mobile navigation */
@media (max-width: 768px) {
    nav {
        flex-direction: column;
    }
    
    .menu-toggle {
        display: block;
    }
    
    .nav-menu {
        display: none;
    }
    
    .nav-menu.active {
        display: flex;
        flex-direction: column;
    }
}

Example 2: Responsive Grid

/* Desktop: 4 columns */
.grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

/* Tablet: 2 columns */
@media (max-width: 1024px) {
    .grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

/* Mobile: 1 column */
@media (max-width: 768px) {
    .grid {
        grid-template-columns: 1fr;
    }
}

Example 3: Font Sizes

/* Base font sizes */
h1 { font-size: 3rem; }
h2 { font-size: 2.5rem; }
p { font-size: 1rem; }

/* Tablet adjustments */
@media (max-width: 1024px) {
    h1 { font-size: 2.5rem; }
    h2 { font-size: 2rem; }
}

/* Mobile adjustments */
@media (max-width: 768px) {
    h1 { font-size: 2rem; }
    h2 { font-size: 1.75rem; }
    p { font-size: 0.95rem; }
}

🎨 Live Examples

Attribute Selector Examples:

Input Types:

Responsive Design Info:

Resize your browser to see responsive changes!

Media queries adapt layouts for different screen sizes

📝 Test Your Knowledge - MCQ

Q1: Which selector targets links ending with .pdf?

Q2: What does [href*="google"] select?

Q3: What is the correct syntax for a max-width media query?

Q4: Which media feature detects dark mode preference?

Q5: What does [attribute^="value"] match?

💪 Practice Questions

  1. Select all links starting with "https" and make them green using attribute selectors.
  2. Add a PDF icon (📄) after all links ending with ".pdf" using ::after pseudo-element.
  3. Create a media query that changes a 3-column grid to 1 column on screens smaller than 768px.
  4. Style all required input fields with a red left border using [required] selector.
  5. Write a media query for dark mode that changes background to dark and text to light colors.

📌 Summary

  • [attribute]: Has attribute
  • [attribute="value"]: Exact match
  • [attribute^="value"]: Starts with value
  • [attribute$="value"]: Ends with value
  • [attribute*="value"]: Contains value anywhere
  • [attribute~="value"]: Space-separated word match
  • [attribute|="value"]: Hyphen-separated start
  • Case insensitive: Add i flag (e.g., [href$=".pdf" i])
  • Data attributes: Use [data-*] for custom attributes
  • Media queries: @media (condition) { }
  • Common breakpoints: 576px, 768px, 992px, 1200px
  • Mobile first: Use min-width
  • Desktop first: Use max-width
  • prefers-color-scheme: Detect dark/light mode
  • orientation: portrait or landscape
← Back to Content Next Topic: CSS Images →