Reputation: 752
I need my thumbnail to fill in the space of the container which is 100x100px. But I have some landscape images that I would like to have centered inside so they get cropped of left and right side. Is it possible to achieve this without using a background image.
Here is what I have so far:
HTML
<div class="outer">
<div class="thumbnail">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" alt="" />
</div>
</div>
CSS
.outer {
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid grey
}
.thumbnail {
overflow: hidden
}
img {
width: auto;
height: 100px;
}
http://codepen.io/ingvi/pen/JYjBNP?editors=110
Upvotes: 0
Views: 2942
Reputation: 1318
Okay, here's a new answer using JS to set our clipping amounts:
http://codepen.io/tinyglowstudio/pen/ojNVGj?editors=111
HTML:
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=450%C3%97250&w=450&h=250" alt="" />
CSS:
img
position: absolute;
width: auto;
height: 100px;
z-index: 0;
JS
$(".thumbnail img").each(function() {
var Height = 100 / $(this).height();
var Width = $(this).width() * (100 / $(this).height());
var trimAmount = (Width - 100) / 2;
$(this).css({
'transform' : 'translate(-' + trimAmount + 'px, 0)',
'clip' : 'rect(0 ' + (100 + trimAmount) + 'px 100px ' + trimAmount + 'px)'});
});
Upvotes: 0
Reputation: 1318
Are your portrait images always going to be the same size, or will they be variable widths? If they're the same size, you can do this:
http://codepen.io/tinyglowstudio/pen/ojNVGj?editors=110
HTML:
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=300%C3%97100&w=300&h=100" alt="" />
I changed it to 300 and 100 for my own math. You can do the algebra yourself :)
CSS:
img
position: absolute;
width: auto;
height: 100px;
z-index: 0;
clip: rect(0px 200px auto 100px);
transform: translate(-100px);
This works in IE
Upvotes: 1
Reputation: 4407
If you don't mind about IE support, you can use object-fit: cover;
property.
css:
.outer {
margin: 0 auto;
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid grey;
}
.thumbnail {
overflow: hidden;
}
img {
width: 100%;
height: 100px;
object-fit: cover;
}
html:
<div class="outer">
<div class="thumbnail">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" alt="" />
</div>
</div>
demo: https://jsfiddle.net/d0wvvdf8/1/
Upvotes: 2
Reputation: 3921
If you adjust the width from width: auto
to width: 100px
the image gets resized to fit inside the thumbnail. If that's what you want.
Upvotes: 0