I'm trying to fit any sized image inside a (always) square div, and retain the aspect when the size of the parent div changes. Here's what I'm doing:
CSS:
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo_container a img{
position:absolute;
}
HTML
<!--p>Photo's height>width </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg"
style="width:100%; height:auto;">
</img>
</a>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg"
style="width:auto; height:100%;left=-100px">
</img>
</a>
</div>
Javascript:
// fix image size on load
$(".photo").one("load", function() {
fixImage($(this));
}).each(function() {
if(this.complete) $(this).load();
});
// Just to test if everything's working fine
$(".photo").on("click",function(){
var rand = Math.floor(Math.random() * 200) + 80;
$(this).parent().parent().width(rand);
$(this).parent().parent().height(rand);
fixImage($(this));
});
// Brings the photo dead center
function fixImage(obj){
//alert("something changed");
var pw = obj.parent().parent().width();
var ph = obj.parent().parent().height();
var w = obj.width();
var h = obj.height();
console.log(w+" "+pw);
if(h>w){
var top = (h-ph)/2;
obj.css("top",top*-1);
}else{
var left = (w-pw)/2;
obj.css("left",left*-1);
}
}
Working example: http://jsfiddle.net/vL95x81o/4
How can this be done without using jquery but only CSS? If the size of the div never changes, this solution is fine. But I'm looking into responsive designs and seems like the size of the photo_container
div might need to change (via CSS) based on the size of the screen.
Here are the photos before being cropped:
I solved this without using background-images or JS. The height comes from the before tag in the container. The 100% of the padding equals 100% of the widht. So the height has always the same width.
http://jsfiddle.net/a1rLeq06/
The css:
The background solution that others have posted was my initial thought, but if you want to still use images then you could do the following:
CSS:
HTML:
This will make any image inside to be either 100% high or 100% wide, depending on the shortest attribute, and centralise them horizontally and vertically.
Edit
It's worth noting that transform is not supported in IE8 or Opera Mini - http://caniuse.com/#feat=transforms2d
Use background images.
You could do something like this:
http://jsfiddle.net/vL95x81o/5/
I have changed the imgs to divs with background images and used background position cover with the image being centered.