首頁  >  文章  >  web前端  >  css div如何居中顯示

css div如何居中顯示

coldplay.xixi
coldplay.xixi原創
2021-03-11 14:12:2052525瀏覽

css div居中顯示的方法:1、使用absolute絕對定位,程式碼為【

absolute居中定位】;2、使用translate定位;3、使用margin居中定位;4、使用fixed的居中定位。

css div如何居中顯示

本教學操作環境:windows7系統、css3版,DELL G3電腦。

css div居中顯示的方法:

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

<html>
    <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>我是absolute居中定位</div>
    </body>
    </html>

2、translate定位這是css3 transform的屬性透過自身的偏移來定位而且他有個極大的好處不需要知道div的寬高度就像js裡的this self一樣可以將寬高度設為百分比IE browser

<!doctype html>
    <html>
    <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>我是translate居中定位</div>
    </body>
    </html>

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

<!doctype html>
    <html>
    <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>我是margin居中定位</div>
    </body>
    </html>

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

<!doctype html>
    <html>
    <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>我是fixed居中定位</div>
    </body>
    </html>

相關教學推薦:CSS影片教學

以上是css div如何居中顯示的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn