目录
我们在用css布局嵌套盒子时,肯定遇到过让盒子垂直水平居中的问题,今天我就简单总结几个常见的垂直水平居中的方式,大家还有什么比较好的方式也可以留言哦。
首先,创建两个盒子,box盒子在div盒子面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 100px;
height: 100px;
background: #55a532;
margin: 0 auto;
}
.box{
width: 10px;
height: 10px;
background: #3fefef;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div class="box"></div>
</div>
</body>
</html>
盒子样式如图
方式一
利用文本居中和行高来实现
先用display:inline-block将子盒子转换为行内块,然后用文本水平居中和行高让box盒子水平垂直居中。由于对齐方式的不同,给box盒子添加vertical-align: middle;
div{
width: 100px;
height: 100px;
background: #55a532;
margin: 0 auto;
text-align: center;
line-height: 100px;
}
.box{
width: 10px;
height: 10px;
background: #3fefef;
display: inline-block;
vertical-align: middle;
}
方式二
利用绝对定位和外边距来实现
先为父盒子设置相对定位,再为子盒子设置绝对定位,且绝对定位的四个方向的值都为0,然后将外边距margin设为auto。
div{
width: 100px;
height: 100px;
background: #55a532;
margin: 0 auto;
position: relative;
}
.box{
width: 10px;
height: 10px;
background: #3fefef;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
此外,还可以在设置绝对定位的前提下,用位移transform: translate来实现居中
方式三
先在父元素中添加display:flex;,然后在父元素中添加主轴居中(justify-content:center)和侧轴居中(align-item:center)即可
div{
width: 100px;
height: 100px;
background: #55a532;
margin: 0 auto;
dispaly:flex;
justify-content:center;
align-item:center
}
.box{
width: 10px;
height: 10px;
background: #3fefef;
}