admin管理员组

文章数量:1336357

I have a div tag with id container. How can I find its center using either jquery or javascript?

<div id="container"></div>

here is css

#container {
    width: 300px;
    height: 300px;
    border: 1px solid red;
}

I have a div tag with id container. How can I find its center using either jquery or javascript?

<div id="container"></div>

here is css

#container {
    width: 300px;
    height: 300px;
    border: 1px solid red;
}
Share Improve this question asked Sep 11, 2012 at 14:08 Om3gaOm3ga 33k45 gold badges149 silver badges230 bronze badges 5
  • 1 Find the centre relative to what? The element's top-left corner, the top-left corner of the page..? – David Thomas Commented Sep 11, 2012 at 14:09
  • the element's top left corner. – Om3ga Commented Sep 11, 2012 at 14:10
  • 2 something like: div = $('#container'); var center = new Array( div.width() / 2 , div.height() / 2 ); :) – alexbusu Commented Sep 11, 2012 at 14:10
  • 2 @AlexanderV.B. I remend width * 0.5 instead of width / 2 because it is faster ;) – Ron van der Heijden Commented Sep 11, 2012 at 14:11
  • Note that position() is relative to the element's offset parent and that offset() is relative to the document. If you want to know where the center of a div is on the screen, use offset(). – Shmiddty Commented Sep 11, 2012 at 14:21
Add a ment  | 

4 Answers 4

Reset to default 6

Is it this?

var cX = $('#container').offset().left + $('#container').width()/2;
var cY = $('#container').offset().top + $('#container').height()/2;
$(function(){
 var $this = $("#container");
 var offset = $this.offset();
 var width = $this.width();
 var height = $this.height();

 var centerX = offset.left + width / 2;
 var centerY = offset.top + height / 2;
 console.log(centerX ,centerY)

})

You should check:

  1. width / outerWidth
  2. height / outerHeight

jQuery way:

var div = $('#container');
var divCoords = { 
    x : div.width() * 0.5 , 
    y : div.height() * 0.5
};

本文标签: javascriptHow to find the center of the div using jqueryStack Overflow