首页 > 开发学院  >  前端  > 

前端

css水平居中元素的宽度探究

时间:2023-05-26 19:24:10阅读数:0

水平居中还是比较容易的,先看子元素是固定宽度还是宽度未知。

1、固定宽度这种方式是绝对定位居中,除了使用margin,还可以使用transform。

(注意浏览器兼容性,只适用于 ie9+,移动开发请忽略)

        .container{            width: 300px;            height: 200px;            background: pink;            position: relative;        }        .inner{            width: 100px;            height: 50px;            position: absolute;            top: 50%;            left: 50%;            margin-top: -25px;            margin-left: -50px;            background: #fff;            text-align: center;        }

2、宽度未知将子元素设置为行内元素,然后父元素设置text-align: center。

       .container{            width: 300px;            height: 200px;            background: pink;            position: relative;            text-align: center;        }        .inner{            display: inline-block;         }