css制作页眉
使用HTML和CSS创建页眉
创建一个基本的HTML结构,包含<header>标签作为页眉容器。例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>页眉示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>网站标题</h1>
<nav>
<ul>
<li><a href="#">首页</a></li>
<li><a href="#">关于</a></li>
<li><a href="#">联系</a></li>
</ul>
</nav>
</header>
</body>
</html>
基础样式设计
在CSS文件中为页眉添加样式,包括背景色、内边距和布局:
header {
background-color: #333;
color: white;
padding: 1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
nav ul {
display: flex;
list-style: none;
gap: 1rem;
}
nav a {
color: white;
text-decoration: none;
}
响应式设计
添加媒体查询使页眉在不同屏幕尺寸下适应:

@media (max-width: 768px) {
header {
flex-direction: column;
text-align: center;
}
nav ul {
flex-direction: column;
gap: 0.5rem;
}
}
固定定位页眉
如果需要页眉始终固定在页面顶部:
header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
}
body {
padding-top: 60px; /* 避免内容被页眉遮挡 */
}
添加悬停效果
为导航链接添加交互效果:

nav a:hover {
color: #ff9900;
text-decoration: underline;
}
使用CSS变量
定义CSS变量便于统一管理和修改样式:
:root {
--header-bg: #333;
--header-text: white;
--hover-color: #ff9900;
}
header {
background-color: var(--header-bg);
color: var(--header-text);
}
nav a:hover {
color: var(--hover-color);
}
添加阴影效果
为页眉添加细微的阴影增强层次感:
header {
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}






