Better to center by margin: auto or text-align: center?

1

Looking for good practices in HTML, what is the best way to centralize?

I see that I can centralize the menu of a page by both options, but I am in doubt as to the best form and also of which is the correct form instead of just using one that works being wrong in some cases. p>

Let's look at 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 centralize the menu by margin: auto; when I define a width of the menu class and this in some cases can cause me to have problems when the items exceed this size, just change the width: 200px; to width: 100px; that the items stay overlapping others.

Now when I define the menu class without width, I can centralize the menu by setting a text-align: center; in the upper tag selector, which in this case is the #container id. Doing this I can solve the problem of the amount of items in the list that can change and up to different sizes depending on the changes you have to make, but I still wonder if this is the correct way to do the alignment in the center. p>

* { 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>
    
asked by anonymous 28.12.2016 / 02:33

1 answer

1

According to W3C

  

The CSS margin properties are used to generate space around elements.    Follow the link

That is, the function of the "margin" property is to define space around the elements.

The "text-align" property:

  

The text-align property specifies the horizontal alignment of text in   an element.    Follow the link

In short, it serves to align text horizontally.

Good practice is to use a feature according to its function. If your goal is to center text. You should use "text-algin". Otherwise, use "margin".

    
28.12.2016 / 02:47