zoukankan      html  css  js  c++  java
  • 绝对定位元素水平居中

    今天遇到了绝对定位的时候要让元素水平居中的问题。非绝对定位情况下,一般使用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{100%;position:relative;}
    #content div{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{100%;position:relative;}
    #content div{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为元素宽度的一半。

    这样就可以了

  • 相关阅读:
    hdu 5877 (dfs+树状数组) Weak Pair
    hdu 5876 (补图BFS) Sparse Graph
    bzoj 1051 (强连通) 受欢迎的牛
    UVA 10054 (欧拉回路) The Necklace
    HYSBZ 2743 (树状数组) 采花
    Codeforces 702C Cellular Network
    ZAB协议(Zookeeper atomic Broadcast)
    分布式一致性协议-2PC与3PC(二)
    分布式架构(一)
    redis集群
  • 原文地址:https://www.cnblogs.com/xiaochongchong/p/5567355.html
Copyright © 2011-2022 走看看