Rohit
Rohit

Reputation: 370

Vertically center aligning images with absolute position

I am trying to create something

like this

<div class="model-info">
<div class="mainholder">
  <div class="divImage centeredImageContainer" align="center"> 
  <a href="talent_view.aspx?uid=e7385d69-8659-4ab4-a55d-d693ca9ba816">
        <img  class='centeredImage' style='width:80px;' src="http://t0.gstatic.com/images?    q=tbn:ANd9GcRX9N8qSDD4OhL9XH0N8RTbf3bObBR5TrqKeyUFxi-ZpAKQxyVsrw" alt="Anne" title="Anne">
   </a>
 </div>

the css is as :

.centeredImageContainer
{
  position:relative;
 }
 .centeredImage
{position: absolute;
top: 0;
bottom: 0;
margin: auto;
left: 0;
right: 0;}

But when i try to vertically center the image with absolute position it disturb the all design ,

like this

the image is dynamic have no fix size.

Also when i change the .divimage height in px , it accepts but when in % , it goes for 0px height.

how can i set this image vertically centered. Or am i missing something?

thank you

Upvotes: 1

Views: 2673

Answers (2)

alcoceba
alcoceba

Reputation: 423

Difficult when the image doesn't have fixed size. An alternative solution to abbood, is setting the image as a background image of the div and setting the background position to center center:

<div style="height: 600px">         
    <a href="#">
            <div style="text-align:center; height:100%; border-style:solid;  background: url(http://t0.gstatic.com/images?q=tbn:ANd9GcRX9N8qSDD4OhL9XH0N8RTbf3bObBR5TrqKeyUFxi-ZpAKQxyVsrw) no-repeat center center;">
            </div>
    </a>
</div>

The disadvantage is that you cannot change the image size, unless you use the CSS3 property background-size.

Upvotes: 3

abbood
abbood

Reputation: 23548

see my jsfiddle

basically i used this trick:

 <div class="outer"> 
  <div class="middle">
    <div class="inner">
      <!-- content to be vertically centered-->
    </div>
  </div>
 </div>

and css:

.outer {
    display: table;
    position: static;
    height: 9.22em; /* the height you want to center according to */

}
.middle {
    display: table-cell;
    vertical-align: middle;
    position: static;
}
.inner {
    margin-left: auto;
    margin-right: auto;
}

notes:

  • using absolute positioning should be avoided.. b/c it takes the element out of the document flow.. which causes unexpected results like in your case
  • in my solution you must know the height that you want to center according to.. so in my case.. i figured that the height of the right table is approx 9.22em.. so i put that.

Upvotes: 1

Related Questions