css居中几种方式

前端经常遇到对div进行水平垂直居中问题,网上也有很多解决方式,但是我们需要根据不同的前提条件和兼容性等来选择合适的方案

方案1、position+margin:auto (未知元素宽高)

      <style>
            .wrap {
                position:relative;
                height:500px;
            }
            
            .inner {
                width: 100px;
                height: 100px;
                background: pink;
            }
            
            .center {
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                margin: auto;
            }
        </style>

        <div class="wrap">
            <div class="inner center">love</div>
        </div>
          

方案2、table-cell (未知元素宽高)

         <style>
            .content {
                display: table-cell;
                vertical-align: middle;
                text-align: center;
                width: 300px;
                height: 300px;
                background-color: cadetblue;
            }
            
            .inner {
                display: inline-block;
                width: 50px;
                height: 50px;
                line-height: 50px;
                background-color: pink;
            }
        </style>
        <div class="content">
            <div class="inner"> 111 </div>
        </div>

方案3、position+transform(css3存在兼容性问题) (未知元素宽高)

       <style>
            .wrap {
                position:relative;
                width:300px;
                height:300px;
                border:1px solid red;
            }
            
            .inner {
                width: 100px;
                height: 100px;
                background: pink;
            }
            
            .center {
                position: absolute;
                left:50%;
                top:50%;
                transform: translate(-50%,-50%);
            }
        </style>

        <div class="wrap">
            <div class="inner center"></div>
        </div>

或position+calc()(css3存在兼容性问题) (已知元素宽高)

         .center {
                position: absolute;
                top: calc(50% - 50px);
                left: calc(50% - 50px);
         }

或position+margin (已知元素宽高)

         .center {
                position: absolute;
                left:50%;
                top:50%;
                margin-left:-50px;
                margin-top:-50px;
         }

方案4、flex布局(低版本浏览器不兼容) (未知元素宽高)

         <style>
            .wrap {
                display: flex;
                justify-content: center;
                align-items: center;
                height:500px;
            }
            
            .inner {
                width: 100px;
                height: 100px;
                background: pink;
            }
            
        </style>

        <div class="wrap">
            <div class="inner">love</div>
        </div>

参考:CSS水平垂直居中常见方法总结

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容