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:
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>
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">​
</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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With