开发者

adjusting div position

开发者 https://www.devze.com 2022-12-13 21:13 出处:网络
How can I adjust div with exact center of screen at 开发者_如何学Goany resolution with position:absolute.??If the div has an known width and height, you can use negative margin:

How can I adjust div with exact center of screen at 开发者_如何学Goany resolution with position:absolute.??


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();
});


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)


CSS Dead Center

selector {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消