Html – CSS img align: how to set a img middle-right align in a DIV

alignmentcsshtmlimagevertical-alignment

I am looking for a simple way to middle-right align a img in a DIV, i.e., vertical-middle and horizontal-right align, like this:

enter image description here

I tried using vertical-align:middle and float:right in IMG styles, but seems not work together..

<div style='height: 300px; width: 300px'>
    <img src= 'http://www.w3schools.com/tags/smiley.gif' style='vertical-align: middle; float: right;'/>
</div>

Best Solution

There are many ways to do this. It is very easy if image and its container height is known, tricky otherwise. Choose the solution that suit your needs:

Method 1: line height, text-align and vertical align

#div1 {
  width: 300px;
  height: 300px;
  background-color: blue;
  line-height: 300px;
  text-align: right;
}
#div1 img {
  vertical-align: middle;
}
<div id="div1">
  <img src="http://dummyimage.com/100x50/fc0/000000.png">&#8203;
</div>

Method 2: absolute/relative positioning, image height known

#div1 {
  width: 300px;
  height: 300px;
  background-color: blue;
  position: relative;
}
#div1 img {
  position: absolute;
  right: 0;
  top: 50%;
  margin-top: -25px; /* -(image_height/2) */
}
<div id="div1">
  <img src="http://dummyimage.com/100x50/fc0/000000.png">
</div>

Method 3: absolute/relative positioning, image and container height known

#div1 {
  width: 300px;
  height: 300px;
  background-color: blue;
}
#div1 img {
  float: right;
  position: relative;
  top: 125px; /* (div_height-image_height)/2 */
}
<div id="div1">
  <img src="http://dummyimage.com/100x50/fc0/000000.png">
</div>

jsFiddle