Center image in container element with fixed size (CSS, HTML)

You can see it work on http://jsfiddle.net/km5dk/8/

But I think you search something like this.

### HTML ###


    <div id="container">
        <div class="image-container">
            <img src="#" alt="A image" />
        </div>
    </div>​


    ### CSS ###

    #container {
        width: 130px;
        height: 60px;
        display: table;
        background-color: #ccc;         
    }

    #container .image-container {
        text-align: center;
        vertical-align: middle;
        display: table-cell;
    }

    #container .image-container img {
        max-width: 160px;
        max-height: 60px;        
    }

Thinking a little outside of the box (excuse the deliberate pun!) you could use background-size on your container's CSS rule, and background-image: url(this_image.jpg); as an inline style on the individual containers themselves. This would handle all of the scaling for you in a smaller and neater package.

Setting background-size: cover; would scale the image so that the smallest dimension matched (though there may be some cropping), and background-size: contain; would ensure the entire image fitted.

It's another option...

Danny


Use positioning. The following worked for me:

div{
    display:block;
    overflow:hidden;
    width: 70px; 
    height: 70px;  
    position: relative;
}
div img{
    min-width: 70px; 
    min-height: 70px;
    max-width: 250%; 
    max-height: 250%;    
    top: -50%;
    left: -50%;
    bottom: -50%;
    right: -50%;
    position: absolute;
}

make image center

.image-container {
    width: 500px;
    height: 500px;
    position: relative;
}

.image-container img {
    position: absolute;
    right: 0;
    left: 0;
    top: 0;
    bottom: 0;
    margin: auto auto;
}

auto-resize an image to fit a div container

.image-container img {
    max-height: 100%;
    max-width: 100%;
}

Tags:

Html

Css