如何使一个盒子水平垂直居中
-
父元素使用相对定位,子元素使用绝对定位,上下左右都设为0;设置margin:auto
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* 定位 */ .box { position: relative; } .box1{ position: absolute; left:0; right: 0; top:0; bottom: 0; margin:auto } </style> </head> <body> <div class="box" style="width:500px;height:500px;background-color: greenyellow;"> <div class="box1" style="width:200px;height:200px;background-color: aqua;"></div> </div> </body> </html>
-
flex布局。使用弹性盒子的时候需要给父级设置display:flex;在父元素上设置水平与垂直方向上的排列方式即可;
该方法不需要设置子元素。
.box {
display: flex;
justify-content: center;
align-items: center;
}
- 使用子绝父相的定位方法,无需知道盒子的高度
/* 定位+位移 */
.box {
position: relative;
}
.box1 {
position: absolute;
left: 50%;
/* 父盒子宽度的50% */
top: 50%;
/* 父盒子高度的50% */
transform: translate(-50%, -50%);
/* 子盒子自身宽高的50% */
}