简体   繁体   English

在 Bootstrap4 的导航栏中居中文本的问题

[英]Having problem with centering text in a Navbar in Bootstrap4

I created a navbar in Bootstrap, and I would like to center the content in it.我在 Bootstrap 中创建了一个导航栏,我想将其中的内容居中。

<nav class="navbar navbar-light bg-light">
  <div class="container"> 
    <span class="navbar-brand mb-0 h1">
      <i class="bi bi-list-check"></i>
      Nav Text
    </span> 
  </div>
</nav>

In a CSS file, I tried several things, but nothing works.在 CSS 文件中,我尝试了几件事,但没有任何效果。 For example flex:例如弹性:

.navbar { 
  display: flex;
  justify-content: center;
}

It just seems that nothing influences the navbar.似乎没有什么会影响导航栏。 I have no idea why.我不知道为什么。

Your "Nav Text" text is inside a div element that has the class .container .您的“导航文本”文本位于具有.container类的div元素内。 This div is inside another nav element that has the class navbar that is a flexbox container.这个div位于另一个nav元素内,该元素具有作为flexbox容器的类navbar The default styles (boostrap you are using) justifies content to the start of the flexbox ( justify-content:flex-start ).默认样式(您正在使用的 boostrap)将内容对齐到 flexbox 的开头( justify-content:flex-start )。 You have to override this default styling using the value center for justify-content .您必须使用justify-content的值center覆盖此默认样式。 Also, you have to use !important to override the default style.此外,您必须使用!important来覆盖默认样式。 Please see this screenshot.请看这个截图。

https://prnt.sc/1xfrtcp https://prnt.sc/1xfrtcp

And example code below.和下面的示例代码。

 .navbar > .container { justify-content:center!important; }
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav class="navbar navbar-light bg-light"> <div class="container"> <span class="navbar-brand mb-0 h1"> <i class="bi bi-list-check"></i> Centered Nav Text </span> </div> </nav>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM