1 概述
前端工程师都有过这样的痛苦经历,如何让 div 元素居中,所以我决定分享这个教程。
2 使用 absolute
2.1 tailwind
<div class="relative">
<div class="absolute left-1/2 top-1/2 translate-x-[-50%] translate-y-[-50%]"></div>
</div>
2.2 bootstrap
<div class="position-relative">
<div class="position-absolute top-50 start-50 translate-middle"></div>
</div>
3 使用 flex
3.1 tailwind
<div class="flex justify-center items-center">
<div class=""></div>
</div>
3.2 bootstrap
<div class="d-flex justify-content-center align-items-center">
<div class=""></div>
</div>
4 使用 flex + margin
4.1 tailwind
<div class="flex">
<div class="m-auto"></div>
</div>
4.2 bootstrap
<div class="d-flex">
<div class="m-auto"></div>
</div>
5 使用 grid
5.1 tailwind
<div class="grid place-items-center">
<div class=""></div>
</div>
5.2 bootstrap
<div class="d-grid justify-content-center align-items-center">
<div class=""></div>
</div>
6 使用 grid + margin
6.1 tailwind
<div class="grid">
<div class="m-auto"></div>
</div>
6.2 bootstrap
<div class="d-grid">
<div class="m-auto"></div>
</div>