Om3ga
Om3ga

Reputation: 32823

How to find the center of the div using jquery

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

Answers (4)

alexbusu
alexbusu

Reputation: 741

jQuery way:

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

Upvotes: -1

Clyde Lobo
Clyde Lobo

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

kbdjockey
kbdjockey

Reputation: 897

You should check:

  1. width / outerWidth
  2. height / outerHeight

Upvotes: 0

Ciprian Mocanu
Ciprian Mocanu

Reputation: 2196

Is it this?

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

Upvotes: 6

Related Questions