CSS选择器

来源:互联网 发布:手机淘宝口令 编辑:程序博客网 时间:2024/06/05 14:59

1.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 文档中出现一次。



2.类选择器

在 CSS 中,类选择器以一个点号显示:

.center {text-align: center}

在上面的例子中,所有拥有 center 类的 HTML 元素均为居中。

在下面的 HTML 代码中,h1 和 p 元素都有 center 类。这意味着两者都将遵守 ".center" 选择器中的规则。

<h1 class="center">This heading will be center-aligned</h1><p class="center">This paragraph will also be center-aligned.</p>

注意:类名的第一个字符不能使用数字!它无法在 Mozilla 或 Firefox 中起作用。

元素也可以基于它们的类而被选择:

td.fancy {color: #f60;background: #666;}

在上面的例子中,类名为 fancy 的表格单元将是带有灰色背景的橙色。

<td class="fancy">

p.spread {word-spacing: 30px;}p.tight {word-spacing: -0.5em;}<p class="spread">This is a paragraph. The spaces between words will be increased.</p><p class="tight">This is a paragraph. The spaces between words will be decreased.</p>


3.属性选择器 

对带有指定属性的 HTML 元素设置样式。

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

注释:只有在规定了 !DOCTYPE 时,IE7 和 IE8 才支持属性选择器。在 IE6 及更低的版本中,不支持属性选择。

属性选择器

下面的例子为带有 title 属性的所有元素设置样式:

[title]{color:red;}


属性选择器在为不带有 class 或 id 的表单设置样式时特别有用:

<html>
<head>
<style>
input[type="text"]
{
  width:150px;
  display:block;
  margin-bottom:10px;
  background-color:yellow;
  font-family: Verdana, Arial;
}


input[type="button"]
{
  width:120px;
  margin-left:35px;
  display:block;
  font-family: Verdana, Arial;
}
</style>
</head>
<body>


<form name="input" action="" method="get">
<input type="text" name="Name" value="Bill" size="20">
<input type="text" name="Name" value="Gates" size="20">
<input type="button" value="Example Button">


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

0 0