css div居中顯示的4種寫法


Demo:http://www.feman.cn/h5/center.html

 

1.absolute 絕對定位 這是我們最常用的一種居中定位寫法 要求必須確定div的寬高度 目前市面上的瀏覽器基本上都支持這種寫法

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>absolute居中定位</title>
        <style>
          *{margin:0;padding:0}
          .absoluteCenter{ width:600px; height:400px;position:absolute; background: rgb(50,183,97); left:50%; top:50%; margin-left: -300px; margin-top: -200px;  }
        </style>
    </head>
    <body>
        <div class="absoluteCenter">我是absolute居中定位</div>
    </body>
    </html>

2.translate定位 這是css3 transform的屬性 通過自身的偏移來定位 而且他有個極大的好處 不需要知道div的寬高度 就像js里的this self一樣 可以將寬高度設為百分比 IE browser<IE9不支持 在移動端使用較好

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>translate居中定位</title>
        <style>
          *{margin:0;padding:0}
          .translateCenter{ width: 40%; height: 20%; position: absolute; left:50%; top:50%; transform:translate(-50%,-50%); background: #2d2d2d;}
        </style>
    </head>
    <body>
        <div class="translateCenter">我是translate居中定位</div>
    </body>
    </html>

 3.margin居中定位  不需要確定div的寬高度 讓top,bottom,left,right都為0 再加個margin:auto 神來之筆 IE browser< IE 8不支持

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>margin居中定位</title>
        <style>
          *{margin:0;padding:0}
          .marginCenter{ width:200px; height: 200px; position: absolute;left:0; top:0; right:0; bottom: 0; margin: auto; background: #f2056e;}
        </style>
    </head>
    <body>
        <div class="marginCenter">我是margin居中定位</div>
    </body>
    </html>

4.fixed的居中定位 這個用的最多的可能就是導航條這塊兒 讓導航條居中顯示不隨頁面滾動

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>fixed居中定位</title>
        <style>
        *{margin:0;padding:0}
        .fixedCenter{max-width:980px; height:70px; position:fixed; margin:0 auto; left:0; right:0; background:rgb(67,163,244);}
        </style>
    </head>
    <body>
        <div class="fixedCenter">我是fixed居中定位</div>
    </body>
    </html> 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM