Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 355
  • Last Modified:

jquery script to center image

hi i wrote a jquery script to add padding on images to center them within their container.

The script gets the containers height and the images height to then gets the difference in height

the difference in height is then applied as padding on the container to push the image down into the center of the container.

my problem is that it some times breaks and adds half of the containers height with out subtracting the images height.

this is a page that has the script on it:
http://toucanecoclean.co.uk/full-product-range/

all of the product blocks have there own script handling the padding with dynamically generated ids to target each image container.

sometimes it works and other times the images are messed up can any one tell me whats wrong with my code. thanks

the code:

								        <script>
												onResize = function() {
													setTimeout(function() {
													    var imageHeight = $('.image<?php echo $random; ?>').height();
													    var imageContainer = $('.image-inner<?php echo $random; ?>').height();
														
														

													    var padding = imageContainer - imageHeight;
														//alert (padding);
													    var paddingHalf = padding /2

													   $(".image-inner<?php echo $random; ?>").css('padding-top', paddingHalf);
													}, 100);
												}

												$(document).ready(onResize);
												//$(window).bind('resize load', onResize); // resize load !!!!
										</script>

Open in new window

0
helpchrisplz
Asked:
helpchrisplz
2 Solutions
 
GaryCommented:
Try changing height to innerHeight on imageContainer
Tho I think there is probably an easier CSS way to do this.
0
 
COBOLdinosaurCommented:
Why not just style the container with

display:table-cell;vertical-align:middle;

so you don't need the scripting to manage variable dimensions or page re-sizing?

See this example of a div styled as a cell for detailed code if you need it.

Cd&
0
 
InsoftserviceCommented:
Try out this one
.C5wrap img {
    height: auto;
    margin-top: -100px;
}
0
 
helpchrisplzAuthor Commented:
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now