方法一:
通过固定定位,使元素居中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="">
<style>
.v1 {
width: 200px;
height: 200px;
background-color: royalblue;
position: relative;
}
.v2 {
width: 100px;
height: 100px;
background-color: salmon;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<div class="v1">
<div class="v2">
</div>
</div>
<body>
</body>
</html>
运行结果:
方法二:
通过flex布局,使元素居中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="">
<style>
/* 方法二:通过flex布局 */
.v3 {
width: 200px;
height: 200px;
background-color: sienna;
display: flex;
justify-content: center;
align-items: center;
}
.v4 {
width: 100px;
height: 100px;
background-color: silver;
}
</style>
</head>
<div class="v3">
<div class="v4"></div>
</div>
<body>
</body>
</html>
运行结果: