zoukankan      html  css  js  c++  java
  • 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=" 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;
     }
  • 相关阅读:
    css深入理解vertical-align
    css深入理解之overflow
    深入理解CSS中的margin
    深入理解line-height
    深入理解css之float
    javascript正则表达式
    深入理解css之absolute
    _splitpath / _wsplitpath 将绝对路径分割为盘符、路径、文件名、扩展名。
    cocos2d-x环境的搭建之xcode-本人亲历成功搭建!
    lua语法
  • 原文地址:https://www.cnblogs.com/mc67/p/5329966.html
Copyright © 2011-2022 走看看