关于居中

258 阅读1分钟

1、关于元素水平居中、垂直居中、水平垂直居中

1.水平居中
// 给父元素设置
    text-align: center 

// 给父元素设置外间距
    width: 100px;
    height: 100px;
    margin: 0 auto
    
// 给子元素定位并利用css3新属性(记得给父元素设置position: relative)
    position: absolute
    left: 50%
    transfrom: translateX(-50%)
    
// 给子元素定位并利用负margin定位
    width: 100px
    position: absolute
    left: 50%
    maring-left: -50px
    
2.垂直居中
// 将行高设置成盒子的高度
    height: 100px;
    line-height: 100px
    水平垂直居中
// 已知宽高
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto

// 已知宽高利用外边距
position: absolute;
left: 50%;
top: 50%;
margin-top: -50%;
marginleft: -50%

    
// 未知宽高
    position: absolute;
    left: 50%;
    top: 50%;
    transfrom: translate(-50%,-50%)
    
// 利用浮动定位
    display: flex;
    justify-content: center;
    align-items: center