How To Fit Image To Frame Keeping Aspect Ratio And Center In Thumbnail List
Solution 1:
Without JS, you can use max-width/max-height
to keep the images in the boundaries of the .frame
elements. With width:auto;
and height:auto
the images will keep their original aspect ratio and won't be stretched over their original size.
To center the images horizontaly and verticaly in the frames, you can use :
position:absolute;
top:0; bottom:0;
left:0; right:0;
margin:auto;
Full CSS :
.frame{
width:300px; height:300px;
display:inline-block;
border:1px solid teal;
position:relative;
}
.frame > img{
max-width:100%; max-height:100%;
width:auto; height:auto;
position:absolute;
top:0; bottom:0;
left:0; right:0;
margin:auto;
}
Solution 2:
you cannot fit both width and height in frame to maintain aspect ratio. you can set either max-width or max-height value of image to 100% to fit in frame. try my code. I am using this method in my projects. I use wrap and inner to get border and padding in frame. no javascript is needed for fitting image. but you have to use to center your image in frame as width and height of individual image are dynamic value. my sample set image's max-width to fit in frame. HTML:
<div class='wrap'>
<div class='inner'>
<img src='http://www.pacificrimmovie.net/wp-content/uploads/Pacific-Rim-Movie-Striker-Eureka-Australian-Jaeger.jpg' />
</div>
</div>
CSS:
.wrap{
padding:10px;
border: 1px solid #777;
width: 150px;
height: 100px;
overflow:hidden;
float:left;
margin: 0px 20px 20px 0px;
}
.inner{
width: 100%;
height: 100%;
overflow:hidden;
text-align:center;
position:relative;
}
.inner img{
max-width: 100%;
position:absolute;
left:0;top:0;
}
Javascript:
$("img").each(function(){
var top_dif= ($(this).height()-$(this).parent().height())/2;
var left_dif= ($(this).width()-$(this).parent().width())/2;
$(this).css("top",-top_dif);
$(this).css("left",-left_dif);
});
have a look my samples:
debug
http://jsfiddle.net/7LLh14wL/3/ (overflow:visible)
final
http://jsfiddle.net/7LLh14wL/4/ (overflow:hidden)
Solution 3:
You should set only the width or height and not both, it will keep the ratio.
Using max-width and max-height will help for the smaller images.
However, you will need JS to center the larger images.
Solution 4:
use this snippet
JS
$(".frame").each( function(){
var imageUrl = $(this).find('img').attr("src");;
$(this).css('background-image', 'url(' + imageUrl + ')');
$(this).find('img').css("visiblity","hidden");
});
Css
.frame{
background-size:cover;
background-position:50% 50%;
}
Post a Comment for "How To Fit Image To Frame Keeping Aspect Ratio And Center In Thumbnail List"