Search code examples
csstwitter-bootstrappositionoverflowcrop

Bootstrap Thumbnail Cropping and Positioning


I'm having these 3 images with different sizes. When I display them inside 3 containers like this:

@foreach (var item in Model) {   
    <div class="avatar-container">
        <img class="avatar img-thumbnail" src="@Href("~/Content/Avatars/",item.Name+".jpg")" />  
    </div>
}

This is my CSS file:

div.avatar-container {
    display: inline-block;
    max-height: 50px;
    overflow: hidden;
    width: 70px;
}

.avatar {
    width: 100%;
    height:auto;
    overflow: hidden;
}

And also img-thumbnail is from bootstrap.css (line 368). After a while I've managed to crop images (using overflow property) so that the each avatar is displayed as 70x50 thumbnail.

Take a look at these 3 returned thumbnails: image
[PROBLEMS]

image1. It also cropped the nice bottom part of my thumbnail.
image2. Well I would think that thumbnails are squares, not rectangles.
image3. How do I crop to the middle of the image (in both vertically and horizontally manners)?


Solution

  • Here's what I came up with, using JavaScript and another thumbnail container.

    @*HTML-----------------------------------------------*@
    @foreach (var item in Model) {   
        <div class="avatar-container">
            <div class="img-thumbnail">
                <img class="avatar img-thumbnail" src="@Href("~/Content/Avatars/",item.Name+".jpg")" />  
            </div>
        </div>
    }
    @*JavaScript-----------------------------------------*@
    //If the image has greater Width => display as landscape
    <script>
            $(".avatar").each(function () {
                if (this.naturalWidth > this.naturalHeight) {
                    $(this).addClass("landscape");
                }
            });
    </script>
    @*CSS------------------------------------------------*@
    //That big container outside
    div.avatar-container {
        display: inline-block;
        position: relative;
        width: 70px;
        height:70px;
        overflow: hidden;
    }
    //And here's the extra thumbnail container
    div.img-thumbnail{
        width:100% !important;
        height:100%;
        background-color:#e1dada;
    }
    //This is for the actual image
    .img-thumbnail{
        padding:1px !important;
    }
    //This one sets the image as a portrait
    .avatar {
        position: absolute;
        top: 50%;
        left: 50%;
        height: 100%;
        width: auto;
        -webkit-transform: translate(-50%,-50%);
        -ms-transform: translate(-50%,-50%);
        -moz-transform: translate(-50%,-50%);
        -o-transform: translate(-50%,-50%);
        transform: translate(-50%,-50%);
    }
    //This one helps setting up the image horizontally
    .landscape{
        width:100%;
        height:auto;
    }
    

    The final results look like this