CSS 属性 选择器 登录

CSS 属性 选择器

一.什么是属性选择器

  属性选择器就是指,利用html的属性标签作为选择器,其作用是对带有指定属性的HTML元素设置样式。

  属性选择器可以为拥有指定属性的HTML元素设置样式,而不仅限于class和id属性。

  温馨提示:如果使用的是IE浏览器,在IE6或更低版本是不支持属性选择的。IE7也只有在规定了!DOCTYPE时,才支持属性选择器的使用。

二、属性选择器的语法

  属性选择器用[]显示,下面的例子为带有title属性的所有元素设置样式:

  [title]

  {

  color:red;

  }

简易属性选择器

只顾其名不顾其值,这是简易属性选择器的特点。

h1[class] {color: silver;}将会作用于任何带class的h1元素,不管class的值是什么。所以<h1 class="hoopla">Hello</h1>、<h1 class="severe">Serenity</h1>、<h1 class="fancy">Fooling</h1>的h1都会受到这条规则的影响。

当然,这个“属性”不仅仅是class或者id,可以是该元素所有合法属性,比如img的alt,这样img[alt]{css declarations here;}将会作用于任何带有alt属性的img元素。那么a[href][title] {font-weight: bold;}呢?聪明的你一定已经知道,这会作用于同时带href和title属性的a元素,比如<a href="http://php.cn/" title="php Home"></a>。

精确属性值选择器

id和类本质上就是精确属性值选择器,没错,h1#logo等于h1[id="logo"]。如前所述,我们不要局限于id或者class,我们可以使用任何属性!例如a[href="http://php.cn/"][title="W3C Home"] {font-size: 200%;}将会作用于<a href="http://php.cn/" title="php Home"></a>。

部分属性值选择器

如其名,只要属性值部分匹配(这里的部分,实际上要匹配整个单词)就会作用于该元素。让我们来看个例子:

<p class="urgent warning">When handling plutonium, care must be taken to avoid the formation of a critical mass.</p>p[class~="warning"] {font-weight: bold;}    


p[class~="urgent"] {font-weight: bold;}    

中任何一条都可以让这个p的字体变粗。

该选择器十分有用,比如你要样式化插图,其title中都含字符串”Figure”,如 title= "Figure 5:xxx说明",则你可以使用img[title~="Figure"] 。


[title]:选择带有title属性的元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php.cn</title>
<style>
h1[title]{
    color:red;
}
</style>
</head>
<body>
  <h1 title = "属性选择器">标题<h1>
  <p>这是内容</p>
  
  <h1>标题<h1>
  <p>这是内容</p>
</body>
</html>

[title='hello']:选择属性是title并且值是hello的元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php.cn</title>
<style>
h1[title = "hello"]{
    color:red;
}
</style>
</head>
<body>
  <h1 title = "属性选择器">标题<h1>
  <p>这是内容</p>
  
  <h1 title = "hello">标题<h1>
  <p>这是内容</p>
</body>
</html>

[title*='hello']:选择属性是title并且其中包含了hello的元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php.cn</title>
<style>
h1[title*="hello"]{
    color:red;
}
</style>
</head>
<body>
  <h1 title = "hellocss">标题<h1>
  <p>这是内容</p>
  
  <h1 title = "hello css">标题<h1>
  <p>这是内容</p>
</body>
</html>




<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php.cn</title> <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> <!--属性选择器样式无需使用class或id的形式:--> <form name="input" action="/member/edit_course/8" method="get"> 名称1:<input type="text" name="fname" value="tom" size="20"> 名称2:<input type="text" name="lname" value="ros" size="20"> <input type="button" value="提交"> </body> </html>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送