Search

Friends

Atomspheric CO2 (PPM)

Archives

Blather

Uptime verified by Wormly.com

5 August 2011

Vertical centering of cropped image with jQuery

You can use HTML, CSS and jQuery to vertically center cropped images that you don't know the height of. It's a shame to use jQuery at all, but I think it's necessary. I looked at the CSS clip property and at negative proportional margins (margin-top: -50%; etc.), but unless you know the height of the image I don't think it will work.

<div style="height:100px;overflow:hidden;">
    <img id="crop" src="blah.jpg" style="height:200px;" />
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    var image = $("#crop");
    image.css('marginTop', (-(image.height() - image.parent().height()) / 2) + "px");
});
</script>

Comments

No comments yet.

Leave a comment

Markdown

0.089 seconds