水平垂直居中方式
<div class="father">
<div class="son">温情key</div>
</div>
* {
margin: 0;
padding: 0;
}
1. flex
给父元素设置
display: flex;
align-items: center; // 水平居中
justify-content: center; // 垂直居中
已知宽高和未知宽高都可以实现水平垂直居中
.father {
width: 300px;
height: 300px;
background: red;
display: flex;
align-items: center;
justify-content: center;
}
已知宽高
.son {
width: 100px;
height: 100px;
background: aqua;
}
未知宽高
<div class="father">
<div class="son">温情key</div>
</div>
.son {
background: aqua;
}
2. position + translate
父元素:position: relative;
子元素:position: absolute;
left: 50%;
top: 50%;
transform: translate(width / 2, height / 2);
.father {
width: 300px;
height: 300px;
background: red;
position: relative;
}
已知宽高
.son {
position: absolute;
width: 100px;
height: 100px;
background: aqua;
top: 50%;
left: 50%;
transform: translate(-50px, -50px); // 也可以用-50%
}
未知宽高
父元素:position: relative;
子元素:position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
.father {
width: 400px;
height: 300px;
background: red;
position: relative;
}
.son {
background: aqua;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3. positon + 负margin
已知宽高
父元素设置 position: relative;
子元素: position:absolute;
left: 50%;
top: 50%;
margin-left: - (width / 2);
margin-top: - (height / 2);
.father {
width: 400px;
height: 400px;
background: red;
position: relative;
}
.son {
position: absolute;
background: aqua;
width: 100px;
height: 100px;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
4. position + margin: auto
已知宽高
父元素设置 position:relative;
子元素设置 position:absolute;
left: 0;
bottom: 0;
right: 0;
top: 0;
margin: auto;
.father {
width: 400px;
height: 400px;
background: red;
position: relative;
}
.son {
position: absolute;
background: aqua;
width: 100px;
height: 100px;
left: 0;
bottom: 0;
right: 0;
top: 0;
margin: auto;
}
5. grid
父元素添加 display:grid;
子元素添加 align-self: center;
justify-self: center;
有无宽高都适用
.father {
width: 400px;
height: 400px;
background: red;
display: grid;
}
.son {
background: aqua;
align-self: center;
justify-self: center;
}