I want to keep an absolute positioned DIV #box
at the middle of the screen even after window re-size and for all major device (responsive design). Responsive #box is done using css3 media queries while left
is calculated using jquery. But I can positioned my box exactly at the center, on window re-size for small screen there is unequal left & right margins.
<HTML>
<body>
<div id ="box">
<a> is am athe centre?'</a>
</div>
</body>
</HTML>
css :
#box {
position:absolute;
background:red;
width:900px;
height:400px;
}
@media only screen and (min-width: 979px)
{
#box{width:760px;background:yellow;}
}
@media only screen and (min-width: 768px) and (max-width: 979px)
{
#box{width:760px;background:pink;}
}
@media only screen and (min-width: 480px) and (max-width: 767px)
{
#box{width:460px;background:black;}
}
@media only screen and (min-width: 321px) and (max-width: 479px)
{
#box{width:300px;background:blue;}
}
@media only screen and (max-width: 320px)
{
#box{width:300px;background:grey;}
}
jQuery :
function leftmargin(){
var w_box = ($('#box').width());
var w_window = $(window).width();
var w_left = (w_window - w_box)/2 ;
$("#box").css("left", w_left + "px");
}
$(window).resize(function() {
leftmargin();
});
$(document).ready(function() {
leftmargin();
});