div 垂直居中,水平居中的各个方法

289 阅读1分钟

水平居中

  1. 定宽,定高
div{
    width:100px;
    height:100px;
    background:blue;
    margin: 0 auto;
}
  1. 不定宽,不定高

父元素设置
div{
    display:flex
    justify-content:center
}

垂直水平居中

定宽,定高

子元素设置:
div{
    position:absolute;
    width:100px;
    height:100px;
    top:50%;
    left:50%;
    margin-top:-50px;
    margin-left:-50px;
    

}

不定高宽


父元素设置 .parent {
    text-aligin:center;
}
子元素设置 .child{
    display:inline - block;
    vertical-align:middle;
    
}

2:
父元素.A{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    
}
子元素.B{
    position:absolute;
    top:0;left:0;
    right:0;bottom:0;
    margin:auto
    
}

使用flex 布局