Designer DR-1447 Image UI - Resize with proportions
by infous
HTML
<div class="c stretch">
<img src="http://image.tsn.ua/media/images2/original/Dec2011/383533306.jpg">
</div>
<div class="c fit">
<img src="http://image.tsn.ua/media/images2/original/Dec2011/383533306.jpg">
</div>
<div class="c crop">
<img src="http://image.tsn.ua/media/images2/original/Dec2011/383533306.jpg">
</div>
<div class="c test-cover">
<img src="http://image.tsn.ua/media/images2/original/Dec2011/383533306.jpg">
</div>
<div class="c test-cover-2">
<img src="http://image.tsn.ua/media/images2/original/Dec2011/383533306.jpg">
</div>
<div class="c center">
<img src="http://image.tsn.ua/media/images2/original/Dec2011/383533306.jpg">
</div>
CSS
.c {
margin: 10px 0;
outline: 2px dashed #aaa;
overflow: hidden;
}
.c img {
display: block;
}
/* stretch */
.stretch {
height: 200px;
width: 400px;
}
.stretch img {
width: 100%;
height: 100%;
}
/* fit */
.fit {
width: 200px;
}
.fit img {
width: 100%;
}
/* crop (background-size: cover) */
.crop {
background: #ccc;
width: 700px;
height: 200px;
}
.crop1 img {
max-width: 100%;
width: 100%;
}
.crop2 img {
max-height: 100%;
height: 100%;
}
/* test cover css only */
.test-cover {
background: #ccc;
position: relative;
width: 500px;
height:100px;
}
.test-cover img {
min-height: 100%;
min-width: 100%;
}
/* test cover 2 */
.test-cover-2 {
background: #ccc;
position: relative;
width: 2000px;
height:100px;
}
.test-cover-2 .img {
background-size: cover;
background-position: center center;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
.test-cover-2 img {
display: none;
}
/* center (background-size: contain) */
.center {
background: #ccc;
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
}
.center img {
display: inline-block;
margin: 0 auto;
max-height: 100%;
max-width: 100%;
vertical-align: middle;
}
JavaScript
jQuery(function($) {
crop();
cropImgLayer();
});
/* http://css-tricks.com/perfect-full-page-background-image/ */
function crop() {
var c = $(".crop");
var img = $(".crop img");
var cRatio = c.width() / c.height();
var imgRatio = img.width() / img.height();
c.removeClass("crop1").removeClass("crop2");
if (cRatio < imgRatio) {
c.addClass("crop2");
} else {
c.addClass('crop1');
}
}
function cropImgLayer() {
var c = $(".test-cover-2"),
img = $(".test-cover-2 img");
var imgSrc = img.attr("src");
$("<div class=\"img\"></div>").css("background-image", "url(" + imgSrc + ")").appendTo(c);
}