user9708733
user9708733

Reputation: 113

How to center list items in flex box navigation bar?

I have the following code:

.flex {
  display: flex;
  background-color: yellow;
  list-style-type: none;
}

.flex > li {
  flex: 1;
  border: 1px solid black;
  align-items: center;
}
<nav>
  <ul class="flex">
    <!--Logo as a link-->
    <li><a href="{% url 'index' %}">Logo</a></li>
    <li><a>REGISTER</a></li>
    <li><a>LOGIN</a></li>
    <!--Search Bar-->
    <li class="search_bar">
      <form method="GET" action="{% url 'search' %}">
        <input name="query" type="text" placeholder="Zip Code or City/Town">
        <button class="btn btn-outline-success text-white my-2 my-sm-0" type="submit"></button>
      </form>
    </li>
  </ul>
</nav>

http://jsfiddle.net/0jh3fud9/2/

How do I center the list items ("LOGO", "REGISTER" "LOGIN", "SEARCH") within the border they are in?

Upvotes: 2

Views: 56

Answers (2)

M&#225;t&#233; Marosi
M&#225;t&#233; Marosi

Reputation: 36

What you should do is declare your elements as a flex container as you've done.

Add the align-items: center; and justify-content: center; properties to them, but you don't really do that here, since there is no space in where you could center anything hence it doesn't know what to center it to.

Remove flex: 1; and I recommend adding padding: 10px; and a margin: 5px; and it should work. If you want them to be close to each other then only add padding.

P.S. you could also use a text-align: center;

Upvotes: 0

Timothy Fisher
Timothy Fisher

Reputation: 1129

Try adding the commented CSS rules to your li elements (see updated fiddle):

.flex > li {
    display: flex; // <-- make flex items
    align-items: center; // <-- center vertically in box
    justify-content: center; // <-- center horizontally in box
    flex: 1;
    border: 1px solid black;
    align-items: center;
}

This will make each of the list items also behave as a flex item and will center them horizontally and vertically in their parent.

Upvotes: 1

Related Questions