How can I adjust div with exact center of screen at any resolution with position:absolute.??
+4
A:
If the div has an known width and height, you can use negative margin:
div {
position: absolute;
width: 800px;
height: 500px;
left: 50%;
top: 50%;
margin-top: -250px;
margin-left: -400px;
}
Notice the negative margins are half of the width and height.
If the div's size is not known or is fluid, you have to use JavaScript. Here's how to make it work using jQuery:
$(function() {
$(window).resize(function() {
$('div.something').css({
left: $(window).width() - ($(this).width() / 2),
top: $(window).height() - ($(this).height() / 2)
});
});
$(window).resize();
});
Tatu Ulmanen
2009-12-07 12:52:18
Note that this will (on small windows) position content outside the window without making it accessible with scrollbars.
David Dorward
2009-12-07 12:53:18
+1
A:
The following bit of script will get you the Height and Width of visable space in the window.
<script type="text/javascript">
<!--
function pageWidth() {
return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}
function pageHeight() {
return window.innerHeight != null ? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null;
}
function posLeft() {
return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}
function posTop() {
return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}
function posRight() {
return posLeft() + pageWidth();
} function posBottom() {
return posTop() + pageHeight();
}
pageWidth()
pageHeight()
//-->
</script>
A little bit of simple math will get you the xy co-ordinates of the center of the screen x=Width/2 y= Height/2
set the top position to y+(DivHeight/2),and the left position of your dive to x-(DivWidth/2)
John Nunn
2009-12-07 12:58:27
A:
selector {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
Nimbuz
2009-12-07 13:08:05