阅读(1918)

CSS 属性选择器

最后一次修改 2017年08月03日

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="html" href="http://html.cn">html</a>
<hr>
<h2>Will not apply to:</h2>
<p>Hello!</p>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


属性和值选择器

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

实例

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

<body>
<h2>Will apply to:</h2>
<img title="html" src="http://img.php.cn/upload/content/000/000/001/59817c5286471132.png" width="247 height="48" />
<br>
<a title="html" href="http://html.cn">html</a>
<hr>
<h2>Will not apply to:</h2>
<p title="greeting">Hi!</p>
<a class="html" href="http://html.cn">html</a>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


属性和值的选择器 - 多值

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

实例

<!DOCTYPE html>
<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属性的元素样式的例子,使用(|)分隔属性和值:

实例

<!DOCTYPE html>
<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>

运行实例 »

点击 "运行实例" 按钮查看在线实例


表单样式

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

实例

<!DOCTYPE html>
<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" 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>

运行实例 »

点击 "运行实例" 按钮查看在线实例