简体   繁体   中英

How do I vertically center an image in a div?

Suppose the image is 100w x 300h. But I have a div that is always 100x100. I want to center the image (so that the top and bottom get cut off)

Note: The height will always be variable. It's not always 300.

How can I do that in JQuery?

Why don't you just set the image as a background property of the div? Straight CSS solution, no js necessary:

.cutoffAndCentered { width: 100px; height: 100px; background: url('image.jpg') no-repeat center center; }

Or you can always do the same via jQuery:

$('.myDiv').css('background','url(image.jpg) no-repeat center center');

You should use display: table-cell and overflow:hidden; This tutorial should help http://www.brunildo.org/test/img_center.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM