Dmytro
Dmytro

Reputation: 17176

How to fit image in div container?

I have image <img> in <div> container.

<div id="container">
    <img id="image" />
</div>

Images can be different sizes and the container size is fixed. I want to fit image fully in the container, centered, without stretching and without using this image as css background of the <div> as most of the stack overflow answers suggest. Here is the js fiddle of what I've already tried.

Upvotes: 0

Views: 371

Answers (3)

MKreegs
MKreegs

Reputation: 138

I agree with imnancysun. However, you should add the vendor prefixes to make sure the css will work with more browsers. I would suggest:

.container {
    margin: 20px;
    width: 100px;
    height: 120px;
    position:relative; 
    border: 1px solid red;  
}

.container img {
    max-width:100%;
    max-height:100%;
    position:absolute; 
    top:50%;
    left: 50%;
    -webkit-transform: translateY(-50%) translateX(-50%);
        -ms-transform: translateY(-50%) translateX(-50%);
            transform: translateY(-50%) translateX(-50%);
}

I use firefox most of the time. Without the prefixes, all of the images where outside of the divs.

This is a cool tool to help add the vendor prefixes to your CSS.

Upvotes: 1

ala_747
ala_747

Reputation: 611

You can do:

.container {
    margin: 20px;
    width: 100px;
    height: 120px;
    text-align:center;
    border: 1px solid red;    
}

.container img {
    width:auto;
    max-width: 100%;
    height: auto;
    max-height: 100%;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

I've made you a working fiddle example with your code.

Upvotes: 1

imnancysun
imnancysun

Reputation: 632

Try this:

.container {
    margin: 20px;

    width: 100px;
    height: 120px;
    position:relative; 
    border: 1px solid red;  
}

.container img {
    max-width:100%;
    max-height:100%;
    position:absolute; 
    top:50%;
    left: 50%;
    transform: translateY(-50%) translateX(-50%);
}

Here's the jsfiddle

Upvotes: 2

Related Questions