Home  >  Q&A  >  body text

Solution to the problem of page title and page anchor overlapping

<p>If I have a non-scrolling header in an HTML page that is fixed at the top, with a defined height: </p> <p>Is there a way to use URL anchors (<code>#fragment</code> part) to make the browser scroll to a specific position in the page but still respect the height of the fixed element<strong> Help without using JavaScript</strong>? </p> <pre class="brush:none;toolbar:false;">http://example.com/#bar </pre> <pre>Error (but common behavior): Correct: ---------------------------------- ------------------ ---------------- | BAR/////////////////////// header | ////////////////////////// header | ---------------------------------- ------------------ ---------------- | rest of text here | | BAR | | ... | | | | ... | | rest of text here | | ... | | ... | ---------------------------------- ------------------ ---------------- </pre> <p><br /></p>
P粉521748211P粉521748211447 days ago526

reply all(2)I'll reply

  • P粉285587590

    P粉2855875902023-08-22 17:09:27

    If you can't or don't want to set a new class, you can add a fixed-height :target# to the ::before pseudo-element in CSS. ##Pseudo class:

    :target::before {
      content: "";
      display: block;
      height: 60px; /* 固定的标题高度 */
      margin: -60px 0 0; /* 负的固定标题高度 */
    }
    

    Or use jQuery to scroll the page relative to

    :target:

    var offset = $(':target').offset();
    var scrollto = offset.top - 60; // 减去固定的标题高度
    $('html, body').animate({scrollTop:scrollto}, 0);
    

    reply
    0
  • P粉986937457

    P粉9869374572023-08-22 09:39:10

    I encountered the same problem. I solved this problem by adding a class to the anchor element and using the topbar's height as the value of padding-top.

    <h1><a class="anchor" name="barlink">Bar</a></h1>

    I used the following CSS:

    .anchor { padding-top: 90px; }

    reply
    0
  • Cancelreply