您的位置:首页 > 其它

绝对定位元素水平居中

2016-06-07 16:12 330 查看
今天遇到了绝对定位的时候要让元素水平居中的问题。非绝对定位情况下,一般使用margin:0 auto的方法来进行居中,但在绝对定位情况下,margin:0 auto会失效。手机端网页的例子:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>定位测试</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<style>
body{padding:0;margin:0;}
#content{width:100%;position:relative;}
#content div{width:300px;;height:200px;background-color:#999;position:absolute;margin:0 auto;}
</style>
</head>
<body>
<section id="content">
<div>我是绝对定位的div</div>
</section>
</body>
</html>


  

上面的例子中,margin:0 auto没有作用。解决的办法是:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>定位测试</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<style>
body{padding:0;margin:0;}
#content{width:100%;position:relative;}
#content div{width:300px;;height:200px;background-color:#999;position:absolute;left:50%;margin-left:-150px;}
</style>
</head>
<body>
<section id="content">
<div>我是绝对定位的div</div>
</section>
</body>
</html>


  

Left:50%。利用margin可以设负值,margin-left为元素宽度的一半。

这样就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: