如何选择并插入样式表:
当大量页面需要更改样式时,外部样式表是最好的选择。
插入方法:每个页面使用 <link> 标签链接到样式表。<link> 标签在(文档的)头部:
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
浏览器会从文件 mystyle.css 中读到样式声明,并根据它来格式文档。
样式表应该以 .css 扩展名进行保存。
下面是一个样式表文件的例子:
p {margin-left: 20px;}
当单个文档需要特殊的样式时,就应该使用内部样式表。
你可以使用 style标签在文档头部定义内部样式表,就像这样:
<head>
<style type="text/css">
hr {color: sienna;}
p {margin-left: 20px;}
body {background-image: url("images/back40.gif");}
</style>
</head>
更改特定内容的样式,选择内联样式。
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>
选择器分类:
标记选择器
title标签后添加
<style type="text/css">
p{
color:
font-size: 10px
}
</style>
类选择器
在实际应用中,不会像上节中所有段落都要是红色的,如果仅希望一部分段落是红色的,另一部分段落是蓝色的,该怎么做呢?这就需要用到类别选择器。用户可以自由定义类别选择器名称
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>类别选择器</title>
<style type="text/css">
.blue{
color: aqua;
}
.big{
font-size: 40px;
}
</style>
</head>
<body>
<p class="blue">对单个标签生效</p>
<p class="big">对单个标签生效</p>
<p class="blue big">对单个标签生效</p>
</body>
</html>
id选择器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>类别选择器</title>
<style type="text/css">
#blue{
color: aqua;
}
#big{
font-size: 40px;
}
</style>
</head>
<body>
<p id="blue">对单个标签生效</p>
<p id="big">对单个标签生效</p>
<p id="blue big">ID选择器不支持多个复用</p>
</body>
</html>
后代选择器
<head>
<style type="text/css">
h1 em {color:red;}
</style>
</head>
子选择器
<head>
<style type="text/css">
h1 > strong {color:red;}
</style>
</head>
兄弟选择器
<head>
<style type="text/css">
h1 + p {margin-top:50px;}
</style>
</head>
<body>
<h1>This is a heading.</h1>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
</body>
属性选择器
<head>
<style type="text/css">
[title]
{
color:red;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<h2 title="Hello world">Hello world</h2>
<a title="W3School" href="http://w3school.com.cn">W3School</a>
<hr />
<h1>无法应用样式:</h1>
<h2>Hello world</h2>
<a href="http://w3school.com.cn">W3School</a>
</body>
伪类
在支持 CSS 的浏览器中,链接的不同状态都可以不同的方式显示,这些状态包括:活动状态,已被访问状态,未被访问状态,和鼠标悬停状态。
<head>
<style type="text/css">
a:link {color: #FF0000}
a:visited {color: #00FF00}
a:hover {color: #FF00FF}
a:active {color: #0000FF}
</style>
</head>
<body>
<p><b><a href="/index.html" target="_blank">这是一个链接。</a></b></p>
<p><b>注释:</b>在 CSS 定义中,a:hover 必须位于 a:link 和 a:visited 之后,这样才能生效!</p>
<p><b>注释:</b>在 CSS 定义中,a:active 必须位于 a:hover 之后,这样才能生效!</p>
</body>
伪元素
"first-line" 伪元素用于向文本的首行设置特殊样式。
在下面的例子中,浏览器会根据 "first-line" 伪元素中的样式对 p 元素的第一行文本进行格式化:
<head>
<style type="text/css">
p:first-line
{
color: #ff0000;
font-variant: small-caps
}
</style>
</head>
<body>
<p>
You can use the :first-line pseudo-element to add a special effect to the first line of a text!
</p>
</body>