标题与副标题的实现
HTML 中在标题旁边添加副标题的几种方法
问题
如果需要在一个标题的旁边创建副标题,可以怎样操作?
解答
方法一:使用 <small> 标签
<h1>主标题 <small>副标题</small></h1>
<style>
h1 small {
font-size: 0.5em;
color: #666;
font-weight: normal;
}
</style>
方法二:使用 <hgroup> 标签(HTML5)
<hgroup>
<h1>主标题</h1>
<p>副标题说明文字</p>
</hgroup>
<style>
hgroup {
margin-bottom: 1em;
}
hgroup h1 {
margin-bottom: 0.25em;
}
hgroup p {
margin: 0;
color: #666;
font-size: 1rem;
}
</style>
方法三:使用 Flexbox 实现同行显示
<div class="title-group">
<h1>主标题</h1>
<span class="subtitle">副标题</span>
</div>
<style>
.title-group {
display: flex;
align-items: baseline; /* 基线对齐 */
gap: 12px;
}
.title-group h1 {
margin: 0;
}
.subtitle {
font-size: 0.875rem;
color: #888;
}
</style>
方法四:使用伪元素
<h1 class="with-subtitle" data-subtitle="副标题">主标题</h1>
<style>
.with-subtitle::after {
content: attr(data-subtitle);
margin-left: 12px;
font-size: 0.5em;
font-weight: normal;
color: #666;
}
</style>
完整示例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>标题与副标题</title>
<style>
/* 方法一:small 标签 */
.method1 small {
font-size: 0.5em;
color: #666;
font-weight: normal;
margin-left: 8px;
}
/* 方法二:hgroup */
hgroup h2 { margin-bottom: 4px; }
hgroup p { margin: 0; color: #666; font-size: 0.875rem; }
/* 方法三:flexbox */
.flex-title {
display: flex;
align-items: baseline;
gap: 12px;
}
.flex-title h2 { margin: 0; }
.flex-title .sub { color: #888; font-size: 0.875rem; }
</style>
</head>
<body>
<!-- 方法一 -->
<h2 class="method1">文章标题 <small>2024年发布</small></h2>
<!-- 方法二 -->
<hgroup>
<h2>产品介绍</h2>
<p>了解我们的最新功能</p>
</hgroup>
<!-- 方法三 -->
<div class="flex-title">
<h2>用户指南</h2>
<span class="sub">v2.0</span>
</div>
</body>
</html>
关键点
<small>标签语义化好,适合简短的副标题<hgroup>适合标题和描述分行显示的场景- Flexbox 配合
align-items: baseline可实现基线对齐 - 伪元素方案通过
data-*属性传递内容,保持 HTML 简洁 - 副标题通常需要调整
font-size、font-weight和color与主标题区分
目录