Skip to content Skip to sidebar Skip to footer

Vertical Middle Alignment Of Image Within Div?

Possible Duplicate: vertical alignment of image inside a div OK, this what I'm trying to do : I'm having an empty div (a box), with almost no height. I'm making an AJAX request

Solution 1:

http://jsfiddle.net/teresko/5mG2y/

The basic idea is the use display: table-cell; and then vertical-align: middle;

the HTML

<div class="container">
    <div class="holder">
        <img class="stuff" src="path/to/image.png">
    </div>                
</div>

the CSS:

.container{ 
    /* the container in which image is placed */
    height:         300px;
    margin:         0 auto;
    width:          200px;
}

.holder{
    display:        table-cell;
    width:          100%;
    vertical-align: middle;
    height:         inherit;
}

.stuff{
    display:        block;
}

This way the placement of image will not depend on dimensions of container. It also can be adjusted to be in horizontal center too. All you have to do is to add .stuff{ margin: 0 auto;}.


Solution 2:

Don't forget that table-cell is not the correct usage. You don't want images to be trated as table cells, since table cells should only contain table data. Just raising a caution flag. Stick to the semantics.

it's better to use the answer from that other thread. This:

#container { position: relative; }
#container img {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: /* -1/2 the height of the image */
  margin-left: /* -1/2 the width of the image */
}

Good luck!


Solution 3:

With jQuery

//HTML
<div><img src="loader.gif" class="loader" alt="Loader" /></div>

//JS
$.fn.centeringIn = function(){
 var pere = this.parent();
 (pere.css("position") == 'static') ? pere.css("position","relative"):pere.css("position");
 this.css({
  'position' : 'absolute',
  'top' : ( pere.height() - this.height() )/2+'px',
  'left' : ( pere.width() - this.width() )/2+'px'
 });
}

$(document).ready( function() {
 $('.loader').centeringIn();
});

Solution 4:

Add some margin-top to the image style so that it is aligned in the middle of the div. Say your div is 50px height and your image has a height of 5px. Then make your margin-top 20px to put it in the middle.


Post a Comment for "Vertical Middle Alignment Of Image Within Div?"