求教css的大神,相对定位后的div怎么水平居中?

<div id="container" style="position:relative;width:320;margin:0 auto">,这样好像不行

第1个回答  2013-04-26
<div style=" position:absolute; width:500px; height:300px; left:50%; top:50%; margin-left:-250px; margin-top:-150px; background:#ccc; text-align:center; line-height:300px;">
我在屏幕中间
</div>
第2个回答  2018-05-29
你为了相对定位居中也就是为了使用相对定位的特性,那么你可以先让一个div绝对定位,然后在里面设置一个一样大相对定位的块,这样你就可以让这个块里的元素有相对定位的属性;
<!DOCTYPE html>
<html>
<head>
<title>测试</title>
<style type="text/css">
*{
padding: 0px;
margin: 0px;
}
.demo{
position: absolute;
width:800px;
height:400px;
background-color: blue;
left: 0px;top: 0px;right: 0px;bottom: 0px;
margin: auto;
}
.demo-child{
position: relative;
width: 800px;
height: 400px;
background-color: green;
}
</style>
</head>
<body>
<div class="demo">
<div class="demo-child">
</div>
</div>
</body>
</html>