为黄梅戏分享会建立统一样式
同一段通知,三种引入样式的方式
下面用三种方式设置同一段通知的文字颜色,观察 CSS 分别写在哪里。
① 行内:写在元素的 style 属性中
<p style="color:teal">周三14:00 · A208</p>
声明直接写在这个元素上,不写选择器。只设置这个元素;多个元素重复使用时,需要逐个修改。
② 内部:在 HTML 的 head 中写 style
<head> 用来放页面的说明和配置,内部样式表 <style> 按 HTML 规范应放在 <head> 中;<body> 则放标题、段落等页面内容。
<style>
.notice { color: teal; }
</style>
<!-- 以下写在 body 中 -->
<p class="notice">周三14:00 · A208</p>
.notice 匹配带有 notice 类的元素。这份规则写在当前 HTML 中,可供当前页面的多个元素使用。
③ 外部:用 link 连接独立 CSS 文件
<link rel="stylesheet" href="shared.css">
<!-- 以下写在 body 中 -->
<p class="notice">周三14:00 · A208</p>
link 放在 head 中;rel="stylesheet" 说明链接的是样式表,href 指定文件路径。
shared.css 中的通知样式
.notice {
color: teal;
}
独立 CSS 文件只写 CSS,不加 <style> 标签。多个 HTML 页面可以引入同一份 CSS,统一修改样式。
展开完整示例代码
demo/inline.html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>行内样式</title>
</head>
<body>
<p style="color:teal">周三14:00 · A208</p>
</body>
</html>
demo/internal.html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>内部样式</title>
<style>
.notice { color: teal; }
</style>
</head>
<body>
<p class="notice">周三14:00 · A208</p>
</body>
</html>
demo/home.html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>黄梅戏分享会</title>
<link rel="stylesheet" href="shared.css">
</head>
<body>
<h1>黄梅戏分享会</h1>
<p class="notice">周三14:00 · A208</p>
<a href="details.html">查看详情</a>
</body>
</html>
demo/shared.css
body { margin:16px; font-family:"Times New Roman",SimSun,serif; color:#18314f; }
h1 { font-family:"Times New Roman",SimHei,sans-serif; font-size:24px; }
.notice { color:teal; line-height:1.7; }