阿里云主机折上折
  • 微信号
Current Site:Index > Attribute selector

Attribute selector

Author:Chuan Chen 阅读数:6036人阅读 分类: CSS

Attribute selectors are a powerful type of selector in CSS3 that allow developers to precisely match elements based on their attributes or attribute values. They provide multiple matching patterns, from simple attribute existence checks to complex value-matching rules, greatly enhancing the flexibility of style control.

Basic Syntax and Types

Attribute selectors use square brackets [] to enclose the target attribute, with the basic syntax structure as follows:

[attribute] {
  /* Style rules */
}

The CSS3 specification defines seven types of attribute selectors:

  1. Existence selector: [attr]
  2. Equality selector: [attr=value]
  3. Contains-word selector: [attr~=value]
  4. Prefix selector: [attr^=value]
  5. Suffix selector: [attr$=value]
  6. Substring selector: [attr*=value]
  7. Hyphen selector: [attr|=value]

Existence Selector

The simplest form checks for the existence of an attribute, regardless of its value:

/* Select all elements with a title attribute */
[title] {
  border: 1px dashed #ccc;
}

This selector will match all the following elements:

<img src="logo.png" title="Company Logo">
<div title="Description">Content Block</div>

Exact Value Matching

When using the equals sign for exact value matching, note that the values must be identical (including case sensitivity):

/* Match input elements with type attribute value "text" */
input[type="text"] {
  background-color: #f0f0f0;
}

This selector will exactly match:

<input type="text">

But will not match:

<input type="TEXT">
<input type="text ">

Contains-Word Matching

The tilde ~ is used to match words separated by spaces in attribute values:

/* Match elements whose class attribute contains the word "warning" */
[class~="warning"] {
  color: #c00;
}

Valid matching examples:

<p class="alert warning">Attention Content</p>
<div class="warning-box">Warning Box</div> <!-- Will not match -->

Prefix Matching

The caret ^ is used to match the beginning of an attribute value:

/* Match links whose href attribute starts with "https" */
a[href^="https"] {
  padding-left: 20px;
  background: url(lock-icon.png) no-repeat left center;
}

Typical application scenario:

<a href="https://example.com">Secure Link</a>
<a href="http://example.com">Regular Link</a> <!-- Will not match -->

Suffix Matching

The dollar sign $ is used to match the end of an attribute value:

/* Match images whose src attribute ends with ".png" */
img[src$=".png"] {
  border: 2px solid #00f;
}

Actual matching cases:

<img src="logo.png">
<img src="icon.jpg"> <!-- Will not match -->

Substring Matching

The asterisk * enables substring matching at any position:

/* Match all links whose href attribute contains "example" */
a[href*="example"] {
  font-weight: bold;
}

Matching scope includes:

<a href="https://example.com">
<a href="http://test.example.org">
<a href="#example-anchor">

Hyphen Matching

The pipe | is designed for language subcodes or hyphenated values:

/* Match elements whose lang attribute equals "zh" or starts with "zh-" */
[lang|="zh"] {
  font-family: "Microsoft YaHei", sans-serif;
}

Applicable cases:

<p lang="zh">Simplified Chinese</p>
<p lang="zh-CN">Mainland China</p>
<p lang="zh-TW">Taiwan Region</p>

Combination Techniques

Attribute selectors can be combined with other selectors:

/* Match button elements whose class contains "btn" and type is "submit" */
button[class~="btn"][type="submit"] {
  background: linear-gradient(#4caf50, #388e3c);
  color: white;
}

Corresponding HTML structure:

<button class="primary btn" type="submit">Submit</button>
<button class="btn" type="button">Cancel</button> <!-- Will not match -->

Case-Insensitive Control

The i identifier enables case-insensitive matching:

/* Match elements whose data-type attribute value is "feature" (case-insensitive) */
[data-type="feature" i] {
  border-left: 3px solid #ff9800;
}

Matching examples:

<div data-type="Feature">Feature 1</div>
<div data-type="FEATURE">Feature 2</div>
<div data-type="feature">Feature 3</div>

Practical Application Examples

Form Styling Enhancement

/* Add icons for different types of input fields */
input[type="email"] {
  background: url(email-icon.png) no-repeat 10px center;
  padding-left: 40px;
}
input[type="tel"] {
  background: url(phone-icon.png) no-repeat 10px center;
  padding-left: 40px;
}

Link Security Notices

/* Add special styles for external links */
a[href^="http://"]:not([href*="mysite.com"]):after {
  content: " (External)";
  font-size: 0.8em;
  color: #999;
}

Responsive Image Handling

/* Display format information based on image type */
img[src$=".jpg"]:after,
img[src$=".jpeg"]:after {
  content: " [JPEG Image]";
}
img[src$=".png"]:after {
  content: " [PNG Image]";
}

Performance Optimization Tips

  1. Avoid Overuse: Attribute selectors have higher computational costs than class selectors
  2. Rightmost Principle: Make the rightmost part of the selector more specific
  3. Scope Limitation: Use with element selectors, e.g., div[data-widget] is better than [data-widget]
/* Not recommended */
[data-tooltip] { ... }

/* Recommended */
button[data-tooltip] { ... }

Browser Compatibility Solutions

For scenarios requiring support for older browsers like IE8:

/* Modern browsers */
[class^="col-"] {
  float: left;
}

/* IE8 fallback */
.col-1, .col-2, .col-3 {
  float: left;
}

Integration with CSS Preprocessors

Dynamic attribute selectors can be generated in Sass/Less:

// Automatically generate spacing utility classes
@for $i from 1 through 5 {
  [data-pad="#{$i}"] {
    padding: #{$i * 5}px;
  }
}

Compiled result:

[data-pad="1"] { padding: 5px; }
[data-pad="2"] { padding: 10px; }
/* ... */

Usage in JavaScript

Attribute selectors are also commonly used in DOM queries:

// Get all external links
const externalLinks = document.querySelectorAll(
  'a[href^="http://"]:not([href*="mysite.com"]), ' +
  'a[href^="https://"]:not([href*="mysite.com"])'
);

Special Character Handling

When attribute values contain special characters, escaping is required:

/* Match attribute values containing parentheses */
[data-id="item\(1\)"] {
  background: yellow;
}

Corresponding HTML:

<div data-id="item(1)">Special Content</div>

Priority of Attribute Selectors

The priority weight of attribute selectors is equivalent to class selectors:

/* Priority: 0-1-1 */
div[title="help"] { color: blue; }

/* Priority: 0-1-0 */
[title] { color: red; }

/* Priority: 0-1-1 */
.warning[title] { color: yellow; }

Dynamic Attribute Matching

Combine with CSS variables for dynamic style control:

[data-theme="dark"] {
  --bg-color: #333;
  --text-color: #fff;
}
[data-theme="light"] {
  --bg-color: #fff;
  --text-color: #333;
}

body {
  background: var(--bg-color);
  color: var(--text-color);
}

Pseudo-Class Combination

Attribute selectors can be combined with pseudo-classes for complex interactions:

/* Add styles for required form fields */
input[required]:focus {
  box-shadow: 0 0 5px rgba(255, 0, 0, 0.5);
}
input[required]:invalid {
  border-color: #f00;
}

Usage in Media Queries

Combine with media queries in responsive design:

/* Hide large images on small screens */
@media (max-width: 600px) {
  img[data-size="large"] {
    display: none;
  }
}

Accessibility Enhancement

Use with ARIA attributes to improve accessibility:

[aria-expanded="true"]::after {
  content: "▼";
}
[aria-expanded="false"]::after {
  content: "►";
}

Future Development Directions

New features proposed in the CSS4 draft:

/* Match attribute values starting with a specific word (CSS4 proposal) */
[attribute^="value" s] {
  /* Style rules */
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:伪类与伪元素

下一篇:变量与主题切换

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.