css 将div固定在页面顶部不随页面滑动

为了将一个 div 设置为固定在页面顶部,并且高度为 5rem,宽度为 100vw,不随页面滚动,可以使用几种不同的 CSS 技术来实现。下面我将列举几种常见的方法:

1. 使用 position: fixed

最直接的方法是使用 position: fixed,这使得元素相对于视口(浏览器窗口)定位,而不是相对于其包含元素:

.div-fixed {

position: fixed;

top: 0;

left: 0;

width: 100vw;

height: 5rem;

background-color: #f4f4f4; /* 示例背景色 */

z-index: 1000; /* 确保 div 在页面顶层 */

}

2. 使用 position: sticky

position: sticky 可以使元素在页面滚动到某个点之前表现得像 position: relative,之后表现得像 position: fixed。这里,我们可以让它一直处于顶部:

.div-sticky {

position: sticky;

top: 0;

width: 100vw;

height: 5rem;

background-color: #f4f4f4;

z-index: 1000;

}

请注意,position: sticky 可能在某些较老的浏览器中不受支持。

3. 使用 Flexbox 或 Grid 布局(视口高度固定时)

如果整个页面的布局是基于 Flexbox 或 Grid,你也可以使顶部 div 固定,而其他内容滚动:

Flexbox 示例:

.body-flex {

display: flex;

flex-direction: column;

height: 100vh;

}

.div-flex-header {

flex: 0 0 5rem; /* flex-grow, flex-shrink, flex-basis */

width: 100vw;

background-color: #f4f4f4;

}

.content-flex {

flex: 1;

overflow-y: auto; /* 只让内容部分滚动 */

}

HTML 结构:

Header

Content scrolls here

4. 使用 CSS Grid 布局

类似于 Flexbox,但使用 CSS Grid:

.body-grid {

display: grid;

grid-template-rows: 5rem auto;

height: 100vh;

}

.div-grid-header {

grid-row: 1 / 2;

width: 100vw;

background-color: #f4f4f4;

}

.content-grid {

grid-row: 2 / 3;

overflow-y: auto; /* 只让内容部分滚动 */

}

HTML 结构:

Header

Content scrolls here

以上每种方法都有其用途和场合,可以根据你的具体需求和页面的其他布局需求来选择最适合的方法。 position: fixed 是最直接的方法,而 Flexbox 和 Grid 提供了更复杂的布局可能性,尤其是在需要与页面其他元素紧密布局时。