让绝对定位原素快速居中

chenjwjw 2012-05-01 09:26:12
根据绝对定位特点,假设某原素已设定位属性为绝对定位:position:absolute;那么该元素就会脱离正常文档流,此时设了绝对定位的元素的left,top,bottom,right的值如不设,默认并不是为0,该元素还会停留在原来的位置,只是不在正常文档流之中!同时该元素仍可以使用margin进行边距的偏移,而偏移的参照物就是其本身!因为绝对定位使用方向偏移再混合margin的方向偏移,两都同方向的值会累加!如left:20px;margin-left:20px;此时实际偏移的值是40px;根据这个规律,假如想让这个具有绝对定位的元素居中就有办法了!可以设:left:0px; right:0px; top:0px;而再设置margin:0px auto;即可使该元素靠上居中显示!这点在做顶部时也很方便哦!
...全文
148 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kinghome 2012-05-02
  • 打赏
  • 举报
回复
span {
width:100px; height:100px;
border:1px solid red;
position:absolute;
left:50%;top:50%;
margin: -50px -50px;
}
happy59 2012-05-02
  • 打赏
  • 举报
回复
span {
width:100px; height:100px;
border:1px solid red;
position:absolute; left:50%;
margin-left:-50px;/*50%宽度*/
}
ddcatlee 2012-05-02
  • 打赏
  • 举报
回复
google -》绝对定位元素的box model
  • 打赏
  • 举报
回复
<div style="position:fixed;width:100%;height:80px;left:0;bottom:0">
<div style="position:relative;width:960px;margin:0 auto;height:80px;background:#ccc;display:block;">
 
</div>
</div>
001007009 2012-05-01
  • 打赏
  • 举报
回复
光看这个方法,起初表示怀疑,虽说absolute之后,margin有效,但是用0 auto来居中怎么会有效果?
top left right bottom同时出现有疑问,因为之前也遇到过类似问题,同时出现的话,只有left,top有效,换句话説left top 比 right bottom的优先级高。

测试了下,在ff下居然真的句中了,但是ie6下却无动于衷。


<!DOCTYPE HTML>
<html>
<head>
<meta charset="gb2312" />
<title></title>
<style>
span {
width:100px; height:100px;
border:1px solid red;
position:absolute; left:0; top:0; right:0; bottom:0;
margin:0 auto;
}
</style>
</head>
<body>
<span>123</span>
</body>
</html>


由于上面对4个方向的作用提出了质疑,于是又测试了下,把right删除了,ff却不居中了,可见right是起了作用的,确实有些疑惑,再思考下。

<!DOCTYPE HTML>
<html>
<head>
<meta charset="gb2312" />
<title></title>
<style>
span {
width:100px; height:100px;
border:1px solid red;
position:absolute; left:0; top:0; bottom:0;
margin:0 auto;
}
</style>
</head>
<body>
<span>123</span>
</body>
</html>

61,128

社区成员

发帖
与我相关
我的任务
社区描述
层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。
社区管理员
  • HTML(CSS)社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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