css盒子垂直水平居中常用的几种方法

方法一:flex布局

main
.container{ display:flex; justify-content:center; align-items: center; width:300px; height:300px; border: 5px solid #ccc; } .main{ background: red; }

方法二: flex布局 + margin

main
.container{ display:flex; width:300px; height:300px; border: 5px solid #ccc; } .main{ margin: auto; background: red; }

方法三: 相对定位

main
.container{ position: relative; width:300px; height:300px; border: 5px solid #ccc; } .main{ position: absolute; left: 50%; top: 50%; transforn: translate(-50%,-50%); background: red; }

方法四: 利用 display:table-cell

main
.container{ display: table-cell; text-align: center; vertical-align: middle; width:300px; height:300px; border: 5px solid #ccc; } .main{ display: inline-block; background: red; }

你可能感兴趣的:(css,css3,前端)