I know a 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 I'm not getting 100% results.
Here is the javascript
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 by 2.
- Calculating the div center which should be centered, Here it is
div2
- Now I reduce the half of the
div2
height with half ofdiv1
height by the result, if I give that as a margin-top, I should be able to get it to center vertically. Am I right? if not could some one explain to me?
Check the fiddle