三種絕對位置元素的水平垂直置中的辦法

來源:互聯網
上載者:User
這次給大家帶來三種絕對位置元素的水平垂直置中的辦法,實現絕對位置元素水平垂直居的注意事項有哪些,下面就是實戰案例,一起來看一下。

1.css實現置中

缺點:需要提前知道元素的寬度和高度。

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        .box{            width: 600px;             height: 400px;            position: absolute;             left: 50%; top: 50%;            border:1px solid #000;            background:red;            margin-top: -200px;    /* 高度的一半 */            margin-left: -300px;    /* 寬度的一半 */        }    </style></head><body>    <p class="box">    </p></body></html>

2、css3實現水平垂直置中

注意:無論元素的尺寸是多少,都可以置中。不過IE8以上才相容這種寫法,移動端可忽略。

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        .box{            width: 600px;             height: 400px;            position: absolute;             left: 50%;            top: 50%;            border:1px solid #000;            background:red;            transform: translate(-50%, -50%);    /* 50%為自身尺寸的一半 */        }    </style></head><body>    <p class="box">    </p></body></html>

3、margin:auto實現置中

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        .box{            width: 600px;             height: 400px;            position: absolute;             left: 0;            top: 0;             right: 0;             bottom: 0;            border:1px solid #000;            background:red;            margin: auto;    /* 有了這個就自動置中了 */        }    </style></head><body>    <p class="box">    </p></body></html>

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

動態載入css詳解

CSS3實現扇形動畫菜單流程詳解

CSS3的webkit-tap-highlight-color屬性如何使用

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.