Sticky Header Script

PHP CSS

Paste the following into your functions.php file

Click to copy
<?php
/**
 * Print Sticky Header script to footer.
 *
 * @since 1.0
 */

function md_child_sticky_script() { ?>
	<script>
		var html = document.getElementsByTagName( 'html' )[0],
			header = document.getElementById( 'header' ),
			headerHeight = header.offsetTop + header.clientHeight,
			pos = 0,
			ticking = false;
		window.onscroll = function( e ) {
			pos = window.scrollY;
			if ( ! ticking ) {
				window.requestAnimationFrame( function() {
					if ( pos > headerHeight ) {
						html.style.paddingTop = headerHeight + 'px';
						MD.addClass( header, 'is-sticky' );
					}
					else {
						html.style.paddingTop = '';
						MD.removeClass( header, 'is-sticky' );
					}
					ticking = false;
				});
			}
			ticking = true;
		}
	</script>
<?php }
add_action( 'wp_footer', 'md_child_sticky_script' );

Paste the following into your style.css file

Click to copy
.header { box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); }

.header.is-sticky {
	padding-bottom: 7px;
	padding-top: 7px;
	position: fixed;
		left: 0;
		top: 0;
	transition: 0.3s;
	width: 100%;
	z-index: 999;
}

.header.is-sticky .logo { font-size: 24px; }

.admin-bar .header.is-sticky { top: 32px; }

@media all and (max-width: 782px) {
	.admin-bar .header.is-sticky { top: 46px; }
}

Use this simple child theme modification to add a sticky scrolling effect to your site’s header. This is a simple solution that requires no jQuery and uses MD’s extremely lightweight JavaScript API to make this simple effect possible on your website.

The Sticky Header feature is slated to make it into a future MD release, but for now this simple effect can be achieved with the above code snippets in your child theme.

With a few extra custom CSS styles, the sticky effect is made more elegant by narrowing the height of the header and reducing the font size of the site title to prevent the header from blocking too much content while scrolling.

November sale: Save 25% on all new licenses!