Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust a 100% width image to vertically center using jQuery or CSS?

Basically I have a fixed size div that contains an <img> tag. I cannot change the structure.

Often these images are much larger than the container due to keeping them 100% width and filling the box. Most times this results in too much of the image shown at top and not cropped to the center of the image.

So using jQuery (or pure CSS if possible) I want to adjust the position of the image to move it up so the top is cropped off instead of the bottom.

Also, this should remain responsive as the viewport changes width.

Here is a fiddle

.container {
    height: 200px;
    width: 100%;
    overflow: hidden;
    margin: 0 0 30px;
}
<div class="container">
    <img src="http://placekitten.com/900/500/">
</div>
<div class="container">
    <img src="http://placekitten.com/901/500/">
</div>

enter image description here

like image 566
o_O Avatar asked Dec 08 '25 22:12

o_O


1 Answers

It's doable with known height container, like your demo. We can set the container to position:relative, and set the image to position:absolute, plus some extra set ups as follows.

.container {
    height: 200px;
    width: 100%;
    overflow: hidden;
    margin: 0 0 30px;
    position: relative;
}
.container img {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    max-width: 100%;
    height: auto;
}
<div class="container">
    <img src="http://placekitten.com/900/500/">
</div>
<div class="container">
    <img src="http://placekitten.com/901/500/">
</div>

jsfiddle

like image 132
Stickers Avatar answered Dec 10 '25 10:12

Stickers