实现元素水平垂直居中效果
效果图如下
通过 flex 方式实现
html
<!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>
.container {
position: relative;
width: 150px;
height: 150px;
background-color: #5cd8a2;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 50px;
height: 50px;
background-color: #ffcb3d;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
通过 margin 和 absolute 实现
html
<!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>
.container {
position: relative;
width: 150px;
height: 150px;
background-color: #5cd8a2;
}
.box {
margin: auto;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 50px;
height: 50px;
background-color: #ffcb3d;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>