1、元素选择器
html {color:black;} h1 {color:blue;} h2 {color:silver;}在 W3C 标准中,元素选择器又称为类型选择器(type selector)
2、组选择器
h1,h2,h3,h4,h5,h6
{
color: green;
}
3、类选择器
.important {color:red;}结合元素选择器,类选择器可以结合元素选择器来使用。
p.important {color:red;}多类选择器
.important {font-weight:bold;}
.warning {font-style:italic;}
.important.warning {background:silver;}
4、ID选择器
#intro {font-weight:bold;}
<p id="intro">This is a paragraph of introduction.</p>
区别 1:只能在文档中使用一次
与类不同,在一个 HTML 文档中,ID 选择器会使用一次,而且仅一次。
区别 2:不能使用 ID 词列表
不同于类选择器,ID 选择器不能结合使用,因为 ID 属性不允许有以空格分隔的词列表。
区别 3:ID 能包含更多含义
类似于类,可以独立于元素来选择 ID。有些情况下,您知道文档中会出现某个特定 ID 值,但是并不知道它会出现在哪个元素上,所以您想声明独立的 ID 选择器。例如,您可能知道在一个给定的文档中会有一个 ID 值为 mostImportant 的元素。您不知道这个最重要的东西是一个段落、一个短语、一个列表项还是一个小节标题。您只知道每个文档都会有这么一个最重要的内容,它可能在任何元素中,而且只能出现一个。在这种情况下,可以编写如下规则:
#mostImportant {color:red; background:yellow;}
5、派生选择器,也称后代选择器
li strong
{
font-style: italic;
font-weight: normal;
}
6、子元素选择器
h1 > strong {color:red;}
结合后代选择器和子选择器table.company td > p
7、相邻兄弟选择器
h1 + p {margin-top:50px;}
html > body table + ul {margin-top:20px;}
8、属性选择器
*[title] {
color:red;
}
a[href] {
color:red;
}
还可以根据多个属性进行选择,只需将属性选择器链接在一起即可,例如,为了将同时有 href 和 title 属性的 HTML 超链接的文本设置为红色,可以这样写:
a[href][titile] {
color:red;
}
为xml元素使用属性元素选择器
属性选择器在 XML 文档中相当有用,因为 XML 语言主张要针对元素和属性的用途指定元素名和属性名。
假设我们为描述太阳系行星设计了一个 XML 文档。如果我们想选择有 moons 属性的所有 planet 元素,使之显示为红色,以便能更关注有 moons 的行星,就可以这样写:
planet[moons] {
color:red;
}
这会让以下标记片段中的第二个和第三个元素的文本显示为红色,但第一个元素的文本不是红色:
<planet>Venus</planet> <planet moons="1">Earth</planet> <planet moons="2">Mars</planet>
a[href="http://www.w3school.com.cn/about_us.asp"] {
color:red;
}
根据部分属性值选择
p[class~="important"] {
color:red;
}
字串匹配属性选择器:
img[src|="figure"] {
border:1px solid gray;
}
9、伪类
selector:psedu-class{property:value}
CSS 类也可与伪类搭配使用
selector.class : psedu-class { property:value}
锚伪类:
a:link {
color:#f00;
}
a:visited {
color:#0f0;
}
a:hover {
color:#f0f;
}
a:active {
color:#00f;
}
伪类和css类:
a.red:visited {
color:#f00;
}
:first-child伪类:
<div><p>These are the necessary steps:</p>
<ul><li>Intert Key</li>
<li>Turn key<strong>clockwise</strong>
</li> <li>Push accelerator</li> </ul> <p>Do<em>not</em>
push the brake at the same time as the accelerator.</p> </div>
在上面的例子中,作为第一个元素的元素包括第一个 p、第一个 li 和 strong 和 em 元素。
给定以下规则:
p:first-child {
font-weight:bold;
}
li:first-child {
text-transform:uppercase;
}
第一个规则将作为某元素第一个子元素的所有 p 元素设置为粗体。第二个规则将作为某个元素(在 HTML 中,这肯定是 ol 或 ul 元素)第一个子元素的所有 li 元素变成大写。
p > i : first-child {
font-weight:bold;
}
lang伪类:
<html> <head> <style type="text/css">q:lang(no) { quotes: "~" "~" }
</style> </head> <body> <p>文字<qlang="no"
>段落中的引用的文字</q>文字</p> </body></html>