一、利用margin:auto
HTML代码:
<body>
<div id="app">
<div class="center">
</div>
</div>
</body>
css代码:
#app {
background-color: #eee;
width: 200px;
height: 200px;
position: relative;
}
.center {
width: 50px;
height: 50px;
background-color: forestgreen;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
二、利用display:flex
html代码:
<body>
<div class="div4">
<div class="center">
</div>
</div>
</body>
.div4 {
background-color: #eee;
width: 200px;
height: 200px;
position: relative;
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
}
.div4 .center {
width: 50px;
height: 50px;
background-color: rgb(240, 248, 166);
}
三、利用position: absolute
html部分:
<div class="div2">
<div class="center">
</div>
</div>
css部分:
.div2 {
background-color: #eee;
width: 200px;
height: 200px;
position: relative;
margin-top: 20px;
}
.center {
width: 50px;
height: 50px;
background-color: rgb(34, 71, 139);
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}