CSS属性选择器

具有特定属性的HTML元素样式

具有特定属性的HTML元素样式不仅仅是class和id。

注意:IE7和IE8需声明!DOCTYPE才支持属性选择器!IE6和更低的版本不支持属性选择器。

属性选择器

下面的例子是把包含标题(title)的所有元素变为蓝色:

<!DOCTYPE html>
<html>
<head>
<style>
[title]
{
color:blue;
}
</style>
</head>
<body>
<h2>Will apply to:</h2>
<h1 title="Hello world">Hello world</h1>
<a title="manongjc" href="http://www.catroom.com.cn">www.catroom.com.cn</a>
<hr>
<h2>Will not apply to:</h2>
<p>Hello!</p>
</body>
</html>

效果:
属性选择器

属性和值选择器

下面的实例改变了标题title='w3cschool'元素的边框样式:

<html>
<head>
<style>
[title=catroom]
{
border:5px solid green;
}
</style>
</head>

<body>
<h2>Will apply to:</h2>
<img title="catroom" src=""  />
<br>
<a title="catroom" href="http://www.catroom.com.cn">catroom</a>
<hr>
<h2>Will not apply to:</h2>
<p title="greeting">Hi!</p>
<a class="catroom" href="http://www.catroom.com.cn">catroom</a>
</body>
</html>

效果:

属性和值选择器

属性和值的选择器 - 多值

下面是包含指定值的title属性的元素样式的例子,使用(~)分隔属性和值:

<html>
<head>
<style>
[title~=hello]
{
color:blue;
}
</style>
</head>

<body>
<h2>Will apply to:</h2>
<h1 title="hello world">Hello world</h1>
<p title="student hello">Hello CSS students!</p>
<hr>
<h2>Will not apply to:</h2>
<p title="student">Hi CSS students!</p>
</body>
</html>

效果:
多值选择器

下面是包含指定值的lang属性的元素样式的例子,使用(|)分隔属性和值:

<html>
<head>
<style>
[lang|=en]
{
color:blue;
}
</style>
</head>

<body>
<h2>Will apply to:</h2>
<p lang="en">Hello!</p>
<p lang="en-us">Hi!</p>
<p lang="en-gb">Ello!</p>
<hr>
<h2>Will not apply to:</h2>
<p lang="us">Hi!</p>
<p lang="no">Hei!</p>
</body>
</html>

效果:

lang属性

表单样式

属性选择器样式无需使用class或id的形式:

<html>
<head>
<style>
input[type="text"]
{
width:150px;
display:block;
margin-bottom:10px;
background-color:yellow;
}
input[type="button"]
{
width:120px;
margin-left:35px;
display:block;
}
</style>
</head>
<body>

<form name="input" action="demo-form.php" method="get">
Firstname:<input type="text" name="fname" value="Peter" size="20">
Lastname:<input type="text" name="lname" value="Griffin" size="20">
<input type="button" value="Example Button">


</form>
</body>
</html>

效果:

表单样式