How to keep the header static, always on top while scrolling?

前端 未结 8 793
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 08:15

How would I go about keeping my header from scrolling with the rest of the page? I thought about utilizing frame-sets and iframes, jus

8条回答
  •  醉梦人生
    2020-12-02 09:06

    In modern, supported browsers, you can simply do that in CSS with -

    header{
      position: sticky;
      top: 0;
    }
    

    Note: The HTML structure is important while using position: sticky, since it's make the element sticky relative to the parent. And the sticky positioning might not work with a single element made sticky within a parent.

    Run the snippet below to check a sample implementation.

    main{
    padding: 0;
    }
    header{
    position: sticky;
    top:0;
    padding:40px;
    background: lightblue;
    text-align: center;
    }
    
    content > div {
    height: 50px;
    }
    This is my header
    Some content 1
    Some content 2
    Some content 3
    Some content 4
    Some content 5
    Some content 6
    Some content 7
    Some content 8

提交回复
热议问题