Explain Codes LogoExplain Codes Logo

Select elements by attribute in CSS

html
responsive-design
css-selectors
attribute-selectors
Alex KataevbyAlex Kataev·Sep 7, 2024
TLDR

To select elements based on attributes in CSS, make use of attribute selectors:

  • [attr]: Targets elements with attr, irrespective of value.
  • [attr=value]: Selects elements with attr exactly equalling value.
  • [attr*=value]: Catches elements whose attr contains value somewhere.

Consider:

/* When your elements state their data, boldy heed */ [data-state] { font-weight: bold; } /* When your anchors feel at '#home', make 'em green */ a[href="#home"] { color: green; } /* Bring the heat to buttons that 'submit' */ button[type*="submit"] { background: red; }

Their ultimate power lies in focussed attribute targeting, permitting on-point style surgeries.

Delving deeper into attribute selectors

Attribute selectors open up a trove of options for element pinpointing—think Haute Couture for your HTML! Breadcrumbs to custom data attributes, their versatility provides room for your CSS to break styling barriers.

  • Spot-on match: [attr='value'] perfect for tight spaces (e.g., tailor-made input styles).
  • Partial hits: [attr*='partOfValue']come in handy when breadth over accuracy matters.

All attributes are fair game for these workhorses—including HTML5 data attributes (data-*), enriching both semantic web design and accessibility.

Selector triage: When to pull which trigger

  • App states: [data-state='active'] ideal for style swings based on live data.
  • Language variants: [lang|='en'] flex CSS muscle for multilingual sites by playing nice with hyphen-separated attributes.
  • Responsive design hacks: [size~='large'] customize styles using size attributes.

Combo power: Styling on steroids

Unleash the true power of attribute selectors and create style magic by mixing them up:

/* When an active button is disabled, it feels...blue */ button[data-state='active'][disabled] { background-color: blue; cursor: not-allowed; }

Troubleshooting attribute selectors

Case of the shifting cases

Attribute selectors are default case-sensitive. Use the i flag for case-blind matches:

/* When it doesn't matter if you're SHOUTING or whispering */ [attr='value' i] { color: purple; }

The need for speed

Attribute selectors aren't speed demons, and overuse, especially in substring matches, may slow down render speed. Use class or ID selectors where speed is paramount.

Staying ahead with browser support

Check Can I use... before unholstering complex selectors to ensure friendly cross-browser compatibility.

Visualising attribute selectors

Think of CSS as a toolbox, with each tool (selectors) targeting different types of screws (HTML elements).

The toolbox (CSS): |*spanner*| (element type) |🔧| |*tape measure*| (class) |📏| |*hammer*| (id) |🔨| |*screwdriver*| (**attribute**) |🔩|

Attribute selectors (🔩) are like screwdrivers:

/* Dial-a-screw? Use an attribute selector */ [wrench-size='10mm'] { /* "Paint me yellow, 'coz I'm just '10mm' right"! */ background-color: yellow; }

Attribute selectors, the secret to precision styling.

Enhancing your CSS skill set

Pushing the envelope

Dabble with combination selectors for fancy styling stunts:

  • Chain attribute selectors for an ultra-specific target.
  • Mix with class and element selectors to refine CSS sniping.

CSS-JS Symbiosis

CSS attribute selectors work seamlessly with document.querySelector:

// JavaScript's CSS impression const activeButtons = document.querySelectorAll('button[data-state="active"]');

The upshot? A happy confluence of CSS-JS, leading to superb interactive designs.

Non-standard attribute enlightenment

Sure, browsers grudgingly accept non-standard attributes, but always use data-* attributes for custom data—keep your HTML legit, and retain the separation of concerns.