O primeiro: posicionamento absoluto + margem negativa
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style>
.parent{
width: 400px;
height: 400px;
margin: 100px auto auto 600px;
border: 1px solid #ccc;
position: relative;
}
.box{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="parent">
<div class="box"></div>
</div>
</body>
</html>
efeito:
Observe que, se for relativo à janela do navegador, posicione: relativo;
A segunda: use a transformação do atributo css3
.box{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);//往上(x轴),左(y轴)移动自身长宽的 50%,使其居于中心位置
}
O terceiro tipo: use layout flexível
Quarto: Use table-cell
Dê uma olhada no efeito:
Observe que eu defino a margem, mas o elemento pai não reflete isso. Isso ocorre porque o table-cell
elemento configurado margin
não responde ao valor, mas pode ser padding
configurado em resposta e, ao usar este atributo, não o use float属性和position:absolute;
junto.