Fixed page header overlaps in-page anchors

前端 未结 30 3542
逝去的感伤
逝去的感伤 2020-11-22 00:25

If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:

Is there a way to use the URL anchor (the #fragment part) t

30条回答
  •  感动是毒
    2020-11-22 00:35

    The best way that I found to handle this issue is (replace 65px with your fixed element height):

    div:target {
      padding-top: 65px; 
      margin-top: -65px;
    }
    

    If you do not like to use the target selector you can also do it in this way:

    .my-target {
        padding-top: 65px;
        margin-top: -65px;
    }
    

    Note: this example will not work if the target element have a backgound color that differant from his parent. for example:

    in this case the green color of my-target element will overwrite his parent red element in 65px. I did not find any pure CSS solution to handle this issue but if you do not have another background color this solution is the best.

提交回复
热议问题