0

I'm trying to center a navigation bar on my website. The difficulty I am having is that I do not want the navigation bar's width to take up the entire page width and I want the position of the navigation bar to be fixed.

Here's a very simple example of what I'm trying to do: https://jsfiddle.net/de83m2zL/51/

As you can see, the navigation bar is only part of the page width, but isn't centered. My question is, how can I make it centered?

div#navbar {
  position: fixed;
  margin: 0 auto;
  width: 80%;
  background-color: #0050ca;
}

div ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

div ul li {
  display: inline-block;
  margin-right: 10px;
}

div ul li a {
  color: white;
}

h1 {
  margin-top: 40px;
}
<div id="navbar">
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/">About</a></li>
    <li><a href="/">Blog</a></li>
  </ul>
</div>

<br>

<h1>
  Hello!
</h1>
Gravitron
  • 21
  • 4

2 Answers2

2
div#navbar {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  margin: 0 auto;
  width: 80%;
  background-color: #0050ca;
}

You can position it at 50% of the screen using left: 50% and then

translate the whole element of -50% of its own width using transform: translateX(-50%)


Note: You can check this answer to have a pictured view of how it works.

Wax
  • 605
  • 1
  • 5
  • 15
  • Thanks! It works, but I'm a little curious — if I'm just positioning the element 50% to the left and then moving it back, why is the outcome different from not positioning it at all? – Gravitron Mar 15 '20 at 22:45
  • 1
    `left: 50%` position the element to 50% of the width of the screen and `transform: translateX(-50%)` just slide the element to 50% of the element width (its screen width vs element width) – j3ff Mar 15 '20 at 22:53
  • 1
    @Gravitron I edited my answer to make it clearer. – Wax Mar 15 '20 at 22:53
1

Not completely sure what you want to center, but:

1.) If you want to center the li items inside the (blue) ul , use text-align-center; on the ul

2.) If you want to center the fixed, 80% wide ul on the page, use left and right margins of 10% (= half of 100% page width minus 80% width of ul):

div#navbar {
  position: fixed;
  margin: 0 10%;
  width: 80%;
  background-color: #0050ca;
  
}

div ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  text-align: center;
}

div ul li {
  display: inline-block;
  margin-right: 10px;
}

div ul li a{
  color: white;
}

h1 {
  margin-top: 40px;
}
<div id="navbar">
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/">About</a></li>
    <li><a href="/">Blog</a></li>
  </ul>
</div>

<br>

<h1>
Hello!
</h1>
Johannes
  • 64,305
  • 18
  • 73
  • 130