css中各种居中的奇技淫巧总结

css中各种居中的奇技淫巧总结

  第一种,在固定布局中比较常用的技巧设置container的margin:0 auto;

  第二种(从布局中入手)

  css

 .outer{
     height:200px;
     width:200px;
     background:gray;
     position:relative;
 }
 .inner{
     width:100px;
     height:100px;
     top:50%;
     left:50%;
     background:black;
     position:absolute;
     margin-left:-50px;
     margin-top:-50px;
 }

 html

 <div class="outer">
     <div class="inner"></div>
   </div>

  效果

第三种;单行文字居中

.info{
     /*
     1.前提设置固定的高
     2.只能有一段文字
     */
     height:100px;
     line-height:100px;
     border:1px solid blue;
     text-align:center; /*如要要垂直居中的话就加上它把*/
 }

第四种

 table布局

<table style="width: 100%;">
  <tr>
     <td style="text-align: center; vertical-align: middle;">
          这个也是可以居中的滴呀
     </td>
  </tr>
</table>

也可以改成是我们的div

css:

 .outer{
     display:table;
     width:100%;
 }
 .inner{
     display:table-cell;
     text-align:center;
     vertical-align:middle;
     /*而且:
       水平和垂直方向都居中了滴呀
     */
 }

html

 <div class="outer">
   <div class="inner">居中</div>
 </div>

第五种:translate

css

 .center{
     position:fixed;
     top:50%;
     left:50%;
     background:#000;
     width:50%;
     height:50%;
     -webkit-transform:translateX(-50%) translateY(-50%); 
 }

 附带兼容性写法:

-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

html

<body>
  <div class="center"></div>
</body>

第六种:flex布局

 body{
     display:flex;/*flex布局方式*/
     display:-webkit-flex;
     align-items:center; /*水平方向上*/
     justify-content:center;/*垂直方向上的*/
      
 }
 .info{
     height:200px;
     width:200px;
     background:gray;
 }

 

posted @ 2016-03-28 17:51  咕-咚  阅读(561)  评论(1编辑  收藏  举报