Search code examples
htmlcssflexboxhtml-lists

Does flexbox work differently with items in an unordered list?


I am trying to learn how to use flexbox and I am struggling with using it properly with an unordered list. I want the items inside to "spread out" in the container, but no matter what flex properties I apply they don't seem to work. Code below.

Why aren't the list items speading out within the container? All boxes, borders, and colors are for my own visual repesentation.

body {
  background-color: black;
  box-sizing: border-box;
}

header {
  display: flex;
  background-color: white;
  justify-content: space-between;
  align-items: center;
}

h1 {
  color: white;
  background-color: blue;
}

ul {
  background-color: blue;
  display: flex;
  list-style: none;
  justify-content: space-evenly;
}

li {
  border: 1px solid red;
}
<header>
  <div>
    <h1>Sample Logo</h1>
  </div>
  <div>
    <nav class="navbar">
      <ul>
        <li>Home</li>
        <li>Contacts</li>
        <li>Companies</li>
        <li>Calendar</li>
      </ul>
    </nav>
  </div>
</header>


Solution

  • the ul has padding. add some width to ul and the spacing will work

    body {
      background-color: black;
      box-sizing: border-box;
    }
    
    header {
      display: flex;
      background-color: white;
      justify-content: space-between;
      align-items: center;
    }
    
    h1 {
      color: white;
      background-color: blue;
    }
    
    ul {
      border:solid 1px black;
      display: flex;
      width:50vw;
      
      list-style: none;
      justify-content: space-between;
    }
    
    li {
      border: 1px solid red;
    }
    <header>
      <div>
        <h1>Sample Logo</h1>
      </div>
      <div>
        <nav class="navbar">
          <ul>
            <li>Home</li>
            <li>Contacts</li>
            <li>Companies</li>
            <li>Calendar</li>
          </ul>
        </nav>
      </div>
    </header>