22.垂直上下居中的方法


一、盒子沒有固定的寬和高

方案1、Transforms 變形

這是最簡單的方法,不僅能實現絕對居中同樣的效果,也支持聯合可變高度方式使用。內容塊定義transform: translate(-50%,-50%)  必須加上

top: 50%; left: 50%;

優點:

1.      內容可變高度

2.      代碼量少

缺點:

1.      IE8不支持

2.      屬性需要寫瀏覽器廠商前綴

3.      可能干擾其他transform效果

4.      某些情形下會出現文本或元素邊界渲染模糊的現象

<div class="wrapper">我不知道我的寬度和高是多少,我要實現水平垂直居中。</div>
復制代碼
復制代碼
.wrapper {
            padding: 20px;
            background: orange;
            color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            border-radius: 5px;
            -webkit-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%); }
復制代碼
復制代碼

方案二2、在父級元素上面加上上面3句話,就可以實現子元素水平垂直居中。

<div class="wrapper">
        我不知道我的寬度和高是多少,我要實現水平垂直居中。
</div>
復制代碼
復制代碼
.wrapper {
            width: 500px;
            height: 300px;
            background: orange;
            color: #fff;
            /*只需要在父元素上加這三句*/
            justify-content: center; /*子元素水平居中*/
            align-items: center; /*子元素垂直居中*/
            display: -webkit-flex;
        }
復制代碼
復制代碼

 

二、盒子有固定的寬和高

方案1、margin 負間距

此方案代碼關鍵點:1.必需知道該div的寬度和高度,

                2.然后設置位置為絕對位置,

           3.距離頁面窗口左邊框和上邊框的距離設置為50%,這個50%就是指頁面窗口的寬度和高度的50%,

         4.最后將該div分別左移和上移,左移和上移的大小就是該DIV寬度和高度的一半。

<div class="wrapper">我知道我的寬度和高是多少,我要實現水平垂直居中。</div>
復制代碼
復制代碼
.wrapper {
            width: 400px;
            height: 18px;
            padding: 20px;
            background: orange;
            color: #fff;
            position: absolute;
            top:50%;
            left:50%;
            margin-top: -9px;
            margin-left: -200px;
        }
復制代碼
復制代碼

方案2、margin:auto實現絕對定位元素的居中(該方法兼容ie8以上瀏覽器)

此方案代碼關鍵點:1、上下左右均0位置定位;

                         2、margin: auto;

<div class="wrapper">我不知道我的寬度和高是多少,我要實現水平垂直居中。</div>
復制代碼
復制代碼
.wrapper {
            width: 400px;
            height: 18px;
            padding:20px;
            background: orange;
            color: #fff;
        position</span>:<span style="color: #0000ff;"> absolute</span>;<span style="color: #ff0000;"> left</span>:<span style="color: #0000ff;">0</span>;<span style="color: #ff0000;"> right</span>:<span style="color: #0000ff;">0</span>;<span style="color: #ff0000;"> top</span>:<span style="color: #0000ff;"> 0</span>;<span style="color: #ff0000;"> bottom</span>:<span style="color: #0000ff;"> 0</span>;<span style="color: #ff0000;"> margin</span>:<span style="color: #0000ff;"> auto</span>; }</pre>


免責聲明!

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



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