Search code examples
htmlcsscentering

Centering an <li> element without taking bullet point into account


I am unsure on how to center my li elements in the light green space, just based off the green squares I've created around them. As of right now CSS is including the space taken up by the bullet points when centering, which I do not want.

#square {
  position: fixed;
  width: 350px;
  height: 100%;
  top: 0px;
  left: 0px;
  background-color: rgb(230, 255, 230);
}

ul {
  position: relative;
  bottom: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

li {
  margin-top: 40px;
  padding-left: 75px;
  border-color: white;
  border-width: 2px;
  border-style: solid;
  padding: 5px 20px 5px 20px;
  background-color: green;
  border-radius: 10px;
  width: 100px;
  text-align: center;
}

.navlink {
  text-decoration: none;
  color: white;
}
<div id="square">
  <ul>
    <li><a class="navlink" href="#">Introduction</a></li>
    <li><a class="navlink" href="#">Middle</a></li>
    <li><a class="navlink" href="#">End</a></li>
  </ul>
</div>

I've tried applying list-style-type: none; to ul, however this just hides the bullet points, the space they take up is still there.


Solution

  • It is not actually the space taken up by the bullet points - ul elements have a default padding-left - just reset it to zero:

    Ideally you should just reset the padding instead of negative margins - see demo below:

    #square {
      position: fixed;
      width: 350px;
      height: 100%;
      top: 0px;
      left: 0px;
      background-color: rgb(230, 255, 230);
    }
    
    ul {
      position: relative;
      bottom: 30px;
      display: flex;
      flex-direction: column;
      align-items: center;
      list-style-type: none; /* hide bullet points */
      padding-left: 0; /* ADDED */
    }
    
    li {
      margin-top: 40px;
      padding-left: 75px;
      border-color: white;
      border-width: 2px;
      border-style: solid;
      padding: 5px 20px 5px 20px;
      background-color: green;
      border-radius: 10px;
      width: 100px;
      text-align: center;
    }
    
    .navlink {
      text-decoration: none;
      color: white;
    }
    <div id="square">
      <ul>
        <li><a class="navlink" href="#">Introduction</a></li>
        <li><a class="navlink" href="#">Middle</a></li>
        <li><a class="navlink" href="#">End</a></li>
      </ul>
    </div>