bootstrap 中實現垂直居中的方法有:使用 flexbox 實用程序 align-items-center;使用 margin 實用程序 my-auto;使用 css 定位屬性 position: absolute 和 top: 50%; transform: translatey(-50%);;使用 css 網格屬性 align-content 和 justify-content。
如何在 Bootstrap 中實現垂直居中
在 Bootstrap 中,有幾種方法可以實現垂直居中元素:
1. 使用 flexbox 實用程序
flexbox 實用程序 align-items-center 可以將元素在父容器內垂直居中。
HTML:
<div class="container align-items-center"> <p>垂直居中的文本</p> </div>
登錄后復制
2. 使用 margin
對于較小的元素,可以使用 margin 實用程序 my-auto。它將垂直方向上的 margin 設置為自動,有效地將元素居中。
HTML:
<div class="container"> <p class="my-auto">垂直居中的文本</p> </div>
登錄后復制
3. 使用定位
還可以使用 CSS 定位屬性 position: absolute 和 top: 50%; transform: translateY(-50%); 將元素垂直居中。
HTML:
<div class="container position-absolute" style="top: 50%; transform: translateY(-50%);"> <p>垂直居中的文本</p> </div>
登錄后復制
4. 使用 CSS 網格
CSS 網格屬性 align-content 和 justify-content 可以用來在網格容器內垂直居中元素。
HTML:
<div class="container d-flex align-content-center justify-content-center"> <p>垂直居中的文本</p> </div>
登錄后復制
根據您的具體需求,選擇最適合您的方法。