css 头部制作
CSS 头部制作方法
固定定位法
使用 position: fixed 将头部固定在页面顶部,确保滚动时始终可见。设置 top: 0 和 width: 100% 以覆盖整个视口宽度,通过 z-index 控制层级避免被其他元素覆盖。
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
Flexbox 布局法
通过 Flexbox 实现头部内容水平或垂直排列。justify-content 控制子元素的对齐方式,align-items 调整垂直对齐,适合包含导航菜单或 Logo 的复杂布局。
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background-color: #333;
color: white;
}
响应式设计适配
使用媒体查询调整头部样式以适应不同屏幕尺寸。例如,在小屏幕上隐藏部分内容或切换为汉堡菜单。
@media (max-width: 768px) {
.header nav {
display: none;
}
.hamburger-menu {
display: block;
}
}
透明渐变效果
通过 CSS 渐变或 rgba 实现透明背景,结合滚动事件动态添加阴影以增强视觉层次。
.header {
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.7), transparent);
transition: background 0.3s;
}
.header.scrolled {
background: rgba(0, 0, 0, 0.9);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
粘性定位替代方案
若需头部在特定位置变为固定定位,可使用 position: sticky。设置 top: 0 使元素在到达视口顶部时粘附。
.header {
position: sticky;
top: 0;
background-color: #f8f9fa;
}
注意事项
- 固定定位头部会占用文档流空间,需为页面主体添加
padding-top避免内容被遮挡。 - 测试不同浏览器的兼容性,特别是 Safari 对
sticky的支持。







