Bootstrap 5中div内<p>标签居中问题求助
Bootstrap 5 中div内
标签居中问题解决方法
你的代码里,包裹
的div已经设置了justify-content-center和align-items-center,但没达到居中效果主要有两个原因:
是块级元素,默认宽度占满父容器,flex容器的`justify-content-center`对占满宽度的子元素无效
文本默认左对齐,即使容器布局没问题,文本也不会自动居中
给出三种可行的解决方法:
方法1:给
添加文本居中类
直接让
内的文本水平居中,这是最直接的方式:
<div class="navbar d-flex flex-grow-1 justify-content-end align-items-end mb-3 d-none d-sm-flex"> <div class="d-flex align-items-center justify-content-center text-white me-2 fw-bold"> <p class="text-center">THIS NEEDS TO BE CENTERED</p> </div> <a type="button" class="btn btn-gold" href="">Booking!</a> </div>
方法2:限制
宽度,让flex布局生效
给
添加w-auto类,让它宽度自适应内容,这样父容器的justify-content-center就能让
在容器内水平居中:
<div class="navbar d-flex flex-grow-1 justify-content-end align-items-end mb-3 d-none d-sm-flex"> <div class="d-flex align-items-center justify-content-center text-white me-2 fw-bold"> <p class="w-auto">THIS NEEDS TO BE CENTERED</p> </div> <a type="button" class="btn btn-gold" href="">Booking!</a> </div>
方法3:简化结构,减少嵌套
去掉中间的div,直接把样式加到
上,同时清除
默认的下边距避免垂直布局偏差:
<div class="navbar d-flex flex-grow-1 justify-content-end align-items-end mb-3 d-none d-sm-flex"> <p class="text-white me-2 fw-bold mb-0 text-center">THIS NEEDS TO BE CENTERED</p> <a type="button" class="btn btn-gold" href="">Booking!</a> </div>
内容的提问来源于stack exchange,提问作者RenTi
相关产品推荐
相关产品推荐

