WordPress link anchors scrolling too far under your navbar?

This is a really common problem, especially now that more blogs use a floating navbar. Floating navbars use something called a “z-index” which floats your navigation above your content.

As a reader looks down on your blog, this z-indexed navigation obscures their view of the content at the top of the page. This is fine most of the time, and some themes even use a shadow to enhance the elevated navigation effect. The problem is when anchor titles are hidden under the navbar. This is a confusing and ugly situation. The reader might see the bottom portion of the desired content, but the anchor title could be completely hidden or partly chopped off by the navbar. The solution is to not scroll the content quite so far up under the navbar.

How far should the content scroll? There’s no one-size-fits-all solution. In my opinion, a designer should decide how far to scroll, creating a comfortable distance between the bottom of the navbar and the target anchor. Because a blog can have different kinds of anchors, it’s important to test the desired scroll distance on different pages.

Here’s the solution I came up with. You can add this to your WordPress theme’s footer.php or functions.php inside a “script” tag.

jQuery(document).ready(function ($) {
	$('a[href^="#"]').on('click',function (e) {
		var target = this.hash;
		var $trget = $(target);

		// desired distance adjustment
		var newTop = $trget.offset().top - 90;

		// Scroll and show hash
		$('html, body').animate ({
			scrollTop: newTop
		}, 500, 'swing', function () {
			window.location.hash = target;