以下展示三種置中方法 :
<div class="method-container">
<div class="method-title">Flexbox</div>
<div class="box">
<div class="dot"></div>
</div>
</div>
<div class="method-container">
<div class="method-title">Absolute </div>
<div class="box box-absolute">
<div class="dot"></div>
</div>
</div>
<div class="method-container">
<div class="method-title">Margin 0 Auto</div>
<div class="box" style="position: relative; margin: 0 auto;">
<div class="dot" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></div>
</div>
</div>
body {
display: flex;
justify-content: space-around;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.method-container {
display: flex;
flex-direction: column;
align-items: center;
}
.method-title {
margin-bottom: 10px;
font-weight: bold;
}
.box {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
border: 1px solid red;
margin-bottom: 20px;
}
.box-absolute {
position: relative;
}
.box-absolute div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.dot {
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
}