1
Searching for good HTML practices, what is the best way to centralize?
I see that I can center the menu of a page for both options, but I wonder which is the best way and also which is the right way instead of just using one that works being wrong in some cases.
Let’s see the following code:
* { margin: 0; padding: 0; }
#container { background-color: lightblue;
height: 200px; }
.menu { list-style: none;
margin: auto;
width: 200px; }
.menu-item { display: inline-block; }
a { padding: 10px;
background-color: green; }
<div id="container">
<ul class="menu">
<li class="menu-item"><a href="">Home</a></li>
<li class="menu-item"><a href="">Work</a></li>
<li class="menu-item"><a href="">Contact</a></li>
</ul>
</div>
I can only center the menu by margin: auto;
when I set a menu class width and this in some cases can make me have problems when the items exceed that size, just change the width: 200px;
for width: 100px;
that the items are overlapping other.
When I define the menu class without width I can center the menu by setting a text-align: center;
at the top tag selector, which in this case is id #container
. By doing this I can solve the problem of the number of items on the list that can change and even be of different sizes depending on the modifications you need to make, but I still wonder if this is the right way to do the alignment in the center.
* { margin: 0; padding: 0; }
#container { background-color: lightblue;
height: 200px;
text-align: center; } /* adicionado */
.menu { list-style: none;}
/* removido width: 200px e margin: auto */
.menu-item { display: inline-block; }
a { padding: 10px;
background-color: green; }
<div id="container">
<ul class="menu">
<li class="menu-item"><a href="">Home</a></li>
<li class="menu-item"><a href="">Work</a></li>
<li class="menu-item"><a href="">Contact</a></li>
</ul>
</div>