Centre align absolute positioned div inside 100% width div

Hi, could anyone please enlighten me as to why the div#inner1 doesnt centre align within the container when using absolute positioning?

I need to absolute position within the #container div so #inner1 and #inner2 can be moved around and overlap one another.

Any ideas? Many thanks.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>


<style media="screen" type="text/css">

*
{
	margin: 0;
	padding: 0;
}

#container
{
	position: relative;
	width:100%;
	border: 1px solid green;
}

#inner1
{
	position: absolute;
	width: 500px;
	margin: 0 auto;
	border: 1px solid red;
	height: 500px;
}

#inner2
{
	position: absolute;
	width: 200px;
	height: 200px;
	border: 1px solid blue;
	margin:0 auto;
}

</style>
</head>
<body>
<div id="container">
	<div id="inner1"></div>
	<div id="inner2"></div>    
</div>
</body>
</html>

To answer my own question, is this because absolute positioned items dont have margins as such? If the inner divs are relatively positioned it works.

In order to get what I want should i relatively position the divs, then use a set a negative top-margin of #inner2 to the height of #inner1?

Little confused! :injured: Thanks.

Could a moderator please move this to the CSS section, sorry i posted in the wrong section.

One issue I see is that you have not declared your “left”, “right”, and “z-index” attributes. “margin: 0 auto;” will not work by itself for an a positioned div, you need to set 2 more things. You need to set [margin: 0 auto;] [left: 0;] and [right: 0;]

Re-wrote your code with a couple of adjustments, but it should work:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>


<style media="screen" type="text/css">
 
*
{
	margin: 0;
	padding: 0;
} 

#container
{
	position:relative;
	width:700px;
	height:700px;
	margin: 0 auto;
	left: 0;
	right: 0;
	background-color:#00FFCC;
}

#inner1
{
	position: absolute;
	margin:0 auto;
	top: 50px;
	left: 0;
	right: 0;
	width: 500px;
	height: 500px;
	background-color:#0066FF;
	z-index:20;
}

#inner2
{
	position: absolute;
	margin:0 auto;
	top: 100;
	left: 0;
	right: 0;
	width: 200px;
	height: 200px;
	background-color:#993366;
	z-index:30;
}

</style>
</head>

<body>
<div id="container">
	<div id="inner1"></div>
	<div id="inner2"></div>    
</div>
</body>

</html>