利用 Bootstrap 4/5 实现元素居中

来源:undefined 2025-02-12 13:04:54 1012

在 Bootstrap 4/5 中,水平居中元素可以使用 text-center 类或 mx-auto 类,垂直居中元素在 Bootstrap 4 中可以使用 d-flex 和 align-items-center 类或使用 margin: auto; 样式,而在 Bootstrap 5 中可以使用 d-grid 和 align-content-center 类或使用 position: absolute; 和 top: 50%; left: 50%; 样式。

使用 Bootstrap 4/5 实现元素居中

在 Bootstrap 4/5 中,使用以下方法可以将元素居中:

水平居中

使用 text-center 类:
...
使用 mx-auto 类(Bootstrap 5):
...

垂直居中

Bootstrap 4:

使用 d-flex 和 align-items-center 类:
...

Bootstrap 5:

使用 d-grid 和 align-content-center 类:
...

使用垂直居中的其他方法

使用 margin: auto; 样式:
...
使用 position: absolute; 和 top: 50%; left: 50%; 样式:
...

示例:

水平居中:

1

2

3

<div class="text-center">

<h1>标题</h1>

</div>

登录后复制

1

2

3

<div class="mx-auto">

<button class="btn btn-primary">按钮</button>

</div>

登录后复制

垂直居中:

Bootstrap 4:

1

2

3

<div class="d-flex align-items-center">

<h1>标题</h1>

</div>

登录后复制

1

2

3

<div class="d-grid align-content-center">

<button class="btn btn-primary">按钮</button>

</div>

登录后复制

以上就是利用 Bootstrap 4/5 实现元素居中的详细内容,更多请关注php中文网其它相关文章!

最新文章