css3种不知道宽高的情况下水平垂直居中的方法

第一种:display:table-cell

 

组合使用display:table-cell和vertical-align、text-align,使父元素内的所有行内元素水平垂直居中(内部div设置display:inline-block即可)。

这在子元素不确定宽高和数量时,特别实用!
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 6     <title>Demo001_displayTable</title>
 7     <style>
 8         /*** table-cell middle center组合使用 ***/
 9         .cell {
10             display: table-cell;
11             vertical-align: middle;
12             text-align: center;
13             width: 240px;
14             height: 180px;
15             border:1px solid #666;
16         }
17     </style>
18 </head>
19 <body>
20     <div class="cell">
21         <p>我爱你</p>
22     </div>
23     <div class="cell">
24         <p>我爱你</p><p>亲爱的中国</p>
25     </div>
26     <div class="cell">
27         <p>我爱你</p><p>亲爱的中国</p><div style="width:100px;height:50px;border:1px solid #ccc;display:inline-block">div(inline-block)</div>
28     </div>
29 </body>
30 </html>
View Code

 第二种 transform:translate(-50%,-50%)

translate()函数是css3的新特性,在不知道自身宽高的情况下,可以利用它来进行水平垂直居中。

当使用:top:50%, left:50%,是以左上角为原点,故不处于中心位置。

translate(-50%, -50%)作用是,往上(X轴),左(Y轴)移动自身长度的50%,以使其居于中心位置。
与负margin-left和margin-top实现居中不同的是,margin-left必须知道自身的宽高,而translate可以在不知道宽高的情况下进行居中,
tranlate()函数中的百分比是相对于自身宽高的百分比,所以能进行居中

 

.content {    
   padding:10px;
    background:green;
    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%);
}

 

第三种用弹性布局实现垂直左右居中

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Document</title>
 6   <style type="text/css">
 7   *{
 8       margin: 0;
 9       padding: 0;
10   }  
11   .wrap{
12       width: 100px;
13       height: 100px;      
14       border: 1px solid #000;
15       margin: 3.125em auto;      
16       display: flex;
17       justify-content: center;
18       align-items: center;
19  
20   }
21   .in{      
22       width: 10px;
23       height: 10px;
24       background: #000;
25       border-radius: 50%;
26   }
27   </style>
28 </head>
29 <body>  
30   <div class="wrap">
31       <div class="in"></div>
32   </div>
33 </body>
34 </html>
View Code
display:flex; 设置.wrap为弹性布局

justify-content:center;定义项目在主轴(水平方向)上居中对齐

align-items:center;定义项目在交叉轴(垂直方向)上居中对齐

 

posted @ 2019-07-01 15:49  本木木  阅读(8959)  评论(0编辑  收藏  举报