I’m building a thumbnail gallery. For each thumbnail, I am creating a clipper div and placing image inside that div. Thumbnail sizes are different for different images where as clipper div is 150x150px
<div class='clipper-div'>
<img class='image1' src='img/img2.jpg'/>
</div>
I want to place that image so that it occupies that div completely and rest of the image is clipped such that it is exactly centered.
In order to do this, I am seeing what is the smallest dimension of the image ( height/width ), making it 100%. And then for other dimension, which is now greater than div’s 150px. I’m calculating difference, dividing it by 2 and setting top/left attribute to negative of that value so the image looks centered, and then adding overflow:hidden to clipper div so the excess portion is invisible.
I want to know if there is a better way of doing this, instead of me calculating these values can I just set CSS properties so that all images will be centered in that div (vertically/horizontally) and remaining part is clipped.
If my description is confusing, here is an example:
Let’s say thumbnail size is 300x100px. So height is the smallest attribute, so I’m setting it to 100%. So height becomes 150 and width becomes 400px, so now I calculate the offset. In this case (400-150)/2 = 125px. Now I set image left to -125px
.image1{
position:absolute;
left:-125px;
height:100%;
}
Try this: