Tuesday, 10 September 2013

centering a div vertically using jquery

centering a div vertically using jquery

hi i know lot of techniques out there for centering a div vertically but i
made this according to my thinking.i believe the concept is correct but am
not getting 100% result. Here is the js
jQuery(document).ready(function(){
var l=jQuery('.div1').height();
var level=l/2;
var bt=jQuery('.div2').height()/2;
var val=level-bt;
jQuery('.div2').css("margin-top",val);
});
Css
.div1
{
height:50px;
background-color: red;
position:relative;
}
.div2
{
border: 1px solid;
background-color: orchid;
text-decoration: none;
letter-spacing: 1px;
text-transform:uppercase;
padding: 5px;
position: absolute;
right:5%;
top:0%
}
Html
<div class="div1"><div class="div2">vertical</div>
I calculated the outer div height and calculating the center by dividing
it 2.
Calculating the div center which should be centered, Here it is div2
Now if i reduce the half of the div2 height with half of div1 height by
the result if i give that as margin-top i should able to get it to center
vertically. Am i right? if not could some one explain me?
Check the fiddle

No comments:

Post a Comment