Dave Dave - 2 months ago 13
HTML Question

Unable to center text using text-align:center

I don't know if this is because I'm using bootstrap, but I'm having difficulty centering text in my header element. I have

<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<a id="logo" href="#">My Logo Text</a>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
<li><a href="#">Member Currencies</a></li>
</ul>
</nav>
</div>
</header>


and I added this CSS

#logo {
text-align: center;
margin-right: 10px;
font-size: 1.7em;
color: #fff;
text-transform: uppercase;
letter-spacing: 0px;
padding-top: 9px;
font-weight: bold;
}

#logo:hover {
color: #fff;
text-decoration: none;
}


but the logo text is not getting centered, as you can see here -- https://jsfiddle.net/vuout1bj/ . What else do I need to do to center it?

Answer Source

You are centering your text that is inside of your a element. But your a element has a display property of inline. Your text is actually centered, but it's inside of the a element, and the width of your a element is determined by the contents. So the visual effect of what you are trying to achieve is not really visible.

Either put your a element inside a div (div's have a display property of block by default), and give the centering property to that div:

   <header class="navbar navbar-fixed-top navbar-inverse">
  <div class="container">
    <div style='text-align:center;'>
        <a id="logo" href="#">My Logo Text</a>
    </div>
    <nav>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Home</a></li>
        <li><a href="#">Member Currencies</a></li>
      </ul>
    </nav>
  </div>
</header>

Or, just make your a element have the display:block property:

#logo {
  display:block;
  text-align: center;
  margin-right: 10px;
  font-size: 1.7em;
  color: #fff;
  text-transform: uppercase;
  letter-spacing: 0px;
  padding-top: 9px;
  font-weight: bold;
}