1. flexbox
.parent { display: flex; justify-content: center; align-items: center; width: xxxpx; height: xxxpx; } .child { width: xxxpx; height: xxxpx; }
2. grid
.parent { display: grid; place-items: center; width: xxxpx; height: xxxpx; } .child { width: xxxpx; height: xxxpx; }
3. table-cell
.parent { display: table-cell; width: xxxpx; height: xxxpx; vertical-align: middle; text-align: center; } .child { display: inline-block; width: xxxpx; height: xxxpx; }
4. 定位+translate
.parent { position: relative; width: xxxpx; height: xxxpx; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
5. 定位 + margin(负值)
.parent { position: relative; width: xxxpx; height: xxxpx; } .child { position: absolute; top: 50%; left: 50%; width: wpx; heigth: hpx; margin-left: w/2 px; margin-top: h/2 px; }
6. 定位 + margin(auto)
.parent { position: relative; width: xxxpx; height: xxxpx; } .child { position: absolute; width: xxxpx; height: xxxpx; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }