Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

Resize to fit image in div, and center horizontally and vertically

I have an image in a div. I would like the image to resize to fit the div, and be horizontally and vertically centered. I would like a solution that works in ie >= 8.

Upvotes: 36

Views: 147937

Answers (5)

NOTSermsak
NOTSermsak

Reputation: 356

This is my best suggestion for centering any image even resizing:

<style>     
    img {
        height: 100%;
        object-fit: cover;
        object-position: center;
        margin: auto;
        min-width: 100%;
        vertical-align: middle;
    }
</style>

  img {
      height: 100%;
      object-fit: cover;
      object-position: center;
      margin: auto;
      min-width: 100%;
      vertical-align: middle;
  }
  
  div {
      resize: both;
      overflow: auto;
  }
<div style='width: 300px; height: 150px;'>
    <img src="https://www.bing.com/th?id=OBTQ.BT3B532FA818DCD962FEE4A298558E29679C593839A9D0793843301816155FDD10&rs=2&c=1" alt>
</div>

Upvotes: 0

TwistedOwl
TwistedOwl

Reputation: 1324

NOT SUPPORTED BY IE

More info here: Can I Use?

.container {
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.container img {
  object-fit: cover;
  width: 100%;
  min-height: 100%;
}
<div class='container'>
    <img src='http://i.imgur.com/H9lpVkZ.jpg' />
</div>

Upvotes: 10

Hugo
Hugo

Reputation: 29394

Only tested in Chrome 44.

Example: http://codepen.io/hugovk/pen/OVqBoq

HTML:

<div>
<img src="http://lorempixel.com/1600/900/">
</div>

CSS:

<style type="text/css">
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    max-width: 100%;
    max-height: 100%;
}
</style>

Upvotes: 34

Ravi Soni
Ravi Soni

Reputation: 1343

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Upvotes: 2

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

This is one way to do it:

Fiddle here: http://jsfiddle.net/4Mvan/1/

HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

Upvotes: 50

Related Questions