Hello,

I'm trying to calculate the center of a DIV element. But it doesn't seem to be working, I don't quite get what to do with the calculations.. Here's my code:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">

body {

	background-color: #cccccc;

}

.rectangle {
	
	width: 400px;
	height: 100px;
	border-style:solid;
	border-width:1px;
	
	margin-top: 300px;
	margin-left: 500px;
}


.pointer {
	width: 400px;
	height: 100px;
	
	border-style:solid;
	border-width:1px;
	margin-top: 200px;
	margin-left: 50px;
	
}
</style>

<script>
$(document).ready(function() {
	
	var w = $('.rectangle').width();
	var h = $('.rectangle').height();
	
		var x = w/2; // 200
		var y = h/2; // 50
});

</script>

</head>

<body>
	
	<div class="rectangle"></div>

	<div class="pointer"></div>

</body>

Any ideas? Thanks =)

You need to take into account the margin and padding as well.

Ask Goog for some help with "CSS box model". Then ask yourself what you mean by "center".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.