开发者

Position the center of a div to given coordinates on a page

var x=200, y=140

How would I position the center of开发者_开发百科 a div (width & height = 50px) to the above coordinates?


You can achieve this with pure CSS. Assuming your square div is static at 50px, parent div can have any coordinates:

.parent{
    position:relative;
    width:200px;
    height:140px;
}
.child{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-25px; /* negative half of div height*/
    margin-left:-25px; /* negative half of div width */
    width:50px;
    height:50px;
}

Check working example at http://jsfiddle.net/F4RVf/1/


this should work:

//onload 
$(document).ready(function() {
    var x=200;
    var y=140;
    var div = $("#myDiv");
    var divWidth = div.width() / 2;
    var divHeight = div.height() / 2;
    div.css('left', x - divWidth );
    div.css('top', y - divHeight);
});

here is the CSS

#myDiv{position:absolute; left:0; width:50px; height:50px; background-color:red;}

See it in action here: http://jsfiddle.net/cgvAB/3//


Depending on the rest of the page, you could use absolute positioning (potentially inside of a position:relative parent, if those are offsets):

<style type="text/css">
    #myDiv {
        position: absolute;
        width: 300px;
        height: 300px;
        left: 200px;
        top: 140px;
        margin: -150px 0 0 -150px;
    }
</style>

If your div is variable height/width, you'd need to do the margin bit with javascript (eg with jQuery):

<script type="text/javascript">
    var $myDiv = $('#myDiv');
    $myDiv.css({
        'margin-left': -($myDiv.outerWidth({ 'margin': true }) / 2),
        'margin-top': -($myDiv.outerHeight({ 'margin': true }) / 2)
    });
</script>


<div id="mydiv" style="position: absolute; top:115px; left:175px; width:50px; height:50px;"></div>

*in case of dynamic coordinates add the following to event handling javascript function:

myDiv = document.getElementById('mydiv');
myDiv.style.top = x - 25 + 'px';
myDiv.style.left = y - 25 + 'px';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜