• 几种可以让元素水平垂直居中的方法


    1.负margin法:这是比较常用的方法,在知道元素的宽高的前提下才能使用

     1 <div id="a"></div>
     2 
     3 #a{
     4    height:300px;
     5   width:300px;
     6   position:absolute;
     7   top:50%;
     8   left:50%;
     9   margin-left:-150px;
    10   margin-top:-150px;
    11 }

       注:负margin是个非常有意思的用法,深入了解后会发现他在布局上相当有用。
      优点:代码量少,兼容性好。
      缺点:非响应式方法,内容可能会超出容器。

    2.transform法:

    <div id="a"></div>
    
    #a{ 
        width: 50%;
        height: 20%;
        background: green;
        position: absolute;
        top:50%;
        left: 50%;
        transform:translate(-50%, -50%);
            -webkit-transform:translate(-50%, -50%);
            -ms-transform:translate(-50%, -50%);
    }

      优点:代码量少;宽高可变,相应式布局
      缺点:不支持IE8,可能需要带供应商前缀

    3.Flexbox法

    <div class="vertical-container">
        <div class="a"></div>
    </div>
    
    .vertical-container {
      height: 300px;
      width: 300px;
      background: #ccc;
      display: -webkit-flex;
      display: flex;
      -webkit-align-items: center;
                  align-items: center;
      -webkit-justify-content: center;
                  justify-content: center;
    }
    .a{
       width: 200px;
       height: 200px;
       background: green;
    }

    注:Flexbox的用法远不止如此,在布局上还有很多有趣的用法。

    4.“完全水平垂直居中”:必须要设置元素的高度,图片自身有高度的可以不设。

    <div id="a"></div>
    
    #a{  
        width: 200px;
        height: 200px;
        background: red;
        margin:auto;
        position: absolute;
        top:0;left:0;right: 0;bottom: 0;
    }

    优点:代码量少,兼容性好

     更多博客,前关注我的个人小站:http://eidolons-ailidan.rhcloud.com/

  • 相关阅读:
    TSQL语句 创建表
    数据库设计
    WampServer
    表单验证之相等验证
    表单验证之非空验证
    遗忘的知识点
    JavaScript函数
    JS之数组
    JS的分支与循环语句
    JavaScript基础语法要点总结
  • 原文地址:https://www.cnblogs.com/dan-dan/p/4771614.html
Copyright © 2020-2023  润新知