css制作网页头部
制作网页头部的CSS方法
固定定位头部
使用position: fixed确保头部始终停留在页面顶部,不随滚动条移动。设置width: 100%和top: 0覆盖整个视窗宽度,z-index值需高于其他元素避免被遮挡。
.header {
position: fixed;
top: 0;
width: 100%;
background-color: #ffffff;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index: 1000;
}
Flex布局导航菜单
通过display: flex实现水平排列的导航项,justify-content控制对齐方式,align-items垂直居中。内边距和间距增强可读性。

.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 5%;
}
.nav-item {
margin: 0 1rem;
color: #333;
text-decoration: none;
}
响应式设计
使用媒体查询适配移动设备。小屏幕下隐藏常规菜单,显示汉堡菜单图标。

@media (max-width: 768px) {
.nav-menu {
display: none;
}
.hamburger {
display: block;
cursor: pointer;
}
}
渐变或背景图效果
通过CSS渐变或背景图片增强视觉吸引力。线性渐变可配合background-image属性使用。
.header-hero {
background-image: linear-gradient(to right, #6a11cb, #2575fc);
color: white;
text-align: center;
padding: 4rem 0;
}
粘性头部替代方案
若需部分滚动后固定头部,可使用position: sticky。需指定top: 0并确保父容器未设置overflow: hidden。
.sticky-header {
position: sticky;
top: 0;
background: rgba(255,255,255,0.9);
backdrop-filter: blur(5px);
}






