简体   繁体   中英

Vertically align fontawesome icon with text in navbar

I'm trying to vertically align a fontawesome icon with some text in a navbar from bootstrap. The vertical size of the navbar is set to 10vh . I'm not able to get the text aligned with the icon, it appears like in the below image:

未对齐的文本

Also I would like to add some horizontal space between the icon and the text. Here is my code:

  <nav class="navbar navbar-expand-lg sticky-top navbar-dark bg-dark h-100">
    <ul class="navbar-nav nav-fill w-100">
      <li class="nav-item active">
        <a class="nav-link d-flex align-items-center justify-content-center" href="#">
          <i class="fa fa-home fa-2x icon-white"></i>
          <p>Home</p><!--<span class="sr-only">(current)</span>-->
        </a>
      </li>
      ... (some more li)
    </ul>
  </nav>

I've also tried to put the icon inside the paragraph, placing the a element inside a div , and setting both of the same font-size, but I cannot make it work.

Try the following code, it worked for me:

<nav class="navbar navbar-expand-lg sticky-top navbar-dark bg-dark h-100">
    <ul class="navbar-nav nav-fill w-100">
      <li class="nav-item active">
        <a class="nav-link" style="display: flex; align-items: center;" href="#">
          <i class="fa fa-home fa-2x icon-white"></i>
          <p style="margin-left: 12px;">Home</p>
        </a>
      </li>
      ... (some more li)
    </ul>
  </nav>

Also, here I'm giving the space between the text and the icon as 12px, you can change this according to your need.

You should make the

tag a flex container with height 100% (obviously after setting position: relative. Then you can easily do justify-content: center; and align-items: center;

For any other HTML and CSS noob like me, it seems that p elements have margin by default. I have seen this question where it says that CSS 2.1 specification has a default style sheet for basic elements. Removing the bottom margin of the p element made it aligned with the icon.

Regarding horizontal space, DIVYIA BAID 's suggestion to set a left margin is exactly what I was looking for.

it's very simple

Try This code for best alignment for Fontawesome or any other icon

<li styles="display:flex">
   <a href="#" role="button" data-haspopup="true" aria-expanded="false">Home</a>
   <i class="fal fa-home" style="vertical-align: middle;margin: auto;"></i>
</li>

Wrap the content in a flex container and then align items center to horizontally align them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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