• 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 在页面顶层 */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请注意,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; /* 只让内容部分滚动 */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    HTML 结构:
    <div class="body-flex">
      <div class="div-flex-header">Headerdiv>
      <div class="content-flex">Content scrolls herediv>
    div>
    
    • 1
    • 2
    • 3
    • 4

    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; /* 只让内容部分滚动 */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    HTML 结构:
    <div class="body-grid">
      <div class="div-grid-header">Headerdiv>
      <div class="content-grid">Content scrolls herediv>
    div>
    
    • 1
    • 2
    • 3
    • 4

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

  • 相关阅读:
    vue3 父组件与子组件v-model双向绑定
    第一关:Linux基础知识
    从table1 里获取每个person_id最大end_date的数据。(inner join)
    postman 密码rsa加密登录-2加密密码
    开源机密计算平台:蓬莱-OpenHarmony
    C++ 引用(&)的超详细解析(小白必看系列)
    第20章 OAuth2LoginAuthenticationWebFilter 之ReactiveAuthenticationManager认证授权管理器
    linux下python导入特定路径的包
    【Java基础】四张图轻松拿捏Java VisualVM添加Visual GC插件实现JVM性能调优
    JavaAPI常用类01
  • 原文地址:https://blog.csdn.net/u013190012/article/details/138189819