Search code examples
htmlcss

How to use HTML and CSS only to center multiple divs


I am trying to build a navigation bar, but I cannot properly center my text, even when using text-align: center. I can't find a way to find out the exact values in pixels that I would need for margin and padding without using JavaScript, but I don't want to do that. I am trying everything that I can to find out how I can use CSS and HTML to solve this problem.

body {
  /* Getting rid of the default margins on the webpage */
  margin: 0px;
  
}

#navigation {
  /* Make the header visible for testing purposes */
  background-color: pink;

  /* Center the header, change size */
  margin: 0px auto;
  width: 500px;
}

ul {
  /* Align the text withing the div for functionality purposes */
  text-align: center;

  /* Get rid of the bullet points and style the list */
  list-style-type: none;
}

li {
  background-color: rgb(63, 76, 217);

  /* Display as block elements >> we don't want the links of the navbar to stack */
  display: inline-block;
  padding: 5px;
}
<header id="navigation">
  <ul>
    <li><a href="#">About Us</a></li>
    <li><a href="#">Students</a></li>
    <li><a href="#">Administration</a></li>
    <li><a href="#">Teachers</a></li>
    <li><a href="#">Sign Up</a></li>
  </ul>
</header>

Here is an image of my result...

Image of navigation bar

I am trying to avoid using flex or grid, just basic CSS and HTML to further my learning.

I have tried several other methods found on this site, but it hasn't got too well.


Solution

  • As far as centering the element is concerned without flex/grid, you're almost there.

    You just needed to reset the margin and padding of all elements using * element not body in css.

    * {
      /* Getting rid of the default margins on the webpage */
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: sans-serif;
    }
    
    #navigation {
      /* Make the header visible for testing purposes */
      background-color: pink;
    
      /* Center the header, change size */
      margin: 0px auto;
      width: 500px;
    }
    
    ul {
      /* Align the text withing the div for functionality purposes */
      text-align: center;
    
      /* Get rid of the bullet points and style the list */
      list-style-type: none;
    }
    
    li {
      background-color: rgb(63, 76, 217);
    
      /* Display as block elements >> we don't want the links of the navbar to stack */
      display: inline-block;
      padding: 5px;
    }
    <header id="navigation">
      <ul>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Students</a></li>
        <li><a href="#">Administration</a></li>
        <li><a href="#">Teachers</a></li>
        <li><a href="#">Sign Up</a></li>
      </ul>
    </header>