第一種:將元素通過display:inline-block轉化為行內塊元素居中,例如:
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;text-align:center;font-size:0;}
.box .zi{width:120px;height:100px;background:#0f0;display:inline-block;vertical-align:middle;}
.box:after{content:"";display:inline-block;height:100%;vertical-align:middle;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第二種:用定位的方式將之移動到位置,例如:
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.box .zi{width:120px;height:100px;background:#0f0;
position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第三種:類似第二中只不過通過百分比調整位置,例如
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.box .zi{width:120px;height:100px;background:#0f0;position:absolute;left:50%;top:50%;margin:-50px 0 0 -60px;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第四種:類似第三種,但是在調整回到中心位置時使用transform:translate( ,)進行調整,例如
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.box .zi{width:120px;height:100px;background:#0f0;
position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
第五種:使用彈性盒(display:flex),例如
<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;display:flex;justify-content:center;align-items:center;}
.box .zi{width:120px;height:100px;background:#0f0;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
以上最常用的五種方式,除此之外還有很多方式,根據每個人的習慣不同個人用法不同,如有疑問請諒解。