Jelbow Jelbow - 7 months ago 14
HTML Question

Vertically center UL and horizontally align LI children

I want my

UL
to do the following things:


  • I want to have my
    UL
    vertically centered in
    Nav
    . I tried using a
    wrapper with
    display: table;
    but that didn't work.

  • I want my
    LI
    's to be evenly spread horizontally across the width of
    the
    UL
    , which I did with
    display: flex;
    just not perfectly.

  • And I need it to be independent from the height because that might change later on.



I have the following code:



nav {
width: 780px;
height: 50px;
text-align: center;
background-color: pink;
}
nav ul {
list-style-type: none;
display: flex;
}
nav ul li {
display: inline-block;
margin: 0 auto;
padding: 10px;
background-color: lightgreen;
}

<nav>
<ul>
<li>sample</li>
<li>sample</li>
<li>sample</li>
</ul>
</nav>





fiddle

I hope you can help me, Thanks in advance.

Answer

Just a bit of tweaking to your flexbox layout:

nav {
  width: 780px;
  height: 50px;
  text-align: center;
  background-color: pink;
}

nav ul {
  height: 100%;                     /* take height of nav parent */
  list-style-type: none;
  padding-left: 0;                  /* remove default UL padding */
  display: flex;
  justify-content: space-around;    /* horizontal alignment (applied to LI) */
  align-items: center;              /* vertical alignment (applied to LI) */
}

nav ul li {
  /* display: inline-block;         <-- not necessary */
  /* margin: 0 auto;                <-- not necessary */
  padding: 10px;
  background-color: lightgreen;
}
<nav>
  <ul>
    <li>sample</li>
    <li>sample</li>
    <li>sample</li>
  </ul>
</nav>

Revised Fiddle

Comments