0

Let me start from the illustration which presents the outcome I want to achieve: http://jsfiddle.net/2DvF6/1/

<div id="controler">
  <img id="i1" src="arrow1.png">
  <img id="i2" src="arrow1.png">
</div>

img{
  width:100%;
}
#i1{
  visibility:hidden;
}
#i2{
  position:absolute;
  top:-50%;
  left:0px;
}
#controler{
  position:absolute;
  width:100px;
}

Assume I control only the width of the div#controler and I do not know (and do not want to know) what are the dimensions of the image. I use the nice feature of the img tag, that if height is unspecified then the aspect ratio is used to compute it. Now, how can I move the image -50% of its height up, as in the example? I tried position:relative + top:-50% but it did nothing good. The "solution" I presented requires me to put two images, one invisible to force the size of the div, and one which can then use top:-50%. I've tried vertical-align:middle but it did not help.

qbolec
  • 5,374
  • 2
  • 35
  • 44

4 Answers4

0

Intead of using position: absolute;, use vertical-align: middle;.

bookcasey
  • 39,223
  • 13
  • 77
  • 94
0

Vertical alignment is VERY difficult to get to work like that. I would either put it into a table cell which handles easily and well. Or use jquery to dynamically get the image size and properly position it.

Cliff Ribaudo
  • 8,932
  • 2
  • 55
  • 78
0

css

  img{
      width:100%;
    }
    #i1{
      visibility:hidden;
        position: absolute;
    }
    #i2{

    }
#controler{
    position: absolute;
    width: 100px;
    top: 50px;
    left: 50px;
    border: 1px solid red;
}

html

<div id="controler">      
    <img id="i1" src="http://vanisoft.pl/~lopuszanski/oblep/img/arrows/1_big.png">
    <img id="i2" src="http://vanisoft.pl/~lopuszanski/oblep/img/arrows/1_big.png">
</div>​
Nandhakumar
  • 366
  • 2
  • 9
  • Perhaps I did not make myself clear: I need a solution in which there is no duplicated tag. – qbolec Jul 26 '13 at 18:14
0

Try using http://shipp.co/midway/ It is a JS library that will center any content vertically and horizontally.

HTML:

<div id="controller" class="centerHorizontal centerVertical">
 <img src="http://www.placehold.it/450x250" alt="Placeholder image">
</div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="midway.min.js" type="text/javascript"></script>

here is a jsbin with the code: http://jsbin.com/apuyiq/2/edit

mkuk
  • 300
  • 1
  • 3
  • 10