Sticky Header Script

PHP CSS
Click to copy

Paste the following into your functions.php file

<?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' );
Click to copy

Paste the following into your style.css file

.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; }
}

How to Create a Scrolling “Sticky” Header

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.

Labs

Get the latest MD sent straight to your inbox

There's always something new in the works in the MD Labs! Join the email list to get the newest content and releases sent straight to your inbox.*

Join the MD Newsletter

* I only email you when there's something new, or to share an exciting MD sneak peak.