最近两星期都在学习CSS,觉得选择器是其中比较重要的一个点,所以记录一下,以作日后查询。
派生选择器
派生选择器允许你根据文档的上下文关系来确定某个标签的样式。
例如若希望列表中的 strong 元素变为斜体字,而不是通常的粗体字,可以这样定义一个派生选择器:
<head>
<style type="text/css">
li strong {
font-style: italic;
font-weight: normal;
}
</style>
</head>
<pre name="code" class="html"><pre name="code" class="css"><pre name="code" class="html"><p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>
<ol>
<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>
效果图如下:
id选择器
id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。
id 选择器以 "#" 来定义。
下面的两个 id 选择器,第一个可以定义元素的颜色为红色,第二个定义元素的颜色为绿色:
#red {color:red;}
#green {color:green;}
下面的 HTML 代码中,id 属性为 red 的 p 元素显示为红色,而 id 属性为 green 的 p 元素显示为绿色。
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
注意:
id 属性只能在每个 HTML 文档中出现一次。
在现代布局中,id 选择器常常用于建立派生选择器。
#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}
上面的样式只会应用于出现在 id 是 sidebar 的元素内的段落。
类选择器
在 CSS 中,类选择器以一个点号显示:
.center {text-align: center}
在下面的 HTML 代码中,h1 和 p 元素都有 center 类。
<h1 class="center">
This heading will be center-aligned
</h1>
<p class="center">
This paragraph will also be center-aligned.
</p>
注意:
类名的第一个字符不能使用数字!它无法在 Mozilla 或 Firefox 中起作用。
和 id 一样,class 也可被用作派生选择器:
td.fancy {
color: #f60;
background: #666;
}
类名为 fancy 的表格单元将是带有灰色背景的橙色。
<td class="fancy">
你可以将类 fancy 分配给任何一个表格元素任意多的次数。那些以 fancy 标注的单元格都会是带有灰色背景的橙色。
属性选择器
对带有指定属性的 HTML 元素设置样式。
<span style="font-size:14px;"><html>
<head>
<style type="text/css">
[title]
{
color:red;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<h2 title="Hello world">Hello world</h2>
<a title="Test" ">Test</a>
<hr />
<h1>无法应用样式:</h1>
<h2>Hello world</h2>
<a>Test</a>
</body>
</html></span>
效果图如下: