Reputation: 32823
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;
}
Upvotes: 1
Views: 6145
Reputation: 741
jQuery way:
var div = $('#container');
var divCoords = {
x : div.width() * 0.5 ,
y : div.height() * 0.5
};
Upvotes: -1
Reputation: 9174
$(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)
})
Upvotes: 2
Reputation: 2196
Is it this?
var cX = $('#container').offset().left + $('#container').width()/2;
var cY = $('#container').offset().top + $('#container').height()/2;
Upvotes: 6