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

你设的宽度width:320要加单位px 也就是width:320px;除了使用margin:0 auto居中外,你用相对或绝对定位的话,想水平方向居中也可以加margin-left:-160px;和left:50%;
求教css的大神,相对定位后的div怎么水平居中?
你设的宽度width:320要加单位px 也就是width:320px;
除了使用margin:0 auto居中外,你用相对或绝对定位的话,想水平方向居中也可以加margin-left:-160px;和left:50%;2013-04-26
可以设置边界老设置居中,参考如下:
<div style="height:500px; width:500px; border:1px solid #ddd; position:relative; text-align:center; margin:0 auto;">
<div style="height:200px; width:300px; background-color:#ddd; margin:-100px 0 0 -150px; position:absolute; top:50%; left:50%;"></div>
</div>2015-07-10
因为你写错了 这段代码是可以居中的 <div id="container" style="position:relative;width:320px;margin:0 auto">2013-04-26
我试着可以居中的,就是你的width:320,少了px。
<div id="container" style="position:relative;width:320px; height:100px;margin:0 auto; border:1px solid #0000FF"></div>2013-04-26

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>2013-04-26
你为了相对定位居中也就是为了使用相对定位的特性,那么你可以先让一个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>2018-05-29
mengvlog 阅读 50 次 更新于 2025-12-17 04:39:30 我来答关注问题0
檬味博客在线解答立即免费咨询

CSS相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部