Skip to content

Instantly share code, notes, and snippets.

@benpearson
Last active September 14, 2017 00:13
Show Gist options
  • Save benpearson/e124b9861caa30bdbf99 to your computer and use it in GitHub Desktop.
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)
/*
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;
}
}
@mattfalber
Copy link

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.

    	<?php
    	query_posts(array('posts_per_page' => 5, 'cat' => '2,5'));
    	if(have_posts()) : while(have_posts()) : the_post();
    	?>
    
    	  <li class="featured-post">
    		<?php the_post_thumbnail('slider-image'); ?>
    		<div class="flex-caption">
    			<a href="<?php the_permalink(); ?>" > <h2 class="entry-title"><?php the_title();?></a></h2><br>
    			<a href="<?php the_permalink(); ?>" class="excerpt"><?php the_content(); ?></a>
    		</div>
    
    		
    	  </li>
      
    	<?php
    	    endwhile;
    		endif;
    		wp_reset_query();
    	?>
    </ul>
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment