bjf552
bjf552

Reputation: 11

How to center list items on my nav bar?

new here don't really know a lot about coding yet. Could someone tell me how I could center the list items without messing anything up, thanks.

ul.topnav {
    list-style-type: none;
    margin: 0;
    padding: 15;
    overflow: hidden;
    background-color: #333;
}
ul.topnav li {float: left;}

ul.topnav li a {
    display: inline-block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    transition: 0.3s;
    font-size: 19px;
}
ul.topnav li a:hover {background-color: #555;}

ul.topnav li.icon {display: none;}

Upvotes: 1

Views: 106

Answers (4)

mhSangar
mhSangar

Reputation: 467

You can use display: flex in the nav:

.ul.topnav {
    display:flex;
    justify-content: center;
}

But if you add the HTML, I could help you a bit more.

Upvotes: 1

Anton Koning
Anton Koning

Reputation: 386

Just change ul.topnav li {float: left;} to ul.topnav li {display: inline-block;} and add text-align: center; to ul.topnav. So the stylesheet would look like this:

ul.topnav {
  ...
  text-align: center;
}
ul.topnav li {
  display: inline-block;
}

Upvotes: 2

Lucas Lazaro
Lucas Lazaro

Reputation: 1526

My suggested approach would be to wrap your ul in a <nav> element and then treat the <ul> as a inline-block element. That would give you a nice range of browser compatibility.

You can see the demo on this jsfiddle

But it goes like this:

HTML:

<nav class="navbar">
  <ul class="topnav">
    <li>
      <a href="#">Test</a> 
    </li>
    <li>
      <a href="#">Test</a> 
    </li>
    <li>
      <a href="#">Test</a> 
    </li>
  </ul>  
</nav>

CSS (just the altered part):

.navbar {
  text-align: center;
  width: 100%;
  background-color: #333;
}

ul.topnav {
    display: inline-block;
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

Upvotes: 1

I did not test it , but if It helps...

ul.topnav {
        list-style-type: none;
        margin: 0;
        height:100px;
        overflow: hidden;
        background-color: #333;
    }
    ul.topnav li {float: left; width:auto; height:100%;}

    ul.topnav li a {
        display: inline-block;
        color: #f2f2f2;
        text-align: center;
        line-height:100px;
        text-decoration: none;
        transition: 0.3s;
        font-size: 19px;
        padding-left:10px;
        padding-right:10px;
    }
    ul.topnav li a:hover {background-color: #555;}

    ul.topnav li.icon {display: none;}

Upvotes: 0

Related Questions