CSS - 不定宽高的水平垂直居中

废话不多说,直接上代码~~

1 . 使用 transform: translate(-50%,-50%) 实现居中。

    居中效果如图。

 

 1 <style>
 2             body { background: #000; }
 3             .wrapper { width: 200px;height: 300px;
 4                        position: absolute;top:50%;left:50%;
 5                        -webkit-transform:translate(-50%,-50%);
 6                        background: lightblue; }
 7         </style>
 8         
 9         <div class="wrapper">
10             <p>我是第一行</p>
11             <p>我是第一行</p>
12             <p>我是第一行</p>
13             <p>我是第一行</p>
14         </div>

 

2 . 使用 flexbox 实现不定宽高的水平垂直居中。

  效果如图。

 

<style>
            body { background: #000; }
            /* flexbox 版 不定宽高的水平垂直居中 */    
            .wrapper { justify-content: center;  /* 子元素水平居中 */
                      align-items: center;       /* 子元素垂直居中 */
                      display:-webkit-flex;
                      width: 500px;height: 300px;
                      background: lightblue; }    
        </style>
        
        <div class="wrapper">
            <p>我是第一行</p>
            <p>我是第一行</p>
            <p>我是第一行</p>
            <p>我是第一行</p>
        </div>

 

    

posted @ 2016-06-14 22:29  温柔的敲敲敲  阅读(134)  评论(0)    收藏  举报