Navbar图片布局、文字居中及底部分割线实现技术问询
问题
我需要在navbar顶部放置3张图片,每张图片下方居中显示对应文字。目前代码里的3张图看似均匀分布,但不确定是否需要代码明确控制位置;另外当前底部文字显示在最后一张图右侧,不符合“图片下方居中”的预期;最后要在文字下方加一条实线,分隔navbar和网站其他内容。现有代码如下:
<nav class="navbar navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="/docs/5.0/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24" class="d-inline-block align-text-top"> Bootstrap_Left </a> <a class="navbar-brand" href="#"> <img src="/docs/5.0/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24" class="d-inline-block align-text-top"> Bootstrap_center </a> <a class="navbar-brand" href="#"> <img src="/docs/5.0/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24" class="d-inline-block align-text-top"> Bootstrap_right </a> <div align="center">My Site<br>Po Box 12, My State</div> </div> </nav>
解决方法
1. 确保图片稳定均匀分布
当前的均匀分布是Bootstrap flex布局的默认表现,属于巧合。要让布局稳定,给图片所在的container-fluid添加d-flex justify-content-around类,强制三个图片容器均匀分配空间。
2. 实现图片下方居中文字
把每个navbar-brand改成垂直布局:添加d-flex flex-column align-items-center类,让图片和文字上下排列,文字自动居中在图片下方。同时用mt-1给文字添加上边距,避免和图片紧贴。
3. 底部文字居中+添加分隔线
将底部文字容器移出图片所在的container-fluid,作为navbar的独立子元素,用text-center实现居中;给navbar添加border-bottom border-dark类,直接在底部生成实线分隔。
修改后的完整代码:
<nav class="navbar navbar-light bg-light border-bottom border-dark"> <div class="container-fluid d-flex justify-content-around"> <a class="navbar-brand d-flex flex-column align-items-center" href="#"> <img src="/docs/5.0/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24"> <span class="mt-1">Bootstrap_Left</span> </a> <a class="navbar-brand d-flex flex-column align-items-center" href="#"> <img src="/docs/5.0/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24"> <span class="mt-1">Bootstrap_center</span> </a> <a class="navbar-brand d-flex flex-column align-items-center" href="#"> <img src="/docs/5.0/assets/brand/bootstrap-logo.svg" alt="" width="30" height="24"> <span class="mt-1">Bootstrap_right</span> </a> </div> <div class="container-fluid text-center py-2"> My Site<br>Po Box 12, My State </div> </nav>
额外说明
- 如果想调整分隔线的样式,可以修改
border-bottom的类,比如border-bottom-3加粗线条,border-primary改变颜色。 justify-content-around可以换成justify-content-between,前者会在容器两侧留空,后者会让第一个和最后一个图片贴紧容器边缘,根据需求选择。
内容的提问来源于stack exchange,提问作者jack
相关产品推荐
相关产品推荐

