Last active
September 14, 2017 00:13
-
-
Save benpearson/e124b9861caa30bdbf99 to your computer and use it in GitHub Desktop.
Vertically center images in slider container when image height is greater than container height (larger screens often have max height on container)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Flexslider | |
*/ | |
jQuery(document).ready(function($) { | |
// Vertically center images in slider container when image height is greater than container height (larger screens) | |
function verticallyCenterImages() { | |
var containerHeight = $('.flexslider').height(); | |
$('.flexslider .slides li').each(function() { | |
var image = $(this).find('img'); | |
var imageHeight = image.height(); | |
image.css("top", "initial"); // reset for window resize | |
if (imageHeight > containerHeight) { | |
var verticalShift = (containerHeight - imageHeight) / 2; | |
image.css("top", verticalShift + "px"); | |
} | |
}); | |
} | |
// Load Flexslider | |
$(window).load(function() { | |
$('.flexslider').flexslider({ | |
controlNav: false, | |
start: function(){ | |
verticallyCenterImages(); | |
} | |
}); | |
}); | |
// Window resize | |
$(window).resize(function() { | |
verticallyCenterImages(); | |
}); | |
}); | |
// CSS | |
.flexslider { | |
margin-bottom: 0 !important; // reset | |
border: none !important; | |
// max height for larger screens | |
max-height: 700px; | |
overflow: hidden; // x overflow added to stop scrollbar bug caused by direction nav. y overflow for max slider height/ | |
.slides img { | |
position: relative; // needed for vertical centering jquery | |
} | |
// Fix navigation arrow bug | |
.flex-direction-nav a:before { | |
font-size: 34px !important; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this. It worked brilliantly until I added a second image. I'm pulling from featured images in Wordpress. Any ideas what I might need to change to get it to work with the query?
Thanks in advance.