一、四种方法让子元素在父元素中水平垂直居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0;padding: 0;}
#box1{
width: 500px;height: 400px;background: red;margin: 50px auto;
position: relative;
}
#box1 .divbox1{
width: 300px;height: 200px;background: green;
position: absolute;left: 50%;top: 50%;margin-left: -150px;margin-top: -100px;
}
#box2{
width: 500px;height: 400px;background: red;margin: 50px auto;
position: relative;
}
#box2 .divbox2{
width: 300px;height: 200px;background: green;
position: absolute;left: 0;top: 0;right: 0;bottom: 0;margin: auto;
}
#box3{
width: 500px;height: 400px;background: red;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
}
#box3 .divbox3{
width: 300px;height: 200px;background: green;
}
#box4{
width: 500px;height: 400px;background: red;margin: 50px auto;
position: relative;
}
#box4 .divbox4{
width: 300px;height: 200px;background: green;
position: absolute;left: 50%;top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div id="box1">
<div class="divbox1"></div>
</div>
<div id="box2">
<div class="divbox2"></div>
</div>
<div id="box3">
<div class="divbox3"></div>
</div>
<div id="box4">
<div class="divbox4"></div>
</div>
</body>
</html>