---
title: "第2章 选择器  =>属性值选择器 P46"
author: "conkeyn"
date: "2009-04-26T23:05:32Z"
tags: ["CSS", "HTML", "XHTML"]
slug: "2-p46"
draft: false
lastmod: "2009-04-26T23:55:13Z"
id: 375236
url: "https://conkeyn.iteye.com/blog/375236"
---

**属性值 选择器**

 

除了可以选择有某些属性的元素外，还可以进一步缩小选择范围，只选择有特定属性值的元素。

1、可以根据具体的属性值选择；

2、可以根据部分属性值选择；

 

1、根据具体属性值选择

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>根据具体属性值选择</title>
<style type="text/css">
a[href="http://www.w3.org/"][title="W3C Home"]{
	font-size:200%;	
}
</style>
</head>

<body>
<p>1、<a href="http://www.w3.org/" >W3C Home</a></p>
<p>2、<a href="http://www.w3.org/" title="W3C Home">W3C Home</a></p>
<p>3、<a href="#" title="W3C Home">W3C Home</a></p>
<p>4、<a href="http://www.w3.org" title="W3C Home">W3C Home</a></p>
</body>
</html>
```

 显示效果：

![](/upload/attachment/98080/01106dbc-cf60-3ed4-b245-327792d528fa.bmp)

注意，这种格式要求必须与属性值完全匹配。 如果遇到的值本身包含一个用空格分隔的值列表达，匹配就会出问题。例如，考虑以下标记片段：

&lt;planet type="barren rocky"&gt;Mercury&lt;/planet&gt;

要根据具体属性值匹配这个元素，唯一的办法就是写作：

planet\[type="barren rocky"]{font-weight:blod;}

 

 

示例3：

&lt;p class="urgent warning"&gt;When handling plutonium,care must be taken to avoid the formation of a critaical mass.&lt;/p&gt;

要根据具体属性值来选择这个元素，必须写作：p\[class="urgent warning"]{font-weight:blod;}

这不同于多类选择器（class中的属性值与顺序无关），需要完全匹配。

 

//==================================================

 

2、根据部分属性值选择器

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>根据部分属性值选择器/title>
<style type="text/css">
span[class~="barren"]{
	font-style:italic;
}
</style>
</head>

<body>
<p>1、<span class="barren rocky"


>Mercury</span></p>
<p>2、
  <span class="cloudy barren"


>Venue</span></p>
<p>3、
  <span class="life-bearing cloudy">Jason</span></p>
  <p>4、
  <span class="one-barren cloudy"


>Tom</span></p>
</body>
</html>
```

 显示效果：

![](/upload/attachment/98092/d85a8b8b-2c33-3be8-a34b-301751e10206.bmp)

请注意代码与显示效果的差别，红色的class="on-barren cloudy"将不匹配，也就是说用空格将"on-barren cloudy"分隔开之后出现"on-barren"和"cloudy"子串，与"barren"不匹配。

注意，选择器中出现了一个波浪号（~）。这正是部分选择的关键，即根据属性值中出现的一个用空格分隔的词来完成选择。如果忽略了这个波浪号，就变了完全值匹配。

类型

描述

\[foo^=”bar”]

选择 foo 属性值以 ”bar” 开头的所有元素

\[foo$=”bar”]

选择 foo 属性值以 ”bar” 结尾的所有元素

\[foo\*=”bar”]

选择 foo 属性值包含子串 ”bar” 的所有元素

\[foo~=”bar”]

选择 foo 属性值先使用空格分隔开，其中包含子串 ”bar” 的所有元素。根据属性值中出现的一个用空格分隔的词来完成选择。