让人蛋疼的百分比相对定位问题,求高人解答

峭沙 2012-01-15 03:35:29
<!doctype html>
<html>
<head>
<style type="text/css">
#test{
border:1px solid black;
}
#sub{
position: relative;
width: 200px;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<div id="test">
<div id="sub">asljkkdfjkasdf</div>
</div>
</body>
</html>
这个简单的页面在firefox,chrome下并没有出现预想的效果,而在一向被我摒弃的IE上面,居然。。好吧,这个是的对相对定位的理解错误呢还是firefox, chrome的bug?
...全文
278 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
峭沙 2012-02-06
  • 打赏
  • 举报
回复
算了,回答都是牛头不对马嘴。还是把分比较热心的7楼吧
  • 打赏
  • 举报
回复
<!doctype html>
<html>
<head>
<style type="text/css">
#test{
border: 1px solid black;
height: 300px;
}
#sub{
position: relative;
width: 200px;
left: 50%;
top : 50%;
margin-left:-100px;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="test">
<div id="sub">asljkkdfjkasdf</div>
</div>
</body>
</html>
  • 打赏
  • 举报
回复
<!doctype html>
<html>
<head>
<style type="text/css">
#test{
border: 1px solid black;
height: 300px;
}
#sub{
position: relative;
display : inline-block;
width: 200px;
left: 50%;
top : 50%;
margin-left:-100px;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="test">
<div id="sub">asljkkdfjkasdf</div>
</div>
</body>
</html>
  • 打赏
  • 举报
回复
试下下面的代码
<html>
<head>
<style type="text/css">
#test{
border:1px solid black;
}
#sub{
position: absolute;
width: 200px;
top: 50%;
left: 50%;
margin:-100 0 0 -100;
text-align:center;
}
</style>
</head>
<body>
<div id="test">
<div id="sub">asljkkdfjkasdf</div>
</div>
</body>
</html>
峭沙 2012-02-06
  • 打赏
  • 举报
回复
还有个问题,为什么标准浏览器采用垂直百分比相对定位时会出现此问题?很不解啊很不解。。
峭沙 2012-02-06
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 iamaitman 的回复:]

测试了下,position为relative时,top如果为百分比的话,确实在不同浏览效果会有所不同,
建议在position为relative时,top不用百分比,而用数值
[/Quote]之所以会碰到这个问题是因为我想弄个垂直居中的效果来,当然上面的代码为便于理解是已经最简化了。而问题在于,用具体数值的话,不用js是不可能做到垂直居中的。
目前我想到的办法是IE6,7用相对定位+绝对定位来解决,而其他浏览器用display: table来解决。不知有没更简便的解决方案?
  • 打赏
  • 举报
回复
测试了下,position为relative时,top如果为百分比的话,确实在不同浏览效果会有所不同,
建议在position为relative时,top不用百分比,而用数值
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 axiheyhey 的回复:]

不好意思高估了大家的理解能力了
[/Quote]
这句话有点意思,哈哈!
峭沙 2012-02-06
  • 打赏
  • 举报
回复
不好意思高估了大家的理解能力了,你们不觉得垂直偏移有问题吗?在IE6,IE7下正常偏移,而在IE8及其他浏览器下却只有水平偏移,而没有垂直偏移。
  • 打赏
  • 举报
回复
你这样做。。如果分辨率发生改变位置就改变了。。
你如果是想要把它固定在最中间

可以这么做,在加载页面的时候执行个js方法
把div的做间距设置为浏览器当前的宽度减去div宽度的一半

上下的话 就把上间距 设置为浏览器当前的高度减去div高的一半

这样就能固定在最中间。。
x372563572 2012-01-16
  • 打赏
  • 举报
回复
貌似 top和left只能在 position:absolute 下才有效
三石-gary 2012-01-16
  • 打赏
  • 举报
回复
楼主又出这么高深的问题?!。。。没发现什么不同啊
hellNo 2012-01-16
  • 打赏
  • 举报
回复
这是什么效果?我把你这个在IE,Chrome,firefox,360急速浏览器,搜过浏览器,遨游上运行了一遍,效果全都一样么?有啥区别?

87,917

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧