<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo01</title>
<style>
.center {
text-align:center;
}
.color {
color:#ff0000;
}
</style>
</head>
<body>
<h1 class="center">标题居中</h1>
<p class="center color">段落居中,颜色为红色。</p>
</body>
</html>
如果我们要在 html 元素中设置 css 样式,那么就需要需要在元素中设置选择器,即决定当前元素使用哪种样式。一般来说,常用的选择器有四种:id 选择器、类选择器、标签选择器和内联选择器。
id 选择器
id 选择器可以为标有特定 id 的 html 元素指定特定的样式。html 元素以 id 属性来设置 id 选择器,css 中 id 选择器以 "#" 来定义。如:
<style>
#para1 {
text-align:center;
color:red;
}
</style>
需要注意的是这种 id 选择器同时适用于外部样式表和内部样式表,也就是说 id 选择器的写法在外部样式表(.css 文件)和内部样式表(<style> 标签)中的写法是一样的。同时需要注意的是 id 属性建议不要以数字开头,因为数字开头的 id 在 Mozilla/Firefox 浏览器中不起作用。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo01</title>
<style>
#para1
{
text-align:center;
color:red;
font-size:30px;
}
</style>
</head>
<body>
<p id="para1">字体颜色为红色,居中,字号为30px</p>
<p>这个段落不受该样式的影响。</p>
</body>
</html>
使用内部样式表的方式引用 css 样式,通过设置元素的 id 属性来选择 id 选择器为元素增加样式。
class 选择器
class 选择器用于描述一组元素的样式,class 选择器有别于 id 选择器,class 可以在多个元素中使用。
class 选择器在 html 中以 class 属性表示,在 css 中,类选择器以"."号显示。如:
<style>
.center {
text-align:center;
}
</style>
同 id 选择器一样,class 选择器也可同时适用于外部样式表和内部样式表。类名的第一个字符不能使用数字,因为它无法在 Mozilla 或 Firefox 中起作用。
如,对所有的 p 元素使用 class="center" 让该元素的文本居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo01</title>
<style>
p.center
{
text-align:center;
}
</style>
</head>
<body>
<h1 class="center">这个标题不受影响</h1>
<p class="center">这个段落居中对齐。</p>
</body>
</html>
<p> 标签通过设置 class 属性使用了 ".center" 的 class 选择器,所有 <p> 标签内的文字就有了居中的效果,而 <h1> 标签虽然也设置了 class 属性,但是".center"的选择器只适用于 <p> 标签,所以 <h1> 标签内的文字并没有居中效果。如果想让 <h1> 和 <p> 标签内的文字都有居中的效果,则只需要改变一下 class 选择器的名称即可。
class 选择器:.center
如果要使用多个 class 选择器的话需要使用空格分开:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo01</title>
<style>
.center {
text-align:center;
}
.color {
color:#ff0000;
}
</style>
</head>
<body>
<h1 class="center">标题居中</h1>
<p class="center color">段落居中,颜色为红色。</p>
</body>
</html>
标签选择器
即以 html 标签名作为 css 修饰所用的选择器。如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo01</title>
<style>
p {
text-align:center;
}
h1 {
color:red;
}
</style>
</head>
<body>
<h1>这个标题文字颜色为红色</h1>
<h2>这个标题没有样式</h2>
<p>这个段落居中对齐</p>
</body>
</html>
内联选择器
即直接在 html 标签内部通过 style 属性写 css 代码,如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo01</title>
</head>
<body>
<h1 style="color:blue;">这个标题文字颜色为蓝色</h1>
<h2>这个标题没有样式</h2>
<p style="text-align:center;">这个段落居中对齐</p>
</body>
</html>
这四种 css 选择器有修饰上的优先级,即:内联选择器 > id 选择器 > class 选择器 > 标签选择器。
除此之外,还有属性选择器、包含选择器、子选择器和 CSS3 中新增的兄弟选择器,不过最常用的就是内联、id、class 和标签选择器。
本文参考自:CSS Id 和 Class选择器 | 菜鸟教程