1453

I am trying to clean up the way my anchors work. I have a header that is fixed to the top of the page, so when you link to an anchor elsewhere in the page, the page jumps so the anchor is at the top of the page, leaving the content behind the fixed header (I hope that makes sense). I need a way to offset the anchor by the 25px from the height of the header. I would prefer HTML or CSS, but Javascript would be acceptable as well.

14
  • 2
    The wrapper div shown in stackoverflow.com/questions/1431639/… is fine I think, not too aggressive.
    – ron
    Apr 20, 2012 at 14:23
  • 52
    There is a nice article on this subject: css-tricks.com/hash-tag-links-padding
    – J. Bruni
    Oct 6, 2013 at 1:44
  • 5
    The question which marks this one as duplicate does not accept javascript solutions. This question has script solutions. It should be reopened. Apr 18, 2018 at 12:30
  • 23
    @J.Bruni There is a much newer CSS-tricks.com article about scroll-padding-top here: css-tricks.com/…
    – Flimm
    Dec 3, 2019 at 11:39
  • 31
    I wish these posts could be updated. I use :target { scroll-margin-top: 24px; }
    – valtism
    Jul 12, 2021 at 1:51

28 Answers 28

1478

You could just use CSS without any javascript.

Give your anchor a class:

<a class="anchor" id="top"></a>

You can then position the anchor an offset higher or lower than where it actually appears on the page, by making it a block element and relatively positioning it. -250px will position the anchor up 250px

a.anchor {
    display: block;
    position: relative;
    top: -250px;
    visibility: hidden;
}
33
  • 16
    This is the better answer, because it doesn't depend on a parent element whose position is set to relative. Thanks for posting this.
    – Eric Mill
    May 27, 2013 at 2:04
  • 91
    Love your solution! It seems not to work with IE7. Anyway, I plan to ignore IE7 users from now on...
    – user334639
    Sep 19, 2013 at 15:35
  • 132
    If you want this to work for visible elements, you can also use a pseudo-element, a la .thing-with-anchor:before { content: ''; display: block; position: relative; width: 0; height: 5em; margin-top: -5em } The display block and position relative are essential.
    – harpo
    May 3, 2014 at 15:22
  • 24
    We are not suppose to be using a tags w/o an href attribute anymore. Instead we are suppose to use id tags within heading / section / etc for anchored text. What is the solution then? Nov 18, 2014 at 4:08
  • 20
    @harpo: Nice idea, but doesn't work. Tried in Chrome 40.
    – djk
    Feb 3, 2015 at 18:51
451

I found this solution:

<a name="myanchor">
    <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>

This doesn't create any gap in the content and anchor links works really nice.

13
  • 8
    Worked great. I created a special CSS anchor class and just attached it to my anchors: <a class="anchor" name="foo"></a>. Thanks.
    – user41871
    Sep 12, 2012 at 20:00
  • 3
    there is still jankiness with the indicator in the nav. so if you scroll down the page, the active nav item doesn't switch until you scroll past the anchor target.
    – Randy L
    Feb 13, 2013 at 18:04
  • 46
    Element just above <h1> will not be clickable, because of the hidden padding/margin. I ended up using Ian Clack's jQuery solution, which works great.
    – Matt
    Aug 14, 2013 at 19:46
  • 2
    How would you make it work with anchors that use element IDs, i.e. <h1 id="smth">Text</h1>...<a href="#smth">Link</a>?
    – Alek Davis
    Nov 7, 2013 at 7:06
  • 7
    I think I figured this out: h2[id], h3[id], h4[id], a[name] { padding-top: XXpx; padding-bottom: XXpx; } It applies to all h2, h3, h4 tags with IDs, as well as named anchors.
    – Alek Davis
    Nov 7, 2013 at 8:41
245

FWIW this worked for me:

[id]::before {
  content: '';
  display: block;
  height:      75px;
  margin-top: -75px;
  visibility: hidden;
}
20
  • 9
    I don't fully understand why this works, but +1 from me. None of the others were as easy to implement or worked as well as this. :-)
    – JackWilson
    Nov 20, 2015 at 6:44
  • 2
    I wrapped this in a media query so it is only applied to medium and large screens where I have a fixed nav.
    – Ron
    Feb 15, 2016 at 18:41
  • 4
    This may work, but it will overlap the content before the headline.
    – dude
    May 4, 2016 at 13:23
  • 2
    Can someone explain why this works?
    – Brady Holt
    Nov 29, 2017 at 14:02
  • 4
    This is great! However, it doesn't work if the [id] element is a child of display: flex container: the height created by the ::before element doesn't affect the height of the [id] element because flex 🤷‍♀️ Jan 17, 2020 at 12:16
227

I was looking for a solution to this as well. In my case, it was pretty easy.

I have a list menu with all the links:

<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>

And below that the headings where it should go to.

<h3>one</h3>
<p>text here</p>

<h3>two</h3>
<p>text here</p>

<h3>three</h3>
<p>text here</p>

<h3>four</h3>
<p>text here</p>

Now because I have a fixed menu at the top of my page I can't just make it go to my tag because that would be behind the menu.

Instead, I put a span tag inside my tag with the proper id.

<h3><span id="one"></span>one</h3>

Now use 2 lines of CSS to position them properly.

h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}

Change the top value to match the height of your fixed header (or more). Now I assume this would work with other elements as well.

6
  • 5
    span could be replaced with an a
    – David Cook
    Jul 23, 2015 at 2:34
  • 2
    This works really nice and avoids some of the problems I hit with other techniques, such as when using an h2 tag that sets a padding-top.
    – Jonathan
    Feb 3, 2016 at 8:20
  • I use this, as well as a JS event listening for click events on the anchors to smooth scroll if JS is available. Apr 20, 2017 at 11:02
  • 1
    In Wordpress, empty <a></a> get stripped out. This solution, the editor does not strip out the empty spans. This is great!
    – Jarad
    Mar 28, 2019 at 6:42
  • I added a class to the <span> element so the children span do not inherit the same styling. Jun 6, 2021 at 23:16
189

As this is a concern of presentation, a pure CSS solution would be ideal. However, this question was posed in 2012, and although relative positioning / negative margin solutions have been suggested, these approaches seem rather hacky, create potential flow issues, and cannot respond dynamically to changes in the DOM / viewport.

With that in mind I believe that using JavaScript is still (February 2017) the best approach. Below is a vanilla-JS solution which will respond both to anchor clicks and resolve the page hash on load (See JSFiddle). Modify the .getFixedOffset() method if dynamic calculations are required. If you're using jQuery, here's a modified solution with better event delegation and smooth scrolling.

(function(document, history, location) {
  var HISTORY_SUPPORT = !!(history && history.pushState);

  var anchorScrolls = {
    ANCHOR_REGEX: /^#[^ ]+$/,
    OFFSET_HEIGHT_PX: 50,

    /**
     * Establish events, and fix initial scroll position if a hash is provided.
     */
    init: function() {
      this.scrollToCurrent();
      window.addEventListener('hashchange', this.scrollToCurrent.bind(this));
      document.body.addEventListener('click', this.delegateAnchors.bind(this));
    },

    /**
     * Return the offset amount to deduct from the normal scroll position.
     * Modify as appropriate to allow for dynamic calculations
     */
    getFixedOffset: function() {
      return this.OFFSET_HEIGHT_PX;
    },

    /**
     * If the provided href is an anchor which resolves to an element on the
     * page, scroll to it.
     * @param  {String} href
     * @return {Boolean} - Was the href an anchor.
     */
    scrollIfAnchor: function(href, pushToHistory) {
      var match, rect, anchorOffset;

      if(!this.ANCHOR_REGEX.test(href)) {
        return false;
      }

      match = document.getElementById(href.slice(1));

      if(match) {
        rect = match.getBoundingClientRect();
        anchorOffset = window.pageYOffset + rect.top - this.getFixedOffset();
        window.scrollTo(window.pageXOffset, anchorOffset);

        // Add the state to history as-per normal anchor links
        if(HISTORY_SUPPORT && pushToHistory) {
          history.pushState({}, document.title, location.pathname + href);
        }
      }

      return !!match;
    },

    /**
     * Attempt to scroll to the current location's hash.
     */
    scrollToCurrent: function() {
      this.scrollIfAnchor(window.location.hash);
    },

    /**
     * If the click event's target was an anchor, fix the scroll position.
     */
    delegateAnchors: function(e) {
      var elem = e.target;

      if(
        elem.nodeName === 'A' &&
        this.scrollIfAnchor(elem.getAttribute('href'), true)
      ) {
        e.preventDefault();
      }
    }
  };

  window.addEventListener(
    'DOMContentLoaded', anchorScrolls.init.bind(anchorScrolls)
  );
})(window.document, window.history, window.location);
44
  • 4
    works great, though for jquery 1.7+, use $("a").on("click",... instead of $("a").live("click",...
    – JasonS
    Aug 3, 2013 at 9:01
  • 5
    Nice comment, I'll update :) - BTW it should also be $("body").on("click", "a"... as it may need to work for anchors which are added into the document by scripts (hence why I was using .live)
    – Ian Clark
    Aug 3, 2013 at 10:15
  • 3
    Also, though, it's worth noting that this will mess with other href/id pairs, as in collapse, carousel, etc... is there an easy way around this?
    – tom10
    Dec 10, 2013 at 3:35
  • 3
    @tom10 I suppose you would just have to make the selector more specific, either by blacklisting anchors using a:not(.not-anchor) (or something less confusingly named) and then make sure that your collapse/carousel libraries add those classes to their anchors. If you're using jQuery UI or Bootstrap I imagine they add some other classes which you could reference.
    – Ian Clark
    Dec 10, 2013 at 13:54
  • 5
    If you are clicking 2 times on the same anchor consecutively (from menu with anchor links), the second click is not working well.
    – user621639
    Jun 28, 2017 at 8:22
94

Pure css solution inspired by Alexander Savin:

a[name] {
  padding-top: 40px;
  margin-top: -40px;
  display: inline-block; /* required for webkit browsers */
}

Optionally you may want to add the following if the target is still off the screen:

  vertical-align: top;
9
  • 7
    I have just tried on Chrome and the display inline-block was not required.
    – Asrail
    Apr 8, 2013 at 6:07
  • 2
    @Asrail For me it didn't work without it
    – Hameno
    Jul 7, 2013 at 9:56
  • 1
    For me, "display: inline-block;" completely broke functionality in Chrome (all links became unclickable).
    – Alek Davis
    Nov 7, 2013 at 8:43
  • 2
    a[name] selector should not be affected to links
    – Ziav
    Nov 9, 2013 at 6:06
  • 1
    FYI: merged from stackoverflow.com/questions/9047703/…
    – Shog9
    Jul 24, 2014 at 19:16
88

My solution combines the target and before selectors for our CMS. Other techniques don't account for text in the anchor. Adjust the height and the negative margin to the offset you need...

:target::before {
    content: '';
    display: block;
    height:      180px;
    margin-top: -180px;
}
6
  • 3
    These two CSS solutions didn't work for me on the first sight, but finally I found out it might not be compatible with other CSS properties. Added a wrapper and that fixed the problem. Combination of :target:before with display:block works best for me.
    – John
    Dec 23, 2014 at 13:49
  • 2
    [Solved] This solution works and i used this solution with display: block;. Without a special class, empty tag or javascript. Aug 5, 2017 at 21:51
  • 6
    If you decide to use this method, it is probably a good idea to add pointer-events: none; as well. Because otherwise links intersecting with the invisible overlay (above the anchor) will not be clickable.
    – Steven
    Aug 13, 2019 at 12:58
  • 2
    This solution messes up collapsed margins by disconnecting them. Edit: I just put the id on the <h1> and not the <section> and it works fine
    – Volper
    Feb 14, 2020 at 15:18
  • 14
    If supporting just modern browsers is okay, I'd recommend just :target { scroll-margin-top: 180px; } (or any other measurement or calc() you wish). Sep 23, 2021 at 11:08
49

This takes many elements from previous answers and combines into a tiny (194 bytes minified) anonymous jQuery function. Adjust fixedElementHeight for the height of your menu or blocking element.

    (function($, window) {
        var adjustAnchor = function() {

            var $anchor = $(':target'),
                    fixedElementHeight = 100;

            if ($anchor.length > 0) {

                $('html, body')
                    .stop()
                    .animate({
                        scrollTop: $anchor.offset().top - fixedElementHeight
                    }, 200);

            }

        };

        $(window).on('hashchange load', function() {
            adjustAnchor();
        });

    })(jQuery, window);

If you don't like the animation, replace

$('html, body')
     .stop()
     .animate({
         scrollTop: $anchor.offset().top - fixedElementHeight
     }, 200);

with:

window.scrollTo(0, $anchor.offset().top - fixedElementHeight);

Uglified version:

 !function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);
10
  • 1
    This solution really helped me out, but it is somehow not working consistently in IE9-11. Sometimes it works, some other clicks it doesn't (scroll position stays at the anchor position). I am totally out of ideas what could cause the issue. May 20, 2015 at 15:20
  • @Crono1985 Is your doc HTML 4 or 5? In 4, IDs had a stricter list of characters so they may be failing to register as valid targets. Next, are you using ID or name? In HTML5, ID is a valid anchor for all tags but name can only be used on link tags.
    – Lance
    Jun 14, 2015 at 21:39
  • Very nice! Thanks! The only problem, it doesn't reliably work, if one follows the link with fragment/hash (I mean some-page#anchor). At least on Chromium 45.0.2454.101 and Firefox. I'm not sure it could fixed though. Dec 10, 2015 at 15:46
  • 2
    @MajesticRa One tricky issue is the order of operations in the on load or scroll events. If your page adjusts the layout after the page is loaded or scrolled (shrinking masthead for example), the calculation of the :target offset can be wrong.
    – Lance
    Dec 10, 2015 at 17:54
  • 1
    That solved my issue. Maybe it worth putting this remark in the answer. Dec 11, 2015 at 16:53
45

For modern browsers, just add the CSS3 :target selector to the page. This will apply to all the anchors automatically.

:target {
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}
7
  • 15
    You could even do :target:before to create a hidden pseudo-element rather than hide the whole target. Mar 24, 2014 at 23:08
  • The :target selector is supposed to be supported since IE9, but the offset only works with FF and Chrome and Safari on my site, not with IE 11.
    – cdonner
    May 27, 2014 at 14:00
  • 1
    When you do things the HTML5 way (and I think 4 too) where you target an id attribute within a node such as section or header, this way caused the element to display overlapping elements above it. Nov 21, 2014 at 0:40
  • 5
    Hiding :target seems like a bad idea in most contexts. You're granting anybody who sends someone a link to your page the power to pick any element with an ID and delete it from the page that the viewer will see. On the tame side, tech-savvy pranksters may well notice this and decide to have some fun with it, much as they once had fun with the ability to make links to some news sites show up with silly titles on Facebook by manipulating their URLs. More severely, it may be a security hole if your page has something like a "don't share this secret information with anyone" message with an ID.
    – Mark Amery
    Mar 7, 2015 at 21:22
  • 1
    adding this code to the style sheet does nothing for me using Chrome 60.0.3112.78 in the website I'm currently working on - though that may well be due to interaction effects... Could you post a pen?
    – Julix
    Aug 1, 2017 at 20:07
42

You can do it without js and without altering html. It´s css-only.

a[id]::before {
    content: '';
    display: block;
    height: 50px;
    margin: -30px 0 0;
}

That will append a pseudo-element before every a-tag with an id. Adjust values to match the height of your header.

7
  • 7
    Interesting idea, but note that this screws up the display if you happen to have visible links with id's.
    – harpo
    Oct 29, 2013 at 2:02
  • 3
    If you have ever wonder why it doesn't work for you, check out if parent element has not border or padding.
    – byashimov
    May 20, 2015 at 11:36
  • 2
    i modified this to select :target[id]:before since the id's that i anchor-link to are sometimes h1-h6.
    – KFunk
    Sep 18, 2017 at 19:10
  • a[id]:before can be changed to something else like div[name]:before
    – cannin
    Dec 5, 2017 at 18:05
  • 1
    height and negative margin should match right? Nov 5, 2018 at 16:57
34

I had been facing a similar issue, unfortunately after implementing all the solutions above, I came to the following conclusion.

  1. My inner elements had a fragile CSS structure and implementing a position relative / absolute play, was completely breaking the page design.
  2. CSS is not my strong suit.

I wrote this simple scrolling js, that accounts for the offset caused due to the header and relocated the div about 125 pixels below. Please use it as you see fit.

The HTML

<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->

The JavaScript

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
&& location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('#'+location.href.split("#")[1]);
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});

See a live implementation here.

8
  • ok i got the anchor to put the anchor name into the url, but i cant seem to get the second part to work. When i open my page with an anchor in the url, it moves to where the anchor is but it won't offset it. Do i need something in addition to jquery to make that work?
    – Robbiegod
    Sep 10, 2014 at 19:06
  • @Robbiegod to offset just tweak the pixel count I have mentioned, scrollTop: target.offset().top - 125 the 125 here is something that worked for me. Refine it as per your needs. It would be great if you could post an example with your problem for more clarifications.
    – Shouvik
    Sep 11, 2014 at 7:06
  • @Shouvik I did change 125 to 165 to match my site already, but it still doesnt offset. I have the js code in a file called site.js at that file loads in the footer, could that be the problem? Does this need to load in the head section? I also copied your code straight into my site.js file. The total change i made was changing the $ to jQuery.
    – Robbiegod
    Sep 11, 2014 at 14:46
  • hmmm, it shouldn't be an issue. The idea is that we want to call this function after the window is loaded as opposed to the page being ready. This is done to take the images loaded into perspective to scroll the page. You should probably check your jquery reference, i.e if the jquery file is loaded. Use the $ instead of JQuery. If you are getting an error it's probably because the jquery is not getting loaded.
    – Shouvik
    Sep 11, 2014 at 14:53
  • jQuery is loading for sure (lightboxes, flexslider etc all work). I load jQuery in the footer too. Then i load my site.js file. using jquery 1.11 and jquery ui as well. i changed all of the jQuery back to $ (though i don't think this is an issue either way because $ is just an alias for jQuery) - it seemed to not make any difference. I don't see any errors, but also when i open a new browser and paste the url with the anchor it doesnt offset the page. I'll keep trying different stuff
    – Robbiegod
    Sep 11, 2014 at 15:19
13

For the same issue, I used an easy solution : put a padding-top of 40px on each anchor.

2
  • 2
    Thanks, this was basically what I ended up doing, but I was wondering whether there's a solution for situations where adding extra padding might be awkward.
    – Ben
    Feb 29, 2012 at 22:57
  • FYI: merged from stackoverflow.com/questions/9047703/…
    – Shog9
    Jul 24, 2014 at 19:17
13

As @moeffju suggests, this can be achieved with CSS. The issue I ran into (which I'm surprised I haven't seen discussed) is the trick of overlapping previous elements with padding or a transparent border prevents hover and click actions at the bottom of those sections because the following one comes higher in the z-order.

The best fix I found was to place section content in a div that is at z-index: 1:

// Apply to elements that serve as anchors
.offset-anchor {
  border-top: 75px solid transparent;
  margin: -75px 0 0;
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
}

// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
  position: relative;
  z-index: 1;
}
12

Solutions with changing position property are not always possible (it can destroy layout) therefore I suggest this:

HTML:

<a id="top">Anchor</a>

CSS:

#top {
    margin-top: -250px;
    padding-top: 250px;
}

Use this:

<a id="top">&nbsp;</a>

to minimize overlapping, and set font-size to 1px. Empty anchor will not work in some browsers.

11

Borrowing some of the code from an answer given at this link (no author is specified), you can include a nice smooth-scroll effect to the anchor, while making it stop at -60px above the anchor, fitting nicely underneath the fixed bootstrap navigation bar (requires jQuery):

$(".dropdown-menu a[href^='#']").on('click', function(e) {
   // prevent default anchor click behavior
   e.preventDefault();

   // animate
   $('html, body').animate({
       scrollTop: $(this.hash).offset().top - 60
     }, 300, function(){
     });
});
4
  • FYI: merged from stackoverflow.com/questions/9047703/…
    – Shog9
    Jul 24, 2014 at 19:17
  • A full solution should also include the scenario in which a user loads a new page with the anchor already in the address bar. I tried to adapt this code to fire upon the $(document).ready event but it is still scrolling to the wrong place in the document. Any ideas? Aug 21, 2014 at 22:46
  • 1
    thanks, that is the solution for twitter bootstrap users Sep 17, 2015 at 9:49
  • @AdamFriedman did you even found a solution to that specifik scenario. I use a smoothanchor library which I can append an offset but that also does not work on pageloads with urls. url#target
    – Todilo
    Feb 25, 2017 at 12:25
5

Instead of having a fixed-position navbar which is underlapped by the rest of the content of the page (with the whole page body being scrollable), consider instead having a non-scrollable body with a static navbar and then having the page content in an absolutely-positioned scrollable div below.

That is, have HTML like this...

<div class="static-navbar">NAVBAR</div>
<div class="scrollable-content">
  <p>Bla bla bla</p>
  <p>Yadda yadda yadda</p>
  <p>Mary had a little lamb</p>
  <h2 id="stuff-i-want-to-link-to">Stuff</h2>
  <p>More nonsense</p>
</div>

... and CSS like this:

.static-navbar {
  height: 100px;
}
.scrollable-content {
  position: absolute;
  top: 100px;
  bottom: 0;
  overflow-y: scroll;
  width: 100%;
}

There is one significant downside to this approach, however, which is that while an element from the page header is focused, the user will not be able to scroll the page using the keyboard (e.g. via the up and down arrows or the Page Up and Page Down keys).

Here's a JSFiddle demonstrating this in action.

3
  • 3
    Non-hacky, but: (1) entirely useless outside this example, (2) cumbersome to adopt and maintain, (3) anti-semantic and-or css-abusive, (4) unintuitive. I'll take the clean a:before {...} solution over this any day! Jan 25, 2017 at 12:40
  • Best answer for me. I am using it now. All the answers here are hacky. Adding a "before" pseudo element to everything is not acceptable for me and can potentially interfere with many other CSS elements already using the "before" pseudo element. This is the right and clean way to proceed.
    – David
    Apr 18, 2018 at 12:55
  • 1
    This is ABSOLUTELY the best solution. It requires no hacks or pseudo-classes. I also find it 100% semantic. Essentially there is a part of the page that you want to have scroll, and you set that explicitly. Also, it completely solves the problem of how to make headings disappear behind navs with no background.
    – abalter
    May 29, 2018 at 0:45
4

The above methods don't work very well if your anchor is a table element or within a table (row or cell).

I had to use javascript and bind to the window hashchange event to work around this (demo):

function moveUnderNav() {
    var $el, h = window.location.hash;
    if (h) {
        $el = $(h);
        if ($el.length && $el.closest('table').length) {
            $('body').scrollTop( $el.closest('table, tr').position().top - 26 );
        }
    }
}

$(window)
    .load(function () {
        moveUnderNav();
    })
    .on('hashchange', function () {
        moveUnderNav();
    });

* Note: The hashchange event is not available in all browsers.

3

You can achieve this without an ID using the a[name]:not([href]) css selector. This simply looks for links with a name and no href e.g. <a name="anc1"></a>

An example rule might be:

a[name]:not([href]){
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}
1
  • 2
    Note that in HTML5, the a element has no name attribute, so this won't work.
    – Geoff
    Jun 30, 2015 at 21:55
2

This was inspired by the answer by Shouvik - same concept as his, only the size of the fixed header isn't hard coded. As long as your fixed header is in the first header node, this should "just work"

/*jslint browser: true, plusplus: true, regexp: true */

function anchorScroll(fragment) {
    "use strict";
    var amount, ttarget;
    amount = $('header').height();
    ttarget = $('#' + fragment);
    $('html,body').animate({ scrollTop: ttarget.offset().top - amount }, 250);
    return false;
}

function outsideToHash() {
    "use strict";
    var fragment;
    if (window.location.hash) {
        fragment = window.location.hash.substring(1);
        anchorScroll(fragment);
    }
}

function insideToHash(nnode) {
    "use strict";
    var fragment;
    fragment = $(nnode).attr('href').substring(1);
    anchorScroll(fragment);
}

$(document).ready(function () {
    "use strict";
    $("a[href^='#']").bind('click',  function () {insideToHash(this); });
    outsideToHash();
});
2
  • Oh - also this solution assumes the id attribute is used for the anchor, not the deprecated name attribute. Nov 21, 2014 at 2:37
  • I like this solution, very modular and beautifully done. Oh I miss the days of JQuery and DOM manipulations :) Apr 4, 2016 at 11:02
1

I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:

<div id="c1234" class="contentElement">...</div>

and i changed the rendering so it renders like this:

<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>

And this CSS:

.anchor{
    position: relative;
    top: -50px;
}

The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.

Only drawback of this technique is you can no longer use :target.

1
  • 2
    Actually you can use :target like so: .anchor:target+div
    – lipsumar
    Apr 24, 2013 at 17:13
0

Adding to Ziav's answer (with thanks to Alexander Savin), I need to be using the old-school <a name="...">...</a> as we're using <div id="...">...</div> for another purpose in our code. I had some display issues using display: inline-block -- the first line of every <p> element was turning out to be slightly right-indented (on both Webkit and Firefox browsers). I ended up trying other display values and display: table-caption works perfectly for me.

.anchor {
  padding-top: 60px;
  margin-top: -60px;
  display: table-caption;
}
1
0

I added 40px-height .vspace element holding the anchor before each of my h1 elements.

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

In the CSS:

.vspace { height: 40px;}

It's working great and the space is not chocking.

1
0

how about hidden span tags with linkable IDs that provide the height of the navbar:

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>

heres the fiddle: http://jsfiddle.net/N6f2f/7

1
0

You can also add an anchor with follow attr:

(text-indent:-99999px;)
visibility: hidden;
position:absolute;
top:-80px;    

and give the parent container a position relative.

Works perfect for me.

1
0

A further twist to the excellent answer from @Jan is to incorporate this into the #uberbar fixed header, which uses jQuery (or MooTools). (http://davidwalsh.name/persistent-header-opacity)

I've tweaked the code so the the top of the content is always below not under the fixed header and also added the anchors from @Jan again making sure that the anchors are always positioned below the fixed header.

The CSS:

#uberbar { 
    border-bottom:1px solid #0000cc; 
    position:fixed; 
    top:0; 
    left:0; 
    z-index:2000; 
    width:100%;
}

a.anchor {
    display: block;
    position: relative;
    visibility: hidden;
}

The jQuery (including tweaks to both the #uberbar and the anchor approaches:

<script type="text/javascript">
$(document).ready(function() {
    (function() {
        //settings
        var fadeSpeed = 200, fadeTo = 0.85, topDistance = 30;
        var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
        var inside = false;
        //do
        $(window).scroll(function() {
            position = $(window).scrollTop();
            if(position > topDistance && !inside) {
                //add events
                topbarML();
                $('#uberbar').bind('mouseenter',topbarME);
                $('#uberbar').bind('mouseleave',topbarML);
                inside = true;
            }
            else if (position < topDistance){
                topbarME();
                $('#uberbar').unbind('mouseenter',topbarME);
                $('#uberbar').unbind('mouseleave',topbarML);
                inside = false;
            }
        });
        $('#content').css({'margin-top': $('#uberbar').outerHeight(true)});
        $('a.anchor').css({'top': - $('#uberbar').outerHeight(true)});
    })();
});
</script>

And finally the HTML:

<div id="uberbar">
    <!--CONTENT OF FIXED HEADER-->
</div>
....
<div id="content">
    <!--MAIN CONTENT-->
    ....
    <a class="anchor" id="anchor1"></a>
    ....
    <a class="anchor" id="anchor2"></a>
    ....
</div>

Maybe this is useful to somebody who likes the #uberbar fading dixed header!

-1

@AlexanderSavin's solution works great in WebKit browsers for me.

I additionally had to use :target pseudo-class which applies style to the selected anchor to adjust padding in FF, Opera & IE9:

a:target {
  padding-top: 40px
}

Note that this style is not for Chrome / Safari so you'll probably have to use css-hacks, conditional comments etc.

Also I'd like to notice that Alexander's solution works due to the fact that targeted element is inline. If you don't want link you could simply change display property:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>
3
  • my nav items link to h2 elements, which are all display: block. i am using chrome, and i did not need to set the h2's to inline or inline-block.
    – Randy L
    Feb 13, 2013 at 17:50
  • @the0ther I was referring to wrapper element not headers. Also experiencing difficulties to imagine your markup based on your words.
    – jibiel
    Feb 13, 2013 at 19:31
  • FYI: merged from stackoverflow.com/questions/9047703/…
    – Shog9
    Jul 24, 2014 at 19:17
-1

Here's the solution that we use on our site. Adjust the headerHeight variable to whatever your header height is. Add the js-scroll class to the anchor that should scroll on click.

// SCROLL ON CLICK
// ---------------------------------------------------------------------
$('.js-scroll').click(function(){
    var headerHeight = 60;

    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight;
    }, 500);
    return false;
});
-2

I ran into this same issue and ended up handling the click events manually, like:

$('#mynav a').click(() ->
  $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top - 40
  }, 200
  return false
)

Scroll animation optional, of course.

2
  • FYI: merged from stackoverflow.com/questions/9047703/…
    – Shog9
    Jul 24, 2014 at 19:18
  • 4
    This javascript isn't even valid, I understand the message you're trying to convey. But it should AT LEAST have valid braces and syntax to be a legitimate answer.
    – gzimmers
    Apr 3, 2019 at 21:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.