Centering Horizontally Vertically jQuery
Special CSS classes to center horizontally, vertically or both horizontally and vertically with jQuery
Samples of Centering Horizontally Vertically jQuery
.centerHorizontally
.centerVertically
.centerBoth
HTML markup for Centering Horizontally Vertically jQuery
<div class="divOuter"> <div class="divInner centerHorizontally"> .centerHorizontally </div> </div> <div class="divOuter"> <div class="divInner centerVertically"> .centerVertically </div> </div> <div class="divOuter"> <div class="divInner centerBoth"> .centerBoth </div> </div>
CSS style for Centering Horizontally Vertically jQuery
.divOuter{
float:left;
height:100px;
width:70%;/*can be % px*/
}
.divInner{
display:inline;/*IE6*/
float:left;
width:auto;/*can be % px auto*/
}
jQuery code for Centering Horizontally Vertically jQuery
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
function centerHorizontally(){
$('.centerHorizontally').each(function(){
$(this).css('margin-left',($(this).parent().innerWidth()-$(this).outerWidth())/ 2 + 'px');
});
};
function centerVertically(){
$('.centerVertically').each(function(){
$(this).css('margin-top',($(this).parent().innerHeight()-$(this).outerHeight())/ 2 + 'px');
});
};
function centerBoth(){
$('.centerBoth').each(function(){
$(this).css('margin-left',($(this).parent().innerWidth()-$(this).outerWidth())/ 2 + 'px');
$(this).css('margin-top',($(this).parent().innerHeight()-$(this).outerHeight())/ 2 + 'px');
});
};
$(function(){
centerHorizontally();
centerVertically();
centerBoth();
});
</script>
2011
Web Development - XHTML CSS JavaScript jQuery.