元素居中几种写法

Posted 心悲动我神

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了元素居中几种写法相关的知识,希望对你有一定的参考价值。

    /**
         * 兼容所有浏览器,不兼容移动端
         * 元素必须有固定宽度高度
         */
        .box{
            width: 320px;
            height: 320px;
            background: red;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -160px;
            margin-left: -160px;
        }


/**
         * 绝对居中法
         * 兼容ie8以上浏览器
         * 元素必须有固定宽度高度,可以百分比
         */
        .box{
            width: 320px;
            height: 320px;
            background: red;
            margin: auto;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
        }


/**
         * transform css3特性 平移
         * 兼容ie9以上版本浏览器,适合移动端元素居中
         * 元素无需固定宽高,宽高可以设置百分比
         */
        .box{
            width: 320px;
            height: 320px;
            background: red;
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%, -50%);
        }


/**
         * flex弹性盒模型居中法
         * 兼容ie10以上浏览器
         * 元素无需固定宽高
         * 灵活
         */
        .wrap{
            width: 880px;
            height: 550px;
            border: 1px solid  red;
            margin: 10px auto;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .box{
            width: 400px;
            height: 200px;
            background: green;
        }

 

以上是关于元素居中几种写法的主要内容,如果未能解决你的问题,请参考以下文章

CSS代码片段

CSS元素垂直居中的几种方法

CSS元素居中的几种方法

元素居中的几种方法

居中元素的几种方法

居中元素的几种方法